# Choosing a state model

> Who decides, what travels fast and what must arrive, and who gives a late joiner the state: chat, a host-authoritative game and collaborative drawing side by side.

The first design question for anything shared is **who decides**. jsflow keeps no state and has no authority: peers are equals, a message reaches the peers that are in the room when it is sent, and a peer can say anything. So your app picks a model. Three common ones, side by side:

| | Chat | Game, host decides | Drawing together |
|---|---|---|---|
| **Who decides** | nobody: an append-only log | one peer, the host (or your server) | nobody: each stroke stands alone |
| **Fast path** (`broadcast`, `send`) | typing indicators | inputs to the host, the host's state a few times a second | pointer positions, strokes in progress |
| **Must arrive** (`sendReliable`) | every message | commands, round start and end, results | finished strokes, undo |
| **Order** | one order everywhere: clock, then author | the host numbers every change | only per author; undo needs a clock |
| **A late joiner gets** | the history from **one** peer | the whole state from the host | each peer's strokes, merged |
| **Source lost** | ask the next peer | choose a new host; a new round | nothing to do |
| **Trust** | names are self-asserted | the host is a peer: it can cheat | any peer can forge or erase |

The rows, one at a time. Each paragraph names the column it is about.

## Who decides

- **Chat.** Nobody. Every message is a fact that stays true; the log is the union of all of them.
- **Game, host decides.** One peer, the host, applies the rules and says what is true; the others send it their inputs and draw what it says. The host can be any peer, chosen when the room has none by a rule every peer computes the same way (see "When the source is lost" below), or your own server.
- **Drawing.** Nobody. A stroke has a unique id and is a fact on its own, so applying it twice, or in another order, gives the same picture.

