TweakCode
Worked Systems lessons

Chat

How Chat works

Before you start

  • Requirements

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

    Open lesson
  • Pick the key every read has

    Messages are partitioned by conversation and ordered by a sequence number.

    Open lesson
  • Queues

    Slow work leaves the request path through a queue.

    Open lesson

Why it matters

Ana may send while Bo is offline, and either phone can reconnect after missing several messages. A live connection says only where a device is now; it cannot prove what that device has already received or preserve a common order after a network change. Sending must not wait for Bo’s phone, and reconnecting must recover every missed message without gaps or duplicates.

Example

Design 1:1 messages

Two people exchange text. If the recipient is online, they see it immediately. If not, they see it the next time they connect. History is kept.

Input
log = {}
Output
[[2, "bo", "hey"], [3, "ana", "lunch?"]]

Mental model

The idea

Keep one example in view

Design 1:1 messages

log = {}→[[2, "bo", "hey"], [3, "ana", "lunch?"]]

Keep this exact scenario and its constraint in view while you build the model.

For conversation c1, append Ana’s “hi,” Bo’s “hey,” and Ana’s offline “lunch?” as seq 1–3; acknowledge from that log, push only when connected, and let Bo reconnect with after=1 to receive seq 2 and 3.

Conversation c1 owns one durable log. Ana’s “hi” is seq 1, Bo’s “hey” is seq 2, and Ana’s offline “lunch?” is seq 3. The server acknowledges each send after its append, then uses Bo’s live connection only as an immediate delivery path when one exists.

Bo stores cursor 1 before disconnecting. sync(c1, after=1) returns seq 2 and 3 in order; after applying both, Bo commits cursor 3. Retrying with cursor 3 returns nothing. If a response is replayed from after=1, the client deduplicates seq 2 and 3 before advancing.

Visual anchor

Design 1:1 messages

conversation c1 (the log)

012
1 ana: hi
2 bo: hey
3 ana: lunch?
↑Bo has up to here
Bo reconnects and says: I have everything up to seq 1. The server returns seq 2 and 3, no gaps and no duplicates.

Pro

The rest of this is on Pro

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