ISPEAKCODE.COM

TALK · MONGODB USER GROUP BENGALURU · AUG 2024

Harnessing Real-Time Superpowers

MongoDB change streams: subscribe to inserts, updates and deletes the moment they happen, instead of polling and hoping. The demo from the meetup is rebuilt as a playground you can drive.

34 SLIDES CHANGE STREAMS LIVE PLAYGROUND
Jump to the playground
Nabil presenting Harnessing Real-Time Superpowers at the NammaMUG meetup: the title slide is on the screen behind him and an audience of about twenty people sits in rows of office chairs.
On stage at NammaMUG
Event poster: NammaMUG Meetup, Let's Meet and Master in Building Scalable Applications, Vector Search and Change Streams. Saturday 24 August, 10 AM to 2 PM IST, at Contentstack, WeWork Roshini Tech Hub, Marathahalli, Bengaluru. Speakers Murugavel Natarajan, Saqib Suban, Naveen Kumar, Nabil Nalakath and Darshan Jayarama. MongoDB User Group Bengaluru with Contentstack.
The event poster

THE MEETUP

NammaMUG: building scalable applications, vector search & change streams

When
Sat 24 Aug 2024 · 10:00–14:00 IST
Where
Contentstack, WeWork Roshini Tech Hub, Marathahalli, Bengaluru
Hosts
MongoDB User Group Bengaluru with Contentstack
01

MONGODB CHANGE STREAMS

Harnessing real-time superpowers

02

PART 1

Tracking changes to data

03

Write separate logic for every CRUD operation

04

Risk of missed updates due to complex logic

05

Frequent database polling to check for changes

06

Hard to maintain as the application grows

07

PART 2

What are MongoDB change streams?

08

Change streams let applications subscribe to real-time changes in your database

09

React immediately to database changes such as inserts, updates and deletes

10

PART 3

Why change streams?

11

Real-time data processing is critical for user engagement, system monitoring and data consistency

12

Ideal for building reactive applications where real-time data is essential

13

Easier to build live dashboards, real-time notifications and event-driven architecture

14Surprised Pikachu meme: 'When you realize you can react to database changes in real time.'
15

PART 4

Setting up change streams

16

Watch a collection

NODE.JS DRIVERTry it ↓
const changeStream = db.collection('orders').watch();
changeStream.on('change', (change) => {
  console.log('Change detected:', change);
});
17

Filtering changes

NODE.JS DRIVERTry it ↓
const pipeline = [
  { $match: { 'fullDocument.status': 'shipped' } }
];
const changeStream = db.collection('orders').watch(pipeline);

The catch. Update events only carry fullDocument if you ask for it, so this filter never sees an order becoming shipped. Pass { fullDocument: 'updateLookup' } to watch(), or match on updateDescription.updatedFields.status. The playground lets you flip it and watch the events disappear and come back.

18

Handling change stream events

A CHANGE EVENT
{
  "operationType": "insert",
  "fullDocument": { /* ... */ },
  "ns": { "db": "test", "coll": "orders" },
  "documentKey": { "_id": ObjectId("...") }
}
19

Reacting to events

NODE.JS DRIVER
changeStream.on('change', (change) => {
  if (change.operationType === 'insert') {
    // Perform an action on insert
  }
});
20

PART 5

Resume tokens

21

Every change event comes with a resume token

22

Resume the change stream exactly where it left off using that token

23

Resume after a disconnect

NODE.JS DRIVERTry it ↓
const resumedStream = collection.watch([], { resumeAfter: savedToken });
24Drake meme: rejecting 'relying on polling and hoping nothing breaks', approving 'resuming exactly where you left off with resume tokens'.
25

PART 6

Real-world use cases

26
  • 01Real-time order tracking in e-commerce
  • 02Alerts on data changes, like new messages in a chat app
  • 03Syncing data across microservices in a distributed system
  • 04Keeping a Redis cache in sync with MongoDB
  • 05Audit trails for security and compliance: who did what, and when
  • 06Syncing many sites into a central data lake for analytics
27Expanding brain meme: checking database changes once a day; polling every 5 minutes; using triggers for specific changes; subscribing to real-time change streams.
28Diagram: three local sites, each running MongoDB, stream data into MongoDB Atlas; the combined data feeds Cloud Metabase dashboards that users access.
Three sites stream their changes into one Atlas cluster, which feeds the dashboards.
29

PART 7

Best practices

30
  • 01Limit the scope to only the events you need
  • 02Store and manage resume tokens safely to prevent data loss
  • 03Monitor performance and adjust the configuration as you go
31Distracted boyfriend meme: the developer turns away from 'polling for changes' to look at 'change streams'.
32

DEMO

The playground

Demo gods meme: a child praying, 'Demo gods, have mercy.'

An orders collection, a change stream and a 5-second poller, all simulated in your browser. Nothing touches a real database; the events follow MongoDB's change event format.

db.orders
    watch() options
    CHANGE STREAM · LISTENING0 events
      POLLING EVERY 5 Snext poll in 5 s

        Insert an order, then click its status twice quickly. The change stream logs every step; the poller only sees where it ended up.

        33

        Questions?

        34

        Thank you