Skip to content

No. 59Backend8 min read2,059 words

How to build a real-time app: WebSockets, SSE and scaling

How to build a real-time app that stays correct: WebSockets vs SSE vs polling, reconnection and replay, ordering, conflicts, fan-out and the stack we use.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways · 05

The short version

  1. 01Choose the transport by direction: Server-Sent Events for mostly one-way updates, WebSockets for two-way conversations like chat and collaboration, and polling when updates are infrequent.
  2. 02The core real-time loop is: client sends an action, the server validates and persists it, then broadcasts the result. Get that loop correct before adding presence, cursors or offline support.
  3. 03Give every message a per-channel sequence number so reconnecting clients can ask for everything after the last one they saw. Without a replay path, dropped connections cause silent data loss.
  4. 04Start with last-write-wins for conflicts. Reach for CRDTs or operational transforms only when people genuinely edit the same text at the same time.
  5. 05Once you run more than one server, you need a pub/sub backbone for fan-out. Redis pub/sub is at-most-once, so treat the database as the source of truth and pub/sub as a notification.
On this page · 13

To build a real-time app, pick the transport that matches the direction of your data (Server-Sent Events for server-to-client updates, WebSockets for two-way conversation), persist every change to a database before broadcasting it, and give each message a sequence number so reconnecting clients can catch up. Add pub/sub for fan-out when you run more than one server, and leave CRDTs, presence and offline support until the product needs them.

Real-time looks like magic until you build it. A cursor moving on someone else's screen, a message landing the instant it is sent, a dashboard updating without a refresh. The demo is easy. Keeping it correct when the network drops, two people edit the same thing or thousands of users connect at once is the hard part. This guide is about that hard part.

What a real-time app is, and which kind you are building

A real-time app pushes updates to users when something changes, instead of waiting for them to ask. There are four common shapes, and the shape decides almost everything else:

ShapeExamplesData directionHardest problem
Chat and messagingSupport chat, team messaging, commentsTwo-wayOrdering, delivery and history
CollaborationShared documents, boards, spreadsheetsTwo-way, high frequencyConflict resolution
Live dashboards and feedsOrder tracking, metrics, notificationsMostly server to clientKeeping data fresh without overload
PresenceWho is online, typing indicators, cursorsTwo-way, very frequentFan-out at scale and stale "ghost" users

The first useful question is not "WebSockets or not?" It is: how wrong can an update be, and for how long, before a user notices or is harmed? A trading screen and a typing indicator have very different answers, and that tolerance is what justifies the engineering.

The real-time MVP: what to build first

The trap is building the hard version of everything on day one.

Build first

  • One transport that works for your shape.
  • A server that validates, persists, then broadcasts every change.
  • Optimistic UI. Show the user's own action immediately and reconcile when the server confirms.
  • Reconnection with catch-up. When the connection drops, reconnect and fetch what was missed.
  • Persistence in Postgres, so nothing important lives only in memory.
  • Authentication on the connection, checked again for every channel a client joins.

Leave for later

  • Horizontal scaling across many servers.
  • CRDTs or operational transforms for true concurrent editing.
  • Presence with cursors and typing indicators.
  • Delivery receipts and read state.
  • Offline support and queued sends.

A surprising amount of real-time ships on that simple loop: send, validate, persist, broadcast. Get it solid before the fancy parts.

WebSockets vs Server-Sent Events vs polling

You have three honest options, and the right one depends on direction and frequency.

PollingServer-Sent EventsWebSockets
DirectionClient asks repeatedlyServer to clientBoth ways
ProtocolPlain HTTP requestsPlain HTTP, long-lived responseUpgraded connection (RFC 6455)
ReconnectionNot neededBuilt into the browser, with last event IDYou build it
InfrastructureNothing newWorks with most HTTP infrastructureNeeds hosts and proxies that allow long-lived upgrades
Best forUpdates every few minutesFeeds, notifications, live dashboardsChat, collaboration, multiplayer

Polling is unglamorous but legitimate. If a dashboard only needs to change every minute or so, polling needs zero new infrastructure.

Server-Sent Events are a one-way stream over HTTP, and they are underrated. The browser's EventSource reconnects automatically and sends a Last-Event-ID header, which the HTML specification defines precisely for resuming a stream. Serve them over HTTP/2 or later, because browsers limit concurrent connections per domain on HTTP/1.1, which bites when users open several tabs.

WebSockets give you a full two-way connection. They are the right call for chat and collaboration, where both sides talk constantly. You own more: connection lifecycle, heartbeats, reconnection and authentication.

Our default: SSE when data flows mostly one way, WebSockets when it is a real conversation, polling when the update rate is low enough that anything else is overkill.

Reconnection and missed messages

Connections drop constantly: tunnels, sleeping laptops, phones switching networks, deploys. The naive client reconnects and shows stale state. The correct client reconnects, asks "what did I miss since message X?" and catches up.

That means every message in a channel has a sequence number the server can replay from. Design this on day one. Bolting it on later is painful.

create table rooms (
  id        uuid primary key default gen_random_uuid(),
  last_seq  bigint not null default 0
);
 
create table messages (
  id          bigserial primary key,
  room_id     uuid not null references rooms(id),
  seq         bigint not null,       -- per-room, strictly increasing
  author_id   uuid not null,
  body        text not null,
  client_tag  uuid not null,         -- de-duplicates retried sends
  created_at  timestamptz not null default now(),
  unique (room_id, seq),
  unique (room_id, client_tag)
);
 
-- Inside one transaction: claim the next sequence number, then insert.
update rooms set last_seq = last_seq + 1 where id = $1 returning last_seq;
insert into messages (room_id, seq, author_id, body, client_tag)
values ($1, $2, $3, $4, $5)
on conflict (room_id, client_tag) do nothing;

The update ... returning takes a row lock on the room, so two concurrent sends cannot claim the same number. The seq gives you order and replay ("everything after 412"). The client_tag, generated by the client, lets it retry a send safely after a dropped connection without creating duplicates. If the insert affects no rows because the tag already exists, roll the transaction back so the sequence number is not used, and return the existing message to the client.

Ordering and conflicts

Ordering. Messages can arrive out of order, especially across servers, and "whenever it reached the server" is not reliable. Order by the per-channel sequence, and have clients buffer briefly if they see a gap, then fetch the missing range.

Conflicts. If two people edit the same field, who wins? For most apps, last-write-wins per field, with the server deciding the order, is honestly fine. Start there.

Real concurrent text editing, two cursors in the same paragraph, needs CRDTs (conflict-free replicated data types) or operational transforms. These are a serious undertaking to build, but mature libraries exist: Yjs and Automerge are the common choices, and they also handle offline edits. Do not adopt them unless the product requires it. Most "collaboration" features are really last-write-wins with good presence on top.

Presence without ghosts

Tracking who is online sounds easy until you realise it changes constantly and every change fans out to everyone in the room.

  • Store presence in memory or Redis with short expiry times that clients refresh through a heartbeat. A dead connection then expires on its own instead of leaving a ghost online.
  • Throttle cursor and typing updates on the client. Nobody needs every pixel of cursor movement.
  • Send presence as small diffs ("joined", "left") rather than the full list each time.
  • Never persist cursor positions to your main database. They are ephemeral by nature.

Scaling fan-out across servers

The moment you run more than one server, a problem appears: a user on server A sends a message, but the others in the room are connected to servers B and C, which have no idea it happened.

The standard fix is a pub/sub backbone. The receiving server persists the message, then publishes it to a channel. Every server subscribed to that room receives it and pushes it to its own clients. Redis pub/sub is the usual starting point; Postgres LISTEN and NOTIFY works for smaller loads without adding a service.

One subtlety matters: Redis pub/sub delivers at most once. If a server is briefly disconnected, it misses messages. That is fine as long as the database is the source of truth and clients can replay by sequence number. Pub/sub is the doorbell, not the mailbox. When you need durable streams, Redis Streams or a dedicated message broker is the next step, and most products never get there. Our post on scaling a web app when traffic spikes covers the wider capacity picture.

Backpressure

A slow client on a bad connection should not be able to stall your server. Bound the per-connection send queue, drop or coalesce updates that are superseded (only the latest dashboard value matters), and disconnect clients that fall too far behind. They will reconnect and replay.

Security for real-time connections

Real-time endpoints are an easy place to forget the rules you apply everywhere else.

  • Authenticate the connection with a short-lived token, not a long-lived secret in the URL.
  • Authorise every channel subscription and every message, not just the initial connection. A user who can connect is not automatically allowed into every room.
  • Check the Origin header on WebSocket upgrades to prevent cross-site hijacking.
  • Validate and size-limit every incoming message, and rate-limit per connection.

The OWASP WebSocket Security Cheat Sheet is a good checklist.

The stack we would reach for

  • Transport: native WebSockets or SSE, without a heavy framework until we need one, or a managed service when speed to market matters more than control.
  • Server: Node.js and TypeScript for the connection layer. The event loop suits many mostly idle connections, and sharing types between client and server removes a category of bugs.
  • State and fan-out: Postgres as the source of truth, Redis for pub/sub and presence. Our practical guide to Redis covers where it fits.
  • Frontend: React with optimistic updates and a thin sync layer that owns reconnection and replay.
  • Hosting: a platform that supports long-lived connections. The Next.js docs note that on hosts deploying route handlers as serverless functions, WebSockets will not work because the connection closes on timeout. Plenty of teams find this out in production. Run the connection layer as its own long-lived service and keep the rest of the app where it is.

If your needs are mainly collaborative editing, presence and shared state, that is squarely our real-time collaboration work, and we will tell you honestly when a managed service beats a custom build.

What drives the cost

We do not quote real-time features we have not scoped. These are the factors that move the effort:

FactorSimplerMore involved
DirectionOne-way updates via SSETwo-way messaging via WebSockets
Delivery guaranteesBest effort, refresh to fixOrdered, de-duplicated, replayable
ConcurrencyLast-write-wins per fieldSimultaneous text editing with CRDTs
ServersOneMany, with pub/sub fan-out
PresenceOnline or offlineCursors, typing, selections
OfflineNot supportedQueued sends and merge on reconnect

The expensive variable is almost always correctness under failure: reconnection, ordering and de-duplication. The happy path is quick. Making it not lie to users when the network misbehaves is where the work is.

Common mistakes to avoid

  • Hosting that cannot hold connections. Check before you commit to a platform.
  • Broadcasting before persisting. If the server crashes in between, clients saw something that does not exist.
  • No replay path. Reconnecting clients that cannot catch up mean silent data loss.
  • Treating pub/sub as storage. It is a notification channel, not a record.
  • Building CRDTs you do not need. Start with last-write-wins.
  • Ignoring backpressure. Bound your queues and coalesce superseded updates.
  • Authenticating once and never again. Check permissions per channel and per message.

Real-time often shows up inside other products. A customer dashboard may need live numbers, and booking and scheduling apps need availability that updates as slots are taken. The same principles apply at a smaller scale.

Where to start

  1. Decide the shape and how stale an update is allowed to be.
  2. Pick the transport: SSE, WebSockets or polling.
  3. Build the persist-then-broadcast loop with sequence numbers and client tags.
  4. Add reconnection with replay, and test it by killing connections on purpose.
  5. Add pub/sub, presence and conflict handling only when the product needs them.

Real-time is not one hard problem, it is several medium ones: transport, persistence, reconnection, ordering and fan-out. This is exactly the kind of system we build, and just as often, the kind we get called in to fix after a demo stopped working under real users. If you are planning something live, tell us what you are building and we will give you a straight answer about which parts are easy and which are not.

FAQ · 05 questions

Frequently asked questions

Should I use WebSockets or Server-Sent Events?

Use Server-Sent Events when the server mostly pushes updates and the client rarely sends anything back, such as notifications, feeds and live dashboards. It runs over plain HTTP and the browser reconnects automatically. Use WebSockets when both sides send messages frequently, such as chat, multiplayer and collaborative editing.

Can I build real-time features on serverless hosting?

Often not directly. Many serverless platforms end a function after a response or a timeout, so they cannot hold long-lived WebSocket connections. Run the connection layer on a host that supports long-lived processes, or use a managed real-time service, and keep the rest of the app wherever suits it.

Do I need a managed service like Pusher or Ably?

A managed real-time service is a good choice when you want presence, channels and global fan-out without running the connection layer yourself, especially for an MVP. Build your own when you need tight control over data, costs at high connection counts or custom delivery guarantees.

What is a CRDT and do I need one?

A CRDT, or conflict-free replicated data type, is a data structure that lets several people edit the same thing at once, even offline, and merges their changes automatically without conflicts. You need one for Google Docs style simultaneous text editing. For most apps, last-write-wins per field is simpler and good enough.

How many WebSocket connections can one server handle?

It depends on memory, message rates, the work done per message and the runtime, so there is no single number. Mostly idle connections are cheap, while chatty ones with heavy processing are not. Load test your own message patterns, and design for horizontal scaling with a pub/sub backbone so you can add servers when needed.

Related service

API & Backend Engineering

Secure, well-documented APIs that scale.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1–2 weeks
Pricing
Fixed price per phase
You own
All code and accounts