Ch.30: System Design: Uber's Trip State Machine

Transcript

0:00 Maya taps Cancel as her driver taps Start trip, and both phones lose signal. This is the Uber trip state machine problem: one real ride can now look like two histories. His screen says started. Hers says cancellation sent. Both apps retry, and he may carry her while her app says canceled. The server has to commit one legal transition and make every retry learn it. The phones cannot vote. That gives every later box one test. With 1 history as the goal, put the full map on screen. Do not memorize every box yet.

0:32 Start with, basically, the spine that decides the race: mobile clients, the API gateway, and one lifecycle service. At the center, a transaction coordinator updates lifecycle state and driver availability in one relational store. That same commit writes transition history and one durable publication record... ...the outbox row. That becomes the handoff. Right. And everything after that can be late without changing the trip? Exactly. The other branches either report or recover that decision. A relay sends the event through the bus to push workers.

1:04 Query reads current state. Timers and redispatch call back into lifecycle authority, with matching outside it. So every recovery path bends back toward that lifecycle service, whether Maya reconnects or a deadline fires? Yes. Each one returns as a command or a read; none can author trip state. Honestly, a lot of boxes for one tap. Yeah. We've all seen a “simple” button pull the backend into the room. Here it changes two people's work in the physical world. That gives us one map to test against every failure.

1:36 That map only matters if it survives Maya's ugly case. Take Maya's exact failure: if Start committed but she never got the push, what does the system still owe both of them? Functionally, the current driver can arrive, start, and complete. A permitted actor can cancel. A pre-pickup driver exit can trigger redispatch. Either app can ask what happened after a timeout. Yeah. Small requirement list, ugly guarantees. Replay Maya's ride: Start commits during a network gap, the push disappears, and Maya reconnects.

2:08 Her read must reveal that committed state, while the transition still reaches downstream consumers after a publishing outage. Oh, that's the nasty part: the server succeeded while the phone experienced failure. Then the race must never assemble a state that no legal command committed. Yeah. Her phone got silence; the server still owes both people one explainable answer. No illegal state, no reopening a terminal trip, no driver owned by two live rides, and no event for an uncommitted transition. Non-functionally, every accepted or rejected command stays attributable without exposing precise location by default.

2:42 Right. To keep the race testable, we exclude matching, pricing, payments, pooled rides, and emergency workflows. Otherwise this becomes every Uber problem wearing one diagram. That scope boundary lets us separate server state from each phone's best guess. Let's model the lifecycle. A simplified trip moves from assigned, to driver arriving, to in progress, then completed. Pre-trip cancellation can move it to canceled or back toward redispatch. Imagine Maya keeps seeing “Cancellation sent.” That is not a trip state; it only means her request left the screen.

3:15 “Starting trip” on the driver's phone has the same limitation. Right. Those labels are observations; the statechart decides which commands the server can legally accept next. Start may be legal from assigned. Complete from assigned is nonsense, even if a delayed client asks politely. And that pattern is real: Uber's fulfillment write-up describes hierarchical statecharts and triggers. Our exact states and rules are fictional, and the source is linked in the description. Okay, but why not keep one flat list of states?

3:46 You can, and, I mean, then every pre-pickup state repeats the same rules. A hierarchy lets assigned and driver-arriving sit under pre-pickup, so one shared rule can forbid Complete in both. Now we can enforce one shared edge in the transaction. Okay, let's hear it. Start with the command contract. Once the statechart defines legal edges, I'm the retrying phone. What has to travel with my request so the server can tell “same attempt” from “stale driver”? Each command carries a trip ID, a unique command ID, the trip version the client last saw, and an assignment generation.

4:22 That number changes when the assignment moves to someone else. Take a client request that times out after the first Start commits. Its retry reuses the command ID, so the service returns the recorded result instead of starting a second time or duplicating work. Yes. The backend checks the actor, verifies that this driver belongs to the current generation, compares versions, and asks the statechart whether the transition is legal. But a mobile engineer could reasonably say, “If every version mismatch rejects, we're punishing harmless updates.” Are they right?

4:54 My first thought was reject every stale version. But that's too blunt. Version is a conflict signal, so the service can re-evaluate current state. A driver from the previous assignment still cannot act on the new one. Yeah, that distinction matters. Trip version is freshness: did the trip change? Assignment generation is authority: does this driver still own the right to act? We get a narrow stale-client check instead of a blanket refusal. Okay, let's unpack the race. Put both requests at the database at the same time with that command evidence. Two requests can each look legal in isolation; a lot of backend teams have debugged some version of that.

5:33 Here Maya's Cancel and the driver's Start hit different service instances. Each reads assigned before its transaction. Where does the second one lose? Right at the reread. The transaction locks the trip row, rereads current state, then validates the edge. Only one instance holds that lock, so one command commits before the other can test the authoritative state. So, one lane at the gate. Exactly. Both arrive together, but only one crosses while the state still says assigned. Let's say Start commits first while Maya's request is still waiting on a database lock. Then Start wins that ordering: it marks the trip in progress, marks the driver occupied, saves its command result, and commits. Maya's waiting transaction wakes, rereads in progress, so our fictional policy rejects a normal rider cancel and returns that state.

6:22 And if Cancel commits first? Start sees canceled and is rejected. The driver app replaces its unconfirmed screen with the server result. Neither phone gets to preserve the answer it hoped for. That sounds almost too simple. Simple only until the lifecycle record, driver row, and side effects can disagree. The statechart chooses the legal edge; the transaction makes one edge win. So the lock does not pick Start. It makes both commands take turns asking the only state that can authorize either. The result is temporary disagreement, not a 3rd trip state.

