javascriptjsonnode.jsdata-synchronization

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?


Solution

  • 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.