Assemble Mbak Yayuk's flood post broadcast code: rooms, acks, idempotency keys, order and Redis. 15 levels, played right in the browser with nothing to install.
Pub/sub (publish/subscribe): the sender does not know who listens. It publishes a kabar to a topic (a room), and the server passes it to everyone subscribed to that topic. At this post the code is real JavaScript, run in a closed frame on a simulator of the village network. Every night has its own radio weather (a kabar can be lost, doubled, late, out of order), and the night’s number is written on the stage. One good night does not make the code right: every level is tried on 32 nights.
One WebSocket server can hold only so many thousand connections, so a big app runs several servers behind a load balancer (horizontal scaling). The catch: the listeners’ connections are spread out, and the server that receives a kabar does not hold all of its listeners. The way out is a shared bus, usually Redis pub/sub: every server publishes to the bus and listens to it, then passes messages to its own connections.
There are three delivery promises. At-most-once: send once; what is lost is lost. At-least-once: send again until the receiver acknowledges (ack); nothing is lost, but it may arrive twice, because what was lost may be the ack. Exactly-once on a real network usually means at-least-once plus a receiver that filters out doubles. The wait before a resend must be longer than the round trip: if not, the sender repeats before the ack can arrive.
There are two kinds of message. A kabar (an event) is something that happened: every one must arrive, and order matters. State is how things are now: a water level, a price, a courier’s position. For state, an old number is useless once a new one comes. So state may be sent at-most-once and may be skipped, as long as what is shown is never older than what was already shown.
ACK means the receiver answers every message that arrives. NACK is the opposite: the receiver speaks up only when it sees a hole in the sequence numbers, and asks for the missing number. NACK suits one sender with many receivers: hundreds of acks for every message would flood the sender, while requests come only when something is lost. The condition: the sender keeps old messages so it can send them again.
Backpressure is what happens when a receiver is slower than the sender. There are only four choices: pile up in a queue (the lag grows, memory runs out), drop the newest, drop the oldest, or tell the sender to slow down. The right one depends on the content. For state, drop what is stale. For a kabar that must arrive, slow the sender down, and remember that sender may be serving other listeners too.