TweakCode
Worked Systems lessons

Chat · Stage 2 of 3

Heartbeats & TTL Presence

Keep a user online only while heartbeats keep refreshing a key

Foundations

In the first lesson, every message was durable. Now, what if the state is whether something is still alive, a connection that can die silently without announcing that it left?

Model liveness as a key with a time to live. On connect, set the key with a TTL; the client sends a heartbeat at a shorter interval, and each heartbeat refreshes the TTL. If heartbeats stop, the key expires on its own, with no cleanup transaction. Watchers learn of changes through a subscription, with a short grace period so a quick reconnect does not flicker.

Take a TTL of 30 seconds and heartbeats every 10. Two heartbeats can be lost without the key expiring, and a dead connection disappears within 30 seconds of its last heartbeat. With one million connected clients, that is 100,000 small writes per second, work for an in-memory store, not the durable database.

time (s)

0123456
0
10
20
30
40
50
60

heartbeat

0123456
✓
✓
✓
·
·
·
·

expires at

0123456
30
40
50
50
50
50
50

online

0123456
yes
yes
yes
yes
yes
no
no
Heartbeats at 0, 10, 20 push the expiry to 50. Then they stop, and at 50 the key expires on its own: offline, with no cleanup step.
  • Requirements

    Each worked system starts from a scoped list of verbs and numbers.

    Open lesson

Case Scenario

The design brief

Design presence

The app shows a green dot when the other person is connected. The dot should disappear within about 30 seconds of a dead connection.

To see how heartbeats and a TTL track liveness, consider presence in an app like WhatsApp: a green dot shows when the other person is connected, and it should disappear within about 30 seconds of a dead connection. The phone refreshes a 30-second presence key every 10 seconds, and silence lets it expire.

Ana’s green dot should react quickly when her phone connects, but a dead phone cannot always announce that it left. At one million connected clients, frequent status updates can overwhelm storage meant for durable messages, and flaky mobile reconnects can make the dot flicker. The presence key must expire within 30 seconds, with only a brief display grace before contacts see her offline.

Pro

The rest of this is on Pro

The idea above is free. The walkthrough, the cost, and the practice are on Pro.