When the state is a shared document that many peers change at once, a merging library such as [Yjs](https://yjs.dev) does the work of the model, and [y-jsflow](https://jsflow.com/docs/guides/yjs.md) syncs its documents over a room. [A shared whiteboard](https://jsflow.com/docs/guides/whiteboard.md) is a complete example, with drawing, notes and cursors.

## The fast path and the must-arrive path

`broadcast` and `send` are datagrams: fast, unordered, and a packet can be lost. `sendReliable` is in order for each sender and receiver pair and retransmitted until acknowledged, or reported by the `undelivered` event if the other peer makes no progress for 30 seconds. A blip shorter than that, with the same id, continues in order; a reload is a new peer and a new session, so order restarts. When a peer comes back (`up: true` after a gap) or you get `undelivered`, send the state again instead of trusting the queue. [Choosing how to send](https://jsflow.com/docs/concepts/choosing-how-to-send.md) has the full table. For these three models:

- **Chat.** All chat messages go by `sendReliable`, one send per peer. A typing indicator is the one thing worth a `broadcast`: a lost one is gone in a second anyway.
- **Game.** The high rate goes on datagrams: each peer sends its input to the host with `send` (routed through the mesh, so in a big room it may cross another peer first), and the host broadcasts the state. A broadcast floods the mesh, each peer forwarding it to its own links (up to about 8), so **size matters more than rate**: 10 to 20 times a second is fine for a state of a few hundred bytes (positions rounded, only what changed); at the full datagram size, 1,052 bytes, go lower. A link that already holds 256 KB of unsent datagrams drops new ones. Anything that must not be missed goes by `sendReliable`: a command that changes the rules, a round starting or ending, a score. A state bigger than 64 KiB (the reliable limit) is sent in parts.
- **Drawing.** Pointer positions and the stroke in progress go by `broadcast`. A finished stroke goes by `sendReliable`, so it is never half there.

## Does it need one total order, and who sequences?

- **Chat.** Yes, one order everywhere, or two people see different conversations. Nobody sequences: every entry carries a clock that is higher than every clock its author has seen, ties break by author id, and every peer sorts the same way. [Keeping state in sync](https://jsflow.com/docs/guides/keeping-state-in-sync.md) has the code.
- **Game.** Yes for changes of state, and the host sequences: it numbers each accepted change, and peers apply them in that order and ignore a number they have seen. The host's reliable sends reach each peer in order. Inputs need no order: the newest wins.
- **Drawing.** Mostly no. Strokes commute, so peers need no common order, except for what is drawn on top and for undo. Use the same clock as chat for those.

## What a late joiner gets, and from whom

- **Chat.** The history, from **one** designated peer, with ids so that repeats are ignored. If every peer sent it, the joiner would see several copies interleaved.
- **Game.** The whole state, from the host, as soon as the joiner's `peer` event says it is reachable. The others stay silent: a second answer is a second version of the truth.
- **Drawing.** Every peer sends its own strokes and the joiner merges them by id. This is the right shape for set-like state: a repeat does nothing and the order does not matter.

The rule behind all three is in [keeping state in sync](https://jsflow.com/docs/guides/keeping-state-in-sync.md): **ordered history comes from one source, set-like state from everyone.**

## When the source is lost

A reload is a new peer with a new id. When a peer leaves or its page goes away, the others see `up: false` almost at once. When it crashes or its network dies, they see it after about a second (a link silent for half a second is taken out of the routes). If its network comes back within about 20 seconds, the same id returns with `up: true`: so expect `up: false` and then `up: true` for the same id after a blip. The 15 seconds in [lifecycle](https://jsflow.com/docs/concepts/lifecycle.md) is how long the service keeps a dropped peer's place so that it can rejoin, not how long the others take to notice.

- **Chat.** The joiner that asked for the history waits a few seconds and asks the next peer. Nothing else is needed.
- **Game.** A **sticky host**. A peer that joins adopts the host it hears from: the host's state messages carry its id and an **epoch**. Only when there is no host (the room was empty, or the host's `peer` event said `up: false`) does a peer elect one, by a rule every peer computes the same way, for example the lowest peer id in `room.peers()` with its own. Peer ids are drawn at random and reused, so "lowest" does not mean "longest here": that is why the rule elects only when no host exists, so that a peer that joins with a lower id, or a host that comes back after a blip, does not take the role from the host the room has. The epoch is a pair, **(counter, host id)**, compared counter first. It goes up when a new host takes over: two peers that elect at the same moment still order, the higher pair wins, and a host that sees a higher pair steps down. `room.peers()` lists every peer reachable through the mesh, not only the ones linked directly (each peer links to about 6 to 8 others), and two peers' lists can differ for a moment around a join or a leave: the epoch covers that. The new host either carries on from the last state it saw (it has been receiving the broadcasts, so it may be a few ticks behind) or starts a **new round**: it announces the round by `sendReliable`, and everyone drops messages from earlier rounds. Inputs sent to the old host after its last broadcast are lost, so every peer **resends its current input when it sees a new epoch**, and the new host does not run a tick on stale input. A host that reloads is a new peer with a new id, and is not the host.
- **Drawing.** Nothing special: no peer is the source, so there is nothing to lose. A peer that returns asks for the strokes again like any joiner.

## Trust: names, identity, and who may cheat

A peer says who it is in its own messages, and any peer can say anything, including another peer's name.

- **Chat.** A name in a message is self-asserted. If it must mean something, join with a [join ticket](https://jsflow.com/docs/guides/join-tickets.md): your server signs the user id, and `room.user(peerId)` returns it for every peer, vouched for by the service. Show that, not the name in the message.
- **Game.** The host is just another browser. Its user can change the rules, and a peer cannot tell. Use a host when the stakes are friendly. Anything that must be fair, secret or recorded (scores that count, hidden cards, prizes) belongs on your own server, with jsflow carrying the fast traffic. See [security and privacy](https://jsflow.com/docs/guides/security-and-privacy.md).
- **Drawing.** Any peer can add, change or erase anything. If that matters, give strokes an author (from the ticket) and refuse edits from anyone else.

## Next

[Keeping state in sync](https://jsflow.com/docs/guides/keeping-state-in-sync.md) has the techniques, with code. [For games](https://jsflow.com/docs/guides/for-games.md) is the short version for a game.

Source: https://jsflow.com/docs/concepts/choosing-a-state-model/