6:56 That winning trip state leads to a second boundary: driver availability. The ride record has to agree with whether that driver is free or occupied, or the race is only half solved. Starting Maya's trip keeps the driver busy. Canceling before pickup may release that person. Those writes cannot drift apart. If they do... ...matching can see a free driver inside an active trip. For example, the trip write could say canceled while the failed driver write still says busy. Worse, the trip could say in progress while the driver looks free and matching assigns another rider.

7:31 Hold on. That is the production nightmare: one service says the driver is occupied while matching sees them as free. The coordinator loads both entities, checks their relationship and versions, then commits both changes or neither. Yeah. Two-write workflows can look harmless in code review and become incident archaeology later. Uber's write-up calls out this same class of trip-plus-driver-availability inconsistency. Our row layout is still fictional. Yes. Atomic commit closes both books together.

8:01 If one transaction cannot cover both records, the design has to prove an equivalent all-or-nothing boundary through another coordination mechanism. Reconciliation later is too late for double assignment. Oh, man. Reconciliation can repair a dashboard. It cannot ask a second passenger to un-enter the car. The transaction protects the street, not just the schema. That atomic boundary settles the street-level race; publication is the next place truth can split. You know the failure. For example, Start commits, then the process dies before it publishes anything.

8:32 Maya reconnects and sees in progress, but support and notifications see nothing. Oof. The ride exists, but the rest of the system never hears about it. So the transaction writes a pending event beside the trip update. A crash before publication leaves it for the relay; a crash after publication but before the sent mark may produce a duplicate. So the relay is at-least-once. What keeps the duplicate from doing the work twice? The relay may deliver the same event more than once. Downstream consumers deduplicate on its transition ID.

9:06 We are not promising exactly-once delivery, only that every published lifecycle event names a committed transition. Okay, duplicates are survivable; invented state is not. Could a consumer update the trip if it sees the event first? Right. A duplicate notification is annoying. Letting that notification move the trip would be corruption. The event is a consequence, not lifecycle authority. Push, analytics, support views, and receipts may lag. The authoritative store still answers what happened. That leaves recovery free to be late without fabricating state.

9:38 With publication separated from authority, redispatch adds a different problem: who may act next. Before pickup, that driver cancels. The service commits the cancellation, releases the driver, and advances the generation. Then the redispatch adapter asks the existing matching system for a replacement. We are deliberately treating matching as a dependency, not reopening the nearby-driver lesson. Imagine the replacement accepts a new generation while the old phone reconnects and sends Arrived using the previous one.

10:07 Without a fence, an obsolete client could move the replacement driver's trip. Yeah, and my instinct is trip version should catch it. That's our usual tool. But the trip ID can be right and the state can still look pre-trip while the command belongs to the wrong driver. The generation blocks it. The old driver receives current assignment state and cannot revive ownership. A retry from the new driver keeps the same command ID and generation. Oh, right. Version says the trip changed. Generation says this driver's authority ended.

10:39 Redispatch changes ownership without rewriting history, and the former driver stays fenced. Now the system can replace the driver without reopening the trip. That redispatch handoff leads to the next delivery problem. What if notifications fail? For example, push to Maya may be lost while push to the replacement arrives twice. Both apps query current trip state on reconnect or when a command result is uncertain. Push reduces delay. Query restores truth. Push tells you sooner; query tells you what's true.

11:12 But if the driver never progresses, who owns that deadline? The server does. I mean, once you strip away the clock, a timer is just another caller. It carries a deterministic ID for that deadline and still passes through actor rules, generation checks, version handling, and the same statechart. A phone countdown is only... ...a display. What if two timer workers wake up together? Same race again? Same command identity, same recorded result. If the trip already moved, the statechart rejects the obsolete timer.

11:44 Humans, retries, and clocks use one command path. That leaves one transition door to defend instead of three. Once reconnects converge, operators still need proof. For example, if Maya says canceled while her driver says started, support should open one timeline: who acted, which generation owned the request, the before-and-after state, and why a command lost. Precise location stays out unless an investigation truly needs it. Yeah. If support needs two dashboards and a group chat to reconstruct one ride, the timeline already lost.

12:17 What turns that from a support ticket into an on-call page? Yeah, that's already an incident smell. We have all watched a support mystery become a fleet problem one alert too late. Before the street breaks, version conflicts rising above their normal baseline, outbox lag, redispatch age, and trips stuck in non-terminal states should warn us. The page-now contradiction is one driver committed to multiple active trips. Right, that stops being a support dispute. The timeline explains one ride; those rates show the fleet-wide risk.

12:50 Now the disputed middle is visible. Let's run the whole race one last time on the map. Right. Start where the disagreement is still visible: both phones. Cancel and Start reach the trip service with their command evidence attached. One transaction validates the winner and commits trip state, driver availability, durable history, and the pending event together. Only then does the relay publish. Notifications may lag, so either phone recovers through query; deadline workers use the same authority.

13:18 When the driver quits pre-pickup, redispatch requests a replacement from matching, increments the assignment generation, and removes the former driver's authority. So a replacement can take ownership without changing what already committed. Yeah. Authority can move; history can't. Right. And every stale screen eventually has to admit which history won. The phones still don't get a vote. They may disagree temporarily, but every path returns to one legal answer. Thanks for listening to Learning Podcasts.