0

I have React web application and REST API (Express.js).

I found that usage of EventStream is better choice if you do not want to use long-polling or sockets (no need to send data client->server).

Usecase:

  1. User opens page where is empty table where other users can add data by POST /data.
  2. This table is filled with initial data from API by GET /data.
  3. Then page is connected to EventStream on /data/stream and listen for updates
  4. Someone add new row and table needs to be updated...

Is possible to broadcast this change (new row added) from backend (controller for adding rows) to all users what are connected to /data/stream?

Baterka
  • 3,075
  • 5
  • 31
  • 60

2 Answers2

1

It is generally not good practice to have a fetch for the initial data, then a separate live stream for updates. That's because there is a window where data can arrive on the server between the initial fetch and the live update stream.

Usually, that means you either miss messages or you get duplicates that are published to both. You can eliminate duplicates by tracking some kind of id or sequence number, but that means additional coding and computation.

SSE can be used for both the initial fetch and the live updates on a single stream, avoiding the aforementioned sync challenges.

The client creates an EventSource to initiate an SSE stream. The server responds with the data that is already there, and thereafter publishes any new data that arrives on the server.

If you want, the server can include an event-id with each message. Then if a client becomes disconnected, the SSE client will automatically reconnect with the last-event-id, and the data flow resumes from where it left off. On the client-side, the auto-reconnect and resume from last-event-id is automatic as it is spec-ed by the standard. The developer doesn't have to do anything.

SSE is kind of like a HTTP / REST / XHR request that stays open and continues to stream data, so you get the best of both worlds. The API is lightweight, easy to understand, and standards-based.

Robin Zimmermann
  • 3,441
  • 1
  • 22
  • 15
0

I will try to answer myself :)

I never thought I can use just whatever pub/sub system on backend. Every user what connects to stream (/data/stream) gets subscribed and server will just publish when receive new row from POST /data

Baterka
  • 3,075
  • 5
  • 31
  • 60