Josh
Josh

Reputation: 878

How to synchronize data between multiple clients on Node.js Server

The following diagram is a basic representation of a web application I am creating.

Node.js Web Application Schematic

The basic operation of the application is as follows:

  1. Client sends request for data from node.js server
  2. Server receives request.
  3. Server fetches data from database.
  4. Server sends data back to client as JSON string.
  5. Client receives data stores it as a JSON object and binds it to a table.

This all works fine. The problem I am having is best represented by the following situation.

  1. Clients 1 to 4 all complete the steps above (i.e. all have an table of data binded to a JSON object).
  2. Client 1 now sends an update request to the server.
  3. Server receives request.
  4. Server updates database.
  5. Server sends response to client 1 indicating successful operation and updates JSON object binded to table.
  6. THE PROBLEM JSON data shown on clients 2 to 4 is now no longer in sync with the database.

So my question is how do I keep the JSON data on all 4 (or more) of my clients in real-time sync with the database on my Node.js server?

Upvotes: 8

Views: 17298

Answers (3)

dlq
dlq

Reputation: 3219

I think the best way to do this in 2021 is with server-sent events. Your backend can emit a server-sent event to all other clients every time it receives data. SSEs are basically downstream unidirectional events, and browsers can listen for them the same way they can listen to a websocket.

The clients will then only be out of sync with respect to network latency, which is unavoidable.

The only problem with SSEs in my opinion is that they have lower browser compatibility, so it'll break IE 11 support.

Upvotes: 2

Facundo La Rocca
Facundo La Rocca

Reputation: 3866

Briefly, what you need is to notify clients when something has changed. Try looking for websockets, there are lots of good tutorial on the web. Basicaly, a websocket is a communication channel between server and clients., what you should do is to send a notification to the client about what has changed, then each client should determine if it has to update something (and request the information) or not.

Take a look a this lib:https://www.npmjs.com/package/websocket

I think it is one of the best (if it is not the best) and you will even find examples and demos.

Upvotes: 4

saille
saille

Reputation: 9181

If you are open to taking on a full-stack framework, Meteor does everything you need to keep all your client views in sync with changes.

Meteor is a huge dependency to take on - it has opinions about your technology choices at every layer in your stack - so its not going to be for everyone, but if you want quick results it is hard to beat.

Upvotes: 0

Related Questions