Building a Real-Time Notification System with WebSockets

Push a message onto a bus in Brisbane and watch it land on a phone in Perth before the driver has put the handset down. That kind of immediacy has moved from novelty to baseline expectation for people who spend their working day inside dashboards, inboxes and dispatch tools. Browsers used to make the experience awkward: a tab that polled for updates every thirty seconds burned mobile data, lagged behind a trading blotter in the Sydney CBD and left users guessing whether a screen was even current. A persistent connection reshapes the problem, because the browser can hold a channel open and react the moment something happens instead of asking permission to look again. Learn more about How To Use Cloud9 S Live Preview For Web Development.

WebSockets supply that persistent channel. The protocol begins as an ordinary HTTP request, upgrades into a long-lived socket, and then carries lightweight frames in both directions without repeating the handshake or opening a fresh TCP connection each time. Building a production notification system on top of it involves considerably more than flipping a switch, however. You need a way to track who is connected, a broker that can fan a message out to thousands of sockets, a preference model that suppresses irrelevant alerts, and an interface that respects the reality that attention is a finite resource. The sections that follow work through those pieces in order, from the handshake at the protocol level to the visual tone of the alerts themselves. Learn more about Letsswagg.org.

Why immediacy has become table stakes

Australian connectivity is a patchwork of excellent and merely workable. Fibre-to-the-node reaches most metropolitan households in Melbourne, Brisbane, Adelaide and Perth, yet fixed wireless and ageing copper exchanges still serve large stretches of regional New South Wales and Queensland. Meanwhile mobile data performs strongly across the country, including on trains and in mining regions where satellite links backhaul to the rest of the world. A notification system therefore has to assume a user might be on a solid NBN connection at a desk in Surry Hills, tethered to a phone hotspot on a worksite, or riding the free Wi-Fi that Melbourne's tram network extends along its routes. Real-time messaging has to feel dependable on all three. Learn more about C9indian.com.

Local business habits reinforce the expectation. Australian shoppers now complete most transactions through apps, retail teams watch fulfilment dashboards through the trading day, and a Melbourne sports betting operation cannot afford a delayed price update when a market swings in under a second. People here are forgiving of systems that are slow, but they are less forgiving of systems that stay silent, because silence reads as a fault rather than a queue. It helps to label a stale screen explicitly, showing when data was last refreshed and offering a one-tap retry, so a delayed alert is presented as delayed rather than missing.

Feedback shapes the build as much as the code does. Shipping an early slice of a notification service and reacting to what people actually use keeps the scope honest, and community threads where developers trade working builds are where that kind of frank, practical feedback tends to live. Conversations in the letsswagg community are a good example of how a half-finished side project gets pressure-tested by people with no obligation to be polite about it.

The mechanics of the WebSocket connection

A browser opens a socket with a single HTTP request that carries an Upgrade: websocket header, a Connection: Upgrade header, a random Sec-WebSocket-Key and a protocol version. The server accepts the key and replies with 101 Switching Protocols, and from that moment the connection carries WebSocket frames: opcode, payload length, masking key and payload, all packed without the verbosity of repeated headers. Each frame may hold a few bytes of control data or a JSON payload, and the connection remains open for as long as both sides want it.

Long-lived connections need active maintenance. Most reverse proxies and load balancers drop idle sockets after a fixed window, so clients send periodic ping frames and expect a pong, closing and reopening the connection when responses stop arriving. Heartbeat intervals around twenty-five to thirty seconds keep intermediaries from mistaking silence for abandonment. When a network path disappears without warning, the browser fires a close event, and the client reconnects using exponential backoff with jitter so a fleet of browsers does not stampede the server the instant a single exchange recovers.

Reconnection creates a second problem: what was missed while the socket was down. The reliable pattern is to assign every message a monotonic sequence identifier per conversation, have the client report the last identifier it received, and let the server replay anything newer. That replay runs over ordinary HTTP, which keeps the recovery path simple to debug. Idempotency keys on the publishing side prevent the same alert from appearing twice when a retry and a replay overlap, and a bounded retry limit stops a broken consumer from looping forever.

