Realtime: live location and push
The rider on the map and the tablet that must ring: when polling is enough, when to hold a connection open, and what open connections cost.
Realtime delivery lets the server send news to a client as soon as it has it, instead of waiting to be asked. It is the right tool when updates arrive at unpredictable moments and the client needs them within a second or two. It also turns connections into state that the system must hold, route to and recover, which is where most of the design effort goes.
Dabba has two screens that need it. The customer, once her order is picked up, watches the rider move towards her on a map. The restaurant tablet must ring within a second or two when a new order arrives, because a kitchen that notices an order three minutes late delivers cold food. This chapter works out what each needs, starting from the simplest design that could work.
How many people are watching, and how often things change
Little’s law gives the number of orders in flight at any moment: arrival rate times time in the system. In the dinner hour Dabba averages about 42 orders a second, and an order takes about 35 minutes from placement to delivery, so 42 × 2,100 ≈ 88,000 orders are in progress, the figure the brief carries. If about half of those customers have the app open at any moment, roughly 44,000 people are watching an order screen. Around 20,000 restaurant tablets are open at dinner.
Things change at very different rates on those two screens. A rider’s location changes every 5 seconds, by the brief. An order’s status changes about six times over its whole life: placed, accepted, preparing, ready, picked up, delivered. A restaurant tablet sees a new order every few minutes on a busy night, and nothing for an hour on a quiet afternoon. Those rates, more than any technology preference, decide the design.
Polling is a reasonable first answer
The simplest design is for the customer’s app to ask “where is my rider?” every 5 seconds. 44,000 viewers polling every 5 seconds is 8,800 requests a second, the same figure the brief reached for all 88,000 orders polling every 10 seconds. Each request is small: the app already has a connection open, the request is authenticated with a token, and the answer comes from the Redis rider index described in the geo chapter. A few stateless API servers can handle that.
The common objection, that polling wastes requests, does not apply much here. The location really does change every 5 seconds, so almost every poll returns something new. A push design would send about the same 8,800 messages a second. What push saves on the location screen is the request overhead and up to 5 seconds of delay, not the message count.
Now change one variable: look at the restaurant tablet instead. It needs to know about a new order within about 2 seconds, so it would poll every 2 seconds. 20,000 tablets polling every 2 seconds is 10,000 requests a second, as much as the whole API was designed for, and at 42 orders a second spread across 20,000 restaurants each tablet sees a new order about every eight minutes. That is about 240 polls per order, so nearly every request returns “nothing new”. The same applies to order status on the customer’s screen: polling every 5 seconds to catch six changes in 35 minutes is about 420 polls for 6 useful answers.
That is the real dividing line. Polling is efficient when data changes about as often as we ask. It is wasteful when changes are rare but must arrive quickly, because the poll interval has to be short for latency and almost every poll finds nothing.
The options, from simplest up
| Mechanism | How it works | Fits when | What it costs |
|---|---|---|---|
| Short polling | Ask every n seconds | Data changes about every n seconds, or a delay of n seconds is fine | Requests even when nothing changed |
| Long polling | The server holds each request open until there is news or a timeout, then the client asks again | Rare updates, and networks that break other options | An open request per client; a new request after every message |
| Server-sent events (SSE) | One HTTP response kept open; the server writes events into it | Server-to-client only; standard HTTP; reconnect built in | An open connection per client; one direction |
| WebSocket | The HTTP connection is upgraded to a two-way channel of messages | Both sides send often, or the client must acknowledge | An open connection per client; more custom protocol to build |
The customer’s order screen only receives. SSE suits it: it is ordinary HTTP, so proxies and load balancers handle it without special settings, and the browser’s EventSource reconnects automatically and tells the server the id of the last event it received. Native mobile apps use a small SSE client library to the same effect.
The restaurant tablet is different because it must answer. When an order arrives the tablet rings until someone taps “accept”, and Dabba needs to know that the tablet received the order, separately from whether a person has accepted it. A tablet that shows nothing because its connection silently died is the failure that costs money. So the tablet uses a WebSocket and acknowledges each order message; if the acknowledgement does not arrive within 10 seconds, the server tries again, and after two minutes without acceptance an automated phone call goes to the restaurant.
The rider app sends rather than receives. Its location updates go up as ordinary HTTP requests, batched when the network is poor: after a gap, the app sends the last few points in one request rather than one request per point. Sending location needs no persistent connection. Receiving does: when the dispatcher offers the rider an order, the offer has to reach the phone within a second or two and be accepted or declined, so the rider app also holds a WebSocket, used for offers and their replies rather than for location. Those rider connections, about 50,000 at peak, live on a separate pool of connection servers owned by dispatch, so the numbers below cover customers and tablets only.
Getting one rider’s location to the right connection
With 44,000 customers on SSE and 20,000 tablets on WebSockets, we have about 64,000 open connections. One idle connection costs a socket and some buffers, tens of kilobytes. A server built on an event loop handles tens of thousands of them, so Dabba runs four connection servers, about 16,000 connections each, with room to lose one.
Now the routing problem. A location update for rider 4411 arrives at an ingest server. The customer waiting for rider 4411 is connected to one particular connection server, out of four. Which one? We could keep a table of “customer to server” and update it on every connect and disconnect, but that table would always be slightly wrong, because connections drop and move constantly.
The usual answer is publish and subscribe. When the customer for order 8812 connects, her connection server looks up the order’s rider and subscribes to the topic rider:4411 on a pub/sub system, such as Redis pub/sub or NATS. The ingest server publishes each update for rider 4411 to that topic and does not know or care who is listening. Every connection server subscribed to it receives the update and writes it to the connections that wanted it.
The subscription is the routing table, and it is maintained by the connection servers themselves as clients come and go. Ingest stays stateless. If the order is reassigned to another rider, the order-events log from the streams chapter carries that event, and the connection server moves the customer’s subscription from the old rider’s topic to the new one.
Only riders with a customer watching need to be published at all. Of 10,000 location updates a second, the ones for riders on an active delivery with a watcher come to roughly the same 8,800 a second we estimated for polling. Pub/sub at that rate is comfortable for one Redis node, and it is easy to partition by rider id if it ever is not.
The customer’s phone goes through an underpass and loses its connection for 40 seconds. During that time, the rider sends 8 location updates, and the order’s status changes from “ready” to “picked up”. When the phone reconnects, what should the server send it?
Show the worked answer
For location, only the latest point. The 8 missed points describe where the rider was; the customer wants to know where he is. Replaying them would animate the rider racing along an old route. Location is state: the newest value replaces everything before it.
For status, the change to “picked up” must not be lost. Status changes are events: each one matters, and the app shows a different screen for each. On reconnect the client sends the id of the last status event it saw, and the server sends everything after it. If the gap is too old for the server’s short buffer, the client fetches the current order state from the API and starts again from there.
State and events need different reconnection rules
That answer separates two kinds of data that travel down the same connection, and treating them alike causes bugs in both directions.
Location is state. The ingest service already writes each rider’s position to the Redis geo set from the storage chapter, and it publishes the same update. A reconnecting client is first sent the rider’s current position from Redis, then receives new updates from the topic. If updates pile up for a slow client, for example on a weak mobile connection, the connection server keeps only the newest one per rider and drops the rest. That is called conflation, and it is correct for state: a slow client gets fewer updates, not older ones.
Order status is a sequence of events. Each status event carries a sequence number for its order. The connection server keeps the last few minutes of events per order, a small version of the log from the streams chapter. A reconnecting client sends its last sequence number, with SSE’s Last-Event-ID header doing this automatically, and the server replays what follows. Conflation would be wrong here: dropping “picked up” because “delivered” is newer loses a step the customer was entitled to see, and some steps, like “rider has arrived”, are the reason she has the app open.
Behind both rules sits the API. The connection is an optimisation for timeliness; the order’s real state lives in the order shard and can always be fetched. A client that is unsure what it missed fetches the order and starts again. That keeps the realtime path simple: it never has to be the only way to learn something.
A deploy that disconnects everyone: a walk-through
The connection servers hold state, and that changes how they can be deployed. Here is what happens the first time someone deploys them like stateless API servers.
At 19:45 a routine release restarts the four connection servers within two minutes. Each restart drops its 16,000 connections. Every client notices within a second and reconnects immediately. Each reconnect re-authenticates against the session service, which normally sees a few hundred logins a second and now receives tens of thousands. It slows down, reconnects time out, and clients retry immediately, adding more load. Pub/sub sees tens of thousands of subscribe requests in the same seconds. For several minutes customers see frozen maps and some tablets miss new orders, at the start of the dinner peak.
Each part of the fix addresses one step of that sequence. Clients reconnect with exponential backoff and random jitter: each failed attempt doubles the wait, up to a cap, and the actual wait is a random value below it, so that 16,000 clients spread their reconnects over tens of seconds instead of one. The failure chapter later in the pathway covers retries in general; here the point is only that clients must not all retry at the same moment. The connection tier checks a signed access token locally, without calling the session service, so reconnecting costs CPU on the connection server rather than a database lookup. Deploys drain one server at a time: the server stops accepting new connections, then sends its clients a “please reconnect” message spread over a few minutes, and only restarts once they have moved to other servers. And connection servers are not deployed during the dinner peak.
The costs are real. A full deploy of the connection tier now takes half an hour instead of two minutes. Signed tokens checked locally cannot be revoked instantly, so they are kept short-lived, around 15 minutes, and refreshed over the API. The connection servers also get their own release schedule, separate from the rest of the platform.
Balancing connections that last for hours
Load balancers were built for requests that last milliseconds. Spreading new requests evenly keeps servers evenly loaded, because old requests finish quickly. Connections that last an hour behave differently, and the difference shows up the first time we add a server.
Say the connection tier is running hot at dinner and we add a fifth server. The load balancer starts sending it new connections, but the existing 64,000 stay where they are, because nothing makes them move. For the next hour the four old servers remain overloaded while the new one fills slowly with only the connections that happen to start. The same happens after a server crashes and returns: it comes back empty while its former clients have piled onto the others.
Two measures help. The load balancer should route new connections to the server with the fewest open connections, not round-robin, so that the new server gets nearly all new arrivals until it catches up. And each server should cap its connections and, when it is well above the fleet average, ask a slice of its clients to reconnect, using the same gradual “please reconnect” message as a deploy. Connections then move a few hundred at a time, and no client notices more than a brief pause in updates. The cost is one more piece of logic in the connection tier and a metric, connections per server, that has to be watched as closely as CPU.
Connections die quietly
A connection that has broken does not always say so. A mobile network’s NAT, or a load balancer with an idle timeout (60 seconds is a common default), can drop a connection that has carried nothing for a while, and neither end learns about it until it tries to send. A tablet in a quiet restaurant at 16:00 could sit on a dead connection for an hour, believing it is online.
Heartbeats prevent this. The server sends a small message every 20 to 25 seconds; in SSE a comment line, which clients ignore, is enough. That keeps idle timeouts from firing, and if the client sees no heartbeat for, say, 60 seconds, it knows the connection is dead and reconnects. For the tablet, Dabba also tracks the other direction: a tablet that has not acknowledged a heartbeat for a minute is shown as offline on the operations dashboard, and new orders for that restaurant trigger the phone call immediately instead of after two minutes.
Finally, when the app is in the background, mobile operating systems close its connections to save battery. Then the only route left is a push notification through Apple’s or Google’s push services. Those are delivered on a best-effort basis and can be delayed or merged, so Dabba uses them to say “your rider has arrived” and to bring the app back to the foreground, never as the only record of an event. When the app opens, it fetches the order from the API.
When realtime is more than the problem needs
For the location map alone, polling every 5 seconds is a perfectly good design and the right first version: stateless, easy to cache, easy to deploy. Dabba would add SSE for customers only when the latency of status updates or the cost of 420 polls per order became a problem worth an always-on connection tier. The tablet, with its rare and urgent orders, is the case that justified building the connection tier first.
We would revisit these choices if customers began interacting during delivery, for example live chat with the rider. Two-way traffic from customers would move them from SSE to WebSockets, and chat history would need the full event treatment, with sequence numbers, storage and delivery receipts.
Behind every screen in this chapter, work is happening that no customer is waiting for: the receipt email and SMS after an order, refunds, payouts calculated each night, photos waiting to be resized. The next chapter, “Background work: queues, schedulers and cron at scale”, picks that work up: how to answer the customer once the order is safely recorded and still make sure everything owed afterwards happens, on time and without doing it twice in a way that hurts.