Skip to content

    Frontend System Design

    Heartbeats, Backpressure and Delivery Guarantees on the Client

    Notice a dead real-time connection, stop a fast sender flooding a slow link, and tell at-most-once, at-least-once and exactly-once apart, with a lab.

    By Published 13 min read

    • frontend-system-design
    • real-time
    • websockets
    • delivery-guarantees
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Reconnection and Message Ordering

    What you'll learn: By the end of this lesson you will be able to explain why a real-time connection can die without telling the page, design an application-level heartbeat and compute how long it takes to notice silence, explain what bufferedAmount measures and why an unbounded sender is a bug, choose a full-queue policy for each kind of message, and state what at-most-once, at-least-once and effectively-once delivery promise, and what each costs.

    Think of three small problems in a phone call. You say "hello?" into silence and must decide whether they are still there: a heartbeat. You talk faster than they can write the address down, and they must be able to say "slow down": that is backpressure. You read out an order number and they say "got it", but the line drops before you hear it, so you say it again, and now they must notice they already wrote it: that is a delivery guarantee.

    The running example is a live panel on a shop: price ticks and order-status updates arrive from the server, and the page sends commands such as "add to cart" over the same connection. The lab's numbers are made up for the lesson.

    The core idea

    1. A connection can die without telling you. A cable pulled, a lid closed or a proxy that forgets a connection leaves no close message. Only silence shows it, and a heartbeat turns silence into a decision.
    2. A sender that never checks its buffer is not fast, it is building a queue. The queue grows in memory and in time: every message waits behind all the others. Backpressure means bounding the queue and choosing what to lose or delay.
    3. A delivery guarantee says who retries and who remembers. No retry: at-most-once. Retry until acknowledged: at-least-once, with duplicates. Retry plus a receiver that remembers: an effect that is once.

    Three illustrations run through the lesson: a minimal example (a ping that goes unanswered), a realistic example (the shop panel with ticks and commands) and a failure example (a half-open connection the page believes is live).

    The other side of this topic, on the server, is in WebSockets, SSE and Long Polling. The lessons on WebSockets in depth and on reconnection and message ordering cover what follows a "dead" verdict and how messages are numbered.

    Heartbeats: turning silence into a decision

    The WebSocket protocol has its own heartbeat. RFC 6455 defines Ping and Pong control frames: on receiving a Ping an endpoint must send a Pong unless it has already received a Close frame, the Pong carries the same application data as the Ping, and a Pong may also be sent unsolicited as a one-way heartbeat. A Ping may be used as a keepalive or to check that the other end is still responsive.

    The catch for a page: the WHATWG WebSockets specification says these frames "are not currently exposed in the API". A script cannot send a Ping and cannot see a Pong. The browser may send pings itself, but that does not tell your code anything. So the page needs an application-level heartbeat: ordinary messages such as {"type":"ping","id":7} that the server answers with {"type":"pong","id":7}.

    Figure 1. A ping that is never answered

    sequenceDiagram accTitle: A heartbeat that detects a dead connection accDescr: The page hears the server at time 0, then nothing. After the interval of 5000 milliseconds it sends ping 1. No pong arrives within the timeout of 2000 milliseconds, so it counts one miss and sends ping 2 at once. A second timeout is the second miss, and the page declares the connection dead at 9000 milliseconds. participant P as Page participant S as Server S-->>P: last message (t=0) Note over P: silence for 5000 ms P->>S: ping 1 (t=5000) Note over P: no pong in 2000 ms: miss 1 P->>S: ping 2 (t=7000) Note over P: no pong in 2000 ms: miss 2 Note over P: dead at t=9000, close and reconnect

    How to read this: a heartbeat is a timer with a rule. The page does not ask "is the server alive?" while it is hearing traffic; it asks only after a quiet interval, and it gives up after a fixed number of misses.

    Three numbers define the design, and the lab's HeartbeatMonitor takes all three:

    Setting What it means Too small Too large
    Interval Silence before the first ping Pings on every pause, wasted traffic Slow to start checking
    Timeout How long a ping may stay unanswered Slow networks look dead Slow to count a miss
    Max missed Misses in a row before "dead" One lost packet kills a good connection Slow to give up

    The worst-case time from the last sign of life to "dead" is interval + maxMissed * timeout. Two rules make a monitor behave well:

    • Any inbound message counts as life. On a busy connection no pings are needed at all. The lab's busy case sends none.
    • Send the next ping at once after a miss, so misses are not stretched by another interval.

    MQTT uses the same idea in its Keep Alive: a client with nothing else to send must send a PINGREQ, and the server must close the connection if it hears nothing within one and a half times the Keep Alive period.

    Server-Sent Events have a related detail. The HTML Standard tells authors to send a comment line (starting with :) every 15 seconds or so, because some legacy proxies drop idle HTTP connections. Clients ignore comment lines, so a script cannot see one: to let the page measure silence, the server must send a real, small event.

    WebSocket.send() never says "slow down". It queues the bytes. The only signal is bufferedAmount, a read-only number of bytes queued by send() and not yet transmitted. The WHATWG specification says it counts application data, not framing overhead or operating-system and network buffering. MDN notes it resets to zero once the queued data has gone, and does not reset when the connection closes: if you keep calling send() it keeps climbing.

    An unbounded sender has a worse failure than slowness. The specification says that if data cannot be sent because of buffer space, the user agent flags the WebSocket as full and closes the connection, with an error event followed by close. A flood ends in a close you did not choose.

    Figure 2. The sending path, with the application's own queue

    The sending path: a bounded application queue feeds the socket only while its buffer is below the high-water markProducer to App queue (enqueue); App queue to Socket buffer (send below high-water); Socket buffer to Network (drains)Producer: ticks, commandsProducerticks, commandsApp queue: boundedApp queueboundedSocket buffer: bufferedAmountSocket bufferbufferedAmountNetwork: slower than the producerNetworkslower than theproducerenqueuesend below high-waterdrains

    How to read this: the high-water mark protects the socket buffer, the queue's limit protects memory, and a policy decides what gives when the queue is full.

    The lab's OutboundQueue moves a message to the socket only while bufferedAmount is below the mark, and applies one of four policies when the queue is full:

    Policy What it does Fits
    reject Refuses the new message and says so Commands: tell the user "not sent" and let them retry
    drop-newest Discards the new message Low-value data where the past matters more
    drop-oldest Discards the oldest waiting message Streams where fresh beats stale
    coalesce Replaces a waiting message with the same key State updates: only the latest price per symbol matters

    Streams have the same idea: MDN defines backpressure as a slow stage signalling backwards so earlier stages slow down, with a queue's desired size equal to its high-water mark minus the size of what is queued. WebSocketStream gives sockets this automatically, but MDN marks it experimental and non-standard, so treat it as a future option.

    The receiving side has the same problem: a page that re-renders on every message can fall behind its own socket. The lesson on real-time data in React state returns to that.

    Delivery guarantees: who retries and who remembers

    A sender cannot know whether a message arrived. It can only learn from an acknowledgement, and the acknowledgement can be lost too. That gives three guarantees, named the same way across messaging systems:

    • At-most-once: send once, never retry. A message may be lost, never repeated. Redis Pub/Sub states it as "a message will be delivered once if at all"; if the subscriber fails or disconnects the message is forever lost. MQTT calls its QoS 0 "at most once", where message loss can occur.
    • At-least-once: keep a copy, retry until acknowledged. Nothing is lost while the sender keeps trying, but a retry after a lost acknowledgement delivers twice. MQTT's QoS 1: "assured to arrive but duplicates can occur".
    • Exactly once: MQTT's QoS 2 promises it with an extra handshake. In an application you build on a lossy link, the usual way is effectively once: at-least-once delivery plus a receiver that remembers the ids it has handled and ignores repeats.

    Figure 3. A lost acknowledgement causes a duplicate, and the receiver's memory absorbs it

    sequenceDiagram accTitle: Retry after a lost acknowledgement accDescr: The sender sends message 41 and the receiver handles it and sends an acknowledgement, but the acknowledgement is lost. The sender times out and sends message 41 again. The receiver sees that id 41 was already handled, ignores the repeat, and acknowledges again. This time the acknowledgement arrives. participant C as Sender participant R as Receiver C->>R: msg 41 R->>R: handle 41, remember id 41 R--xC: ack 41 (lost) Note over C: no ack in time, retry C->>R: msg 41 (again) R->>R: id 41 seen: ignore R-->>C: ack 41

    How to read this: the receiver must acknowledge the repeat too. If it stayed silent about a message it already handled, the sender would retry until it gave up.

    Two details decide whether this works. The id must be the same on every retry (created when the message is made). And the receiver's memory must outlast the retries: a set that forgets too early lets a late retry through. Guarantees about the order of messages are a separate matter, covered in the lesson on reconnection and message ordering. For commands that must survive a page reload, see Offline-First Sync and Conflict Resolution.

    Choosing

    Figure 4. Which behaviour does this message need?

    flowchart TD accTitle: Choosing a delivery and overflow behaviour accDescr: If a newer message makes an older one worthless, such as a price tick, coalesce by key and accept loss. If the message is a user command that must happen, use at-least-once with a stable id and an idempotent receiver, and reject with a visible error when the queue is full. If it is a low-value diagnostic, send at most once and drop the oldest when full. Q{"Does a newer message make
    an older one worthless?"} -->|"yes"| C["Coalesce by key
    at-most-once is fine"] Q -->|"no"| M{"Must it happen,
    even after a retry?"} M -->|"yes"| A["At-least-once, stable id,
    idempotent receiver
    reject + tell the user when full"] M -->|"no"| D["At-most-once,
    drop-oldest when full"]

    How to read this: the question is about the meaning of the message, not about the transport. One connection carries all three kinds at once.

    Choice Gain Cost
    Short heartbeat interval Dead connection noticed sooner More traffic, more false alarms on slow links
    Bounded queue with a policy Memory and staleness stay bounded Some messages are dropped or refused, on purpose
    At-least-once with ids Nothing is lost while retrying Ids, a receiver that remembers, and retry state

    Build it: three models, one run

    Goal. Run a heartbeat monitor against a silent server, run five sender policies against a producer that is faster than the link, and run three delivery guarantees over a link that loses messages and acknowledgements.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic with fake time and a fake socket: no browser, no network, no real timers.

    cd examples/frontend
    pnpm install
    cd labs/heartbeat-backpressure
    pnpm test           # 25 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo.
    2. In section 1, the half-open case: the server's last message was at t=7000, pings go out at 12000 and 14000, and the page declares death at 16000. That is 9000 ms, which is interval + maxMissed * timeout with 5000 + 2 x 2000.
    3. In section 2, compare "peak buf" and "age at t=1000" across the rows.
    4. In section 3, compare "duplicated" for at-least-once and effectively-once, and find the "sender gave up" count.

    Expected output, captured from a real run (Node 26.13.1; the half-open heartbeat case):

    half-open connection: the server goes silent after t=7000 and never replies
      t=12000 ping 1
      t=14000 ping 2
      t=16000 dead after 2 missed pings
      pings sent: 2; last heard at t=7000; declared dead: t=16000 (9000 ms after the last sign of life)

    Expected output, captured from a real run (Node 26.13.1; backpressure; "age at t=1000" is how old the newest transmitted message is at that moment):

    === 2. Backpressure: a producer makes 10 bytes/ms for 1000 ms, the link carries 4 bytes/ms
    one message every 10 ms (100 bytes, key sym0 to sym2 in turn); queue limit 5 messages, high-water mark 300 bytes
    policy                  accepted  refused  coalesced  peak buf  peak queue  age at t=1000  done at
    no limits (the default) 100       0        0          6040      1           610 ms         t=2499
    reject                  48        52       0          396       5           220 ms         t=1199
    drop-newest             48        52       0          396       5           220 ms         t=1199
    drop-oldest             100       52       0          396       5           140 ms         t=1199
    coalesce by key         100       0        54         396       3           100 ms         t=1149
    accepted counts messages the application took (coalesced ones replace a waiting message); refused counts rejected, newest dropped and oldest dropped

    Expected output, captured from a real run (Node 26.13.1; delivery guarantees):

    === 3. Delivery guarantees: 1000 messages, 20% of messages lost, 20% of acknowledgements lost, up to 5 attempts, seed 42
    guarantee         lost  duplicated  handled  sent on link  sender gave up
    at-most-once       213           0      787          1000               0
    at-least-once        1         188     1233          1559               8
    effectively-once     1           0      999          1559               8
    at-least-once with no acknowledgement loss: lost 1, duplicated 0
    effectively-once on a 60% loss link: lost 65, duplicated 0, sender gave up on 414

    Read the numbers. With no limits the buffer peaks at 6040 bytes and the newest message sent at t=1000 is 610 ms old; every bounded policy keeps the buffer at 396 bytes. coalesce sends the freshest data (100 ms old). reject and drop-newest match because only the return value differs: reject returns false so the producer can tell the user. In section 3, at-least-once handled 1233 messages for 1000 sent, 188 of them twice; effectively-once handled each at most once. Both lost 1 message and gave up on 8: seven of the eight were delivered but never acknowledged, so "gave up" is not "lost".

    What the lab does not show. No real socket: real buffer limits, proxy idle timeouts and library defaults are not modelled, and every number is illustrative. The delivery model has no clock, so retry timing, ordering and a receiver that forgets are left out.

    Break it. In src/delivery.ts, delete the line if (seen.has(id)) return; in receive. Effectively-once now duplicates, and the test "effectively-once handles each message at most once" fails. Put it back.

    In practice: a live panel that stayed "live" while stale

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The shop's order page shows a status line and a "Live" badge fed by a WebSocket. Support reports that for some customers on hotel and train Wi-Fi the status stays at "Packed" for many minutes after the order was delivered. Reloading fixes it.

    Starting architecture

    Figure 5. Starting point: nothing checks that the connection is alive

    Starting architecture: the page assumes a connection is alive until the browser reports a closeStatus service to Hotel Wi-Fi (status updates); Hotel Wi-Fi to Order page (never arrive)Order page: 'Live' badge, no heartbeatOrder page'Live' badge, noheartbeatHotel Wi-Fi: silently drops the flowHotel Wi-Fisilently dropsthe flowStatus service: keeps sendingStatus servicekeeps sendingstatus updatesnever arrive

    How to read this: the page has no way to tell "nothing happened" from "nothing is arriving".

    Options considered

    Option What it fixes What it costs Risk
    Poll every 30 s instead No silent staleness Constant requests Higher server load
    Server pings only Server frees dead connections Page still cannot see silence Customer problem unchanged
    Application heartbeat in the page Page detects silence and reconnects A ping, a pong, a timer Reconnect storms if tuned badly

    The decision

    Field Decision record
    Context A live panel can be stale with no sign of it, and the page cannot see protocol pings.
    Decision Add an application ping after 20 s of silence, a 5 s reply timeout and two misses before "dead" (all illustrative), so silence is noticed within 30 s at worst. Any inbound message counts as life. On "dead", close the socket and reconnect, and show "Reconnecting" instead of "Live".
    Consequences, good Stale panels recover without a reload, and the badge tells the truth.
    Consequences, bad Extra messages, and a server that is slow to answer can now cause reconnects.
    Revisit when Reconnects after "dead" are common, or the transport changes.

    Rollout and verification

    1. Ship the server's pong first, ignoring pings it does not know yet on old clients.
    2. Ship the page behind a flag for a few users, and count "declared dead" per hour.
    3. Test the worst case with fake time: silence is declared within interval plus misses times timeout.

    The 2 a.m. failure

    A deploy makes the status service slow for a minute (illustrative): pongs arrive late, thousands of healthy pages count two misses at the same moment, close and reconnect together, and the reconnect load slows the service further. First three checks: (1) compare the "declared dead" count with the server's latency chart; (2) check whether reconnects are spread out or synchronized; (3) check whether the pong goes through the same slow path as the data. Mitigation: raise the timeout or the miss count by flag, and add random delay to reconnects. Follow-up: add jitter to the first ping, keep pongs on a cheap path, and alert on the "declared dead" rate.

    Architect's notes

    • Bound every queue and name its policy per kind of message, in the design.
    • Give every command a stable id at creation, so a retry is the same message.
    • Say "effectively once" when you mean at-least-once plus deduplication: it points at the memory the receiver needs.

    Common mistakes

    • Relying on the close event alone to know the connection died.
    • Ignoring bufferedAmount, so a burst of sends turns into stale data or a forced close.
    • One policy for every message, such as dropping commands the user expects to happen.
    • Generating the id on each retry, which defeats deduplication.
    • Synchronized heartbeats and reconnects, so one slow minute becomes a storm.

    Key takeaways

    • Browsers do not expose WebSocket Ping and Pong to scripts: heartbeat with application messages.
    • Worst-case silence detection is interval + max missed x timeout; any inbound message resets it.
    • send() queues without limit; bufferedAmount is the only signal, and a full buffer ends in a forced close.
    • Pick reject, drop-newest, drop-oldest or coalesce per kind of message.
    • At-most-once loses, at-least-once duplicates, and effectively-once is at-least-once plus a receiver that remembers ids.

    Practice exercises

    Exercise 1 — Starter (45 min): For interval 20000, timeout 5000 and maxMissed 2, work out the worst-case detection time. Then change one setting to get under 15 seconds and say what you give up.

    Exercise 2 — Intermediate (2 hours): Add a drop-lowest-priority policy to the lab and write a test where a command survives a full queue of price ticks.

    Exercise 3 — Advanced (half day): Make the receiver remember only the last 100 ids and add a retry delay. Find the delay at which effectively-once starts to duplicate, and say what the memory must be proportional to.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments