Real-Time Systems with WebSockets and Redis | Intway
Tecnologías / Real-Time Systems with WebSockets and Redis

Real-time systems: screens that update themselves

· upd.

Screens that update themselves: WebSockets for the connection and Redis to share updates and run queues.

WebSockets · Socket.IORedis · BullMQNestJS · Next.js · React NativeSeveral servers

We build real-time systems: screens that update themselves when something changes, without anyone pressing «refresh». The dispatch board that sees a work order close as it happens, the progress bar of an export with thousands of rows, the alert for a new order or a chat with a customer. We use WebSockets for the open connection between the server and each screen, and Redis to share updates between servers and line up long jobs in queues. It's part of our Next.js and NestJS development; this page covers it in depth.

What real time means in a business system

In a business system, real time means the change reaches the screen without reloading, within the time that screen can wait: on a dispatch board, for example, under a second. It isn't the stock market or a video game, where milliseconds count: it's the dispatcher not assigning a work order that someone else already closed, the supervisor seeing clock-ins as they arrive and whoever started a long process knowing how much is left. The rule we follow: the database is the source of truth; the live connection only announces the change. Every change is saved to the database first and only then is the update sent. If an update is lost, the screen gets it back from the database; never the other way round.

WebSockets, SSE or polling

There are three ways for a screen to learn about a change, and the newest one doesn't always win. A WebSocket keeps a connection open in both directions; Server-Sent Events (SSE) are a one-way connection, from the server to the screen, that reconnects on its own; and polling means asking the server every few seconds whether there is anything new.

NeedWebSocketsSSEPolling
A board that changes several times a minuteWorksWorksArrives late and loads the server
A chat or a screen where both sides writeIts typical useWorks, with a separate request to sendThe delay shows
Progress of a long processWorksWorks, and it's simplerEnough if every 5 or 10 seconds
Data that changes a few times an hourMore than neededMore than neededEnough

We choose per screen, not per system: the same system can have a live board and the rest of its screens with no open connection. One detail that matters: without HTTP/2, browsers allow only a few SSE connections at once (six per domain, across all tabs).

What Redis does in a real-time system

  • Sharing updates between servers. With several API instances, each screen is connected to only one. Redis Pub/Sub carries the update to all of them, and each delivers it to its own screens.
  • Keeping what can't be lost. Pub/Sub delivers each message once or not at all: if a subscriber is down, the message is lost. When that is not acceptable we use Redis Streams, which stores messages: each consumer group tracks what was delivered and what is still unacknowledged, and unacknowledged entries are claimed and processed again. So every process has to tolerate a repeated message, and how much is kept depends on the persistence and trimming you configure.
  • Queues for long work. An export, a bulk send or a recalculation go into a queue (BullMQ on Redis, or Amazon SQS when the system runs on AWS), configured with retries and backoff, and publish their progress while they run.
  • Presence. Who is connected right now. API caching and rate limits are covered in Next.js and NestJS development.

How we build it

The code and images on this page are architecture examples, not a specific project.

One update per change, with a version

When a work order changes, the API saves it to PostgreSQL and emits an update to that company's room with the identifier, the order's version and the new status. The screen applies the change only if the version is newer than the one it has, so a repeated or out-of-order update doesn't break it. In NestJS we do this with WebSocket gateways on Socket.IO, and each screen joins only the rooms it is allowed to see.

Real-time system: a dispatch board that updates itself when a technician closes a work order from the phone
The technician closes it, the board updates itselfExample: the technician closes the work order on the phone, the API saves it and the dispatch board shows it closed at once.

Several servers

With more than one API server, each screen is connected to only one. The Redis adapter carries every update to all of them, so it reaches the screens in that room while Redis is available. Socket.IO starts each connection with HTTP requests and then tries to upgrade to WebSocket, so with several servers there are two options: either the load balancer always sends each screen to the same server (sticky sessions), or the connection opens straight over WebSocket. For what was missed during an outage we don't use Socket.IO's automatic recovery: it doesn't work with the Redis Pub/Sub adapter and it restores rooms before permissions are checked. The screen asks the API, which checks the current permissions.

Long processes with live progress

Anything that takes more than a few seconds isn't done while the screen waits. It goes into a queue, a separate process runs it and publishes its progress, and the screen shows it. If the user closes the screen, the job keeps going; when they come back, they see where it is. If it fails, it retries and carries on with what isn't recorded as done. So that an outage right after sending something doesn't duplicate it, every send carries a unique key the provider uses to drop repeats.

Long process on a queue: an export of thousands of rows with a live progress bar and retries
The job runs in the queue, the screen sees the progressExample: each batch is saved before moving on; if it fails, the retry starts at the first batch not recorded as saved.

Reconnection and phones without signal

Connections drop: a lift, a basement, switching from Wi-Fi to mobile data. Socket.IO sends a heartbeat every 25 seconds to detect a dead connection, which also stops the load balancer from closing it as idle (on AWS, the Application Load Balancer does so after 60 seconds without data, by default). On reconnecting, the screen asks the API for what changed since the last change it saw, using a sequence number that follows the order in which changes were committed, and checks again every so often, one request at a time, even while the connection stays open: an update can be lost if Redis drops. On top of that, the update is saved in the same transaction as the change, and a separate process sends it and retries if it fails. On the phone, whatever the technician did offline is sent later through its local queue, as we explain in React Native development.

Best practices for real-time systems

These are the rules we work by. The number of connections, the acceptable delay and the load and outage tests are agreed with you for each system and verified before go-live.

Security

  • wss:// only, never unencrypted ws://, and every connection's origin checked against the list of our own sites, as the OWASP guide recommends. The session cookie isn't enough: depending on its settings, the browser may send it even when another site opens the connection, and WebSocket has no CORS to stop it.
  • A token when the connection opens, checked before the first message is accepted on every connection, including those with no origin (a native app doesn't send one). The connection is closed when the token expires, when the user logs out or when they lose the permission. Whatever was missed during an outage is requested from the API, which checks the current permissions.
  • Every action is authorized on the server, not just joining the room: nobody sees or changes another company's data because the screen asks to.
  • Every incoming message is validated like the body of an HTTP request, with a message limit per user.
  • Redis on a private network, with authentication and TLS: whoever reaches Redis can read and inject updates.

Scale

  • The Redis adapter from the first instance: adding servers doesn't change the code, only the load balancer settings.
  • Rooms per company and per screen: every update reaches only whoever needs to see it.
  • The live connection opens only on the screens that use it, not across the whole site.

Reliability

  • Acknowledgements with a timeout for what the screen sends: if the server doesn't answer, the screen says so.
  • A unique identifier per operation, so a retry never applies it twice.
  • Redis Streams or the database when a message can't be lost; Pub/Sub only for updates that can be recovered.

Monitoring and testing

  • Open connections, messages per second, delivery delay and reconnections, with alarms.
  • End-to-end tests with two browsers: what one changes, the other sees.
  • A load test with the agreed number of connections before go-live, and a deliberate Redis outage to check the system recovers.

Real cases

The cases don't detail the technology behind the live part: this is what had to stay up to date in each one.

Starting pointWhat had to stay up to dateCase
More than 300 companies; more than 5,000 employees clock in on tablets and phonesClock-ins appear on the web dashboard's timesheets as soon as they arrive; pay is calculated at period closeSee the case
34 HVAC technicians who closed their visits on paperThe dispatch panel shows the whole day and which technicians are offline right nowSee the case
A regional Visual Basic and ASP Classic payroll engine that required Internet ExplorerLong calculations go to an Amazon SQS queue: they keep running on AWS even if the screen is closed, and the app restores its state on returnSee the case

How much does a real-time system cost?

It depends on how many screens need to be live, how many people are connected at once, whether a lost message is a problem or just a delay, how many servers are needed and whether there are phones working offline. It almost always pays to start with the screen where delay costs money (the dispatch board, the progress of a process) and leave the rest as it is. How we put the number together is in how to estimate a software project, and for your system, get in touch.

Common mistakes

  • Sending the update before saving. If the database fails, the screen shows something that didn't happen.
  • Using Pub/Sub for what can't be lost. If the server was restarting, the message is gone.
  • A single instance with no adapter. It works until the second server is added and some of the screens stop hearing about changes.
  • Checking permissions only on connect. Rooms and every action are authorized on the server, and the connection is closed when the token expires or permissions change.
  • Not asking for what was missed on reconnect. The screen goes stale and nobody notices.
  • WebSockets across the whole system. A screen that changes twice a day doesn't need an open connection.

If the system grows into separate services, see also microservices, and to run it in the cloud, AWS development and architecture.

Real-time system with WebSockets and Redis: a dispatch board that updates itself

How we build real-time systems

What makes each change reach every screen, on time and only the right ones.

Real-time dispatch board showing each work order's version

Screens that update themselves

The change arrives without reloading.

Ver más →
Three screens connected to different servers receiving the same update

Several servers, one update

Redis shares updates across instances.

Ver más →
Bulk invoice send with a live progress bar from a queue

Long processes with live progress

A queue with retries and the screen kept informed.

Ver más →
Tablet in a service van reconnecting and catching up on the changes

Reconnecting and catching up

When the signal returns, the screen catches up.

Ver más →
Security panel of real-time connections with rejections by origin and permission

Security and room permissions

Each user sees only what's theirs.

Ver más →
What we solve

What we solve with real time

What goes wrong when a screen shows stale data or misses a change.

Screens you have to reload

The dispatcher assigns a work order someone else already closed because the board didn't update.

Processes that don't say how long is left

A large export is started and nobody knows whether it's halfway or stuck.

Updates lost when scaling

With the second server, half the screens stop hearing about changes.

Outages that leave the screen stale

The signal drops, comes back, and the screen still shows the old data.

How we work

How we work

1

Discovery

Which screens need to be live, how many people connect and what can't be lost.

2

Technical decision

WebSockets, SSE or polling, screen by screen, and what Redis does.

3

First live screen

The one that costs most when it's late, tested under load and with outages.

4

Operations

Monitoring connections and delays, and more servers when needed.

25+
Years building software
500+
Projects
300+
Companies see clock-ins as they arrive
10,000+
Users on the time-and-attendance platform
FAQ
What is a real-time system?

In a business system, it's one where a change reaches the screen without reloading, within the time that screen can wait (on a board, under a second): the board that sees a work order close, the progress of a long process or a chat. It isn't the same as stock-exchange or industrial control systems, where milliseconds count.

WebSockets or Server-Sent Events?

WebSockets when both sides send messages often, like a chat or a collaboration screen. Server-Sent Events when only the server notifies, like the progress of a process: it's simpler and reconnects on its own. And if the data changes a few times an hour, polling is enough.

What is Redis used for in a real-time system?

To share updates across several servers, to keep messages that can't be lost (Redis Streams), for long-job queues with BullMQ and to know who is connected.

Are messages lost if the connection drops?

Redis Pub/Sub delivers each message once or not at all: if the receiver was down, it's lost. That's why every change is saved to the database first and, on reconnecting, the screen asks for what changed since the last change it saw. For what can't be lost we use Redis Streams.

Does it scale to thousands of connected users?

It scales by adding API instances with the Redis adapter, which shares updates across all of them, and with the load balancer set up for live connections. Capacity is a goal, not something the adapter gives you: the number of connections is agreed for each system and, before go-live, tested under load and with a deliberate Redis outage.

How much does a real-time system cost?

It depends on how many screens need to be live, how many people connect at once, whether a lost message is a problem and how many servers are needed. It pays to start with the screen where delay costs money; we quote it after a first conversation.

Let's talk about your system

Tell us which screen is always behind and we'll show you how to keep it up to date on its own.

Contact us