Realtime Updates WIth Mongodb

R

What do we mean by a real-time database?
As the name suggests if we get updates from our database as soon as they occur, ie, in real-time, we call it a real-time database. The data with clients are in constant sync with the database.

What are some use cases for real-time updates?
– Real-Time Notifications
– Real-Time Analytics
– Event-Driven Architecture
– Reactive Systems etc

Generally, to get data we make an http request (xhr/fetch) to our server, and receive the required resource, this is called AJAX polling. So to keep our data updated the client will keep making requests and checking if the data has changed.

With this method setting up a connection and tearing it down takes up a lot of our time and resources. To avoid this repetitive connection setup, Web sockets keep a two-way connection open between the client and server. Thus the server can communicate as soon as there is a change in the database, making real-time updates possible.

Using WebSockets and pushing updates from the backend using socket.io/pusher etc is one approach to tracking real-time updates, but there is a shift now towards subscribing to changes at the database itself.

When we think of real-time databases we think of Firebase
Instead of typical HTTP requests, the Firebase Realtime Database uses data synchronization—every time data changes, any connected device receives that update within milliseconds.

We can also achieve real-time subscription with MongoDb change streams :
Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment.
The absence of native triggers in MongoDb can be overcome with change streams. MongoDb change streams let applications get instant updates on CRUD operations happening in the database. Change stream uses the replication process of mongoDb, and provides an API for external applications to give real-time functionality to our database. And we can forward our updates to the frontend from the backend via something like socket.io.

We can use our mongodb real-time application in multiple use cases like replicating the data into a downstream system, sending an email notification, etc while also retaining the benefits that come with using mongoDb as our database.

About the author

Somya Jain
By Somya Jain

Category