Designing an architecture that scales

Split the system into distinct layers rather than one large service. At the edge, a connection registry keeps a map of active sockets, the user or tenant they belong to, and the channels they have subscribed to. Behind it sits a broker such as Redis pub/sub, NATS or Kafka, which decouples the code that publishes an event from the code that owns connections. A notification service then applies the rules: does this user care about this event, is it a duplicate, what template applies, and should it be delivered now, batched or dropped. A delivery log in Postgres records what was sent to whom and when, which answers both audit questions and the inevitable "did you get my alert?" message from a customer.

Authorisation deserves careful attention because sockets are long-lived. Issuing a short-lived token at connection time and attaching it through the Sec-WebSocket-Protocol header avoids leaking credentials into access logs, while a per-channel permission check at subscription time ensures a socket cannot simply ask for a channel it should not hear. Payloads should stay small and uniform, carrying an identifier, a type, a title, a short body, a timestamp, a target URL and an optional action rather than embedding entire domain objects. When a user clicks through, the client fetches the current record over HTTP and always renders fresh data.

That loop between server and browser benefits from fast visual feedback. Guides that explain the live preview workflow show how keeping a rendered browser in front of you while code changes turns a reconnect and payload change into something you can watch happen in seconds, which is far quicker than redeploying to a staging environment and hoping the notification arrives on the first try.

Keeping delivery dependable on Australian networks

Mobile operating systems quietly work against long-lived sockets. iOS suspends background tabs after a short period, and browsers on Android throttle connections once an app loses focus, so a socket that was healthy at 9am may be dead by lunchtime. The practical answer is to treat WebSockets as the fast lane for a foreground session and pair them with native push through APNs and Firebase Cloud Messaging, so a user receives a system notification that deep-links into the live socket once they tap it. Desktop users benefit from the same fallback via web push, which remains the only path to reach a browser tab that has been closed all afternoon.

Store-and-forward logic handles the gaps that remain. A client reconnecting after four hours should not receive forty queued alerts in a burst; it should receive a digest summarising what changed while it slept, with critical items pulled forward. Expiry windows, per-channel digests and a cap on batch size keep a returning user oriented rather than overwhelmed. Regional variation deserves the same treatment, because a message published in Perth may reach a user on the east coast through an entirely different path than one travelling to Darwin, and the delivery log should record region so that latency can be compared honestly.

Observability turns these assumptions into facts. Track the volume of handshakes, active sockets per region, median publish-to-render time, the number of sockets closed by heartbeat timeout versus by the client, and the share of messages served from replay rather than live broadcast. A sudden rise in timeouts on one carrier points to a network or proxy setting rather than a code fault, and a synthetic client that connects, receives and acknowledges a heartbeat every minute from each capital city gives you a signal before users start complaining.

Presenting notifications with calm, legible interfaces

Alerts arrive during meetings, on trains and at the end of a long shift. The c9indian landing page offers a useful reference point for that mood: it leans on generous whitespace, restrained typography and nature-inspired photography rather than dense panels and hard contrast, and that same restraint translates well into how notifications should feel. A quiet toast in the corner that never steals focus, groups similar events, and disappears on its own respects the person reading it. Loud banners for routine updates train people to ignore banners, which is exactly the wrong reflex to build when an equipment fault needs immediate attention.

Copy and hierarchy matter as much as colour. A useful envelope tells the user what happened, where, and what to do next in a single glance, while critical alerts get a distinct weight, an accessible contrast ratio and an option to bypass quiet hours. Scheduling also deserves local awareness, since Australian users span AEST and AEDT, and a digest delivered at nine in the morning Sydney time should not arrive at three in the afternoon for someone in Perth. Giving people per-channel mute controls and a "batch until tomorrow" switch costs little and removes most of the friction that makes people reach for the close button.

Signs the delivery pipeline is healthy:

Cues the interface needs another pass:

Contact