MSD-101 · Deep dives: hard problems, solved
The trip state machine
⏱ 12 min 🎮 Hands-on ☁ Azure ✓ Completed
⚡ The 30-second answer
A trip is a state machine: REQUESTED → MATCHED → ARRIVED → ON_TRIP → COMPLETED → PAID, or CANCELLED. One service owns it, rejects invalid moves, writes with optimistic concurrency (Cosmos DB ETag + If-Match, so two writers cannot both win), and publishes changes from the change feed, so an update is never saved without being announced.
- States and allowed moves
- ETag and 412 retries
- Events from the change feed
- Apps follow the server
Try it
Play with the design before you read about it. Everything runs on this page.
No Azure subscription needed. Read the requirement, see the architecture, build it in a mock portal, send a booking through it, then break it.
☁ Simulate on Azure: The trip state machine
The driver taps Start trip at the same second Priya taps Cancel. Her phone is in a lift, and the trip service restarts during a deployment. The trip must end in one clear state.
It must
- A trip moves REQUESTED → MATCHED → ARRIVED → ON_TRIP → COMPLETED → PAID, or CANCELLED
- Only allowed moves are accepted
- Every change reaches the rider and the driver
- Apps always show the server's state
With these numbers
- Conflicting writes
- 0 lost
- Update reaches app
- < 2 s
- Lost events
- 0
- Audit
- Every change kept
Each box is one Azure service. Tap a box (or Tab to it) to see its job and why it is there.
Create each resource. The defaults are a good design; change a setting and read why it matters. Some choices decide what breaks later.
Home › Create a resource › Azure Container Apps
Create Container App: trip-service
ⓘ ON_TRIP is only allowed after ARRIVED; COMPLETED only after ON_TRIP.
ⓘ A write based on an old version fails with 412 and is retried on fresh data.
Deployment in progress…
Microsoft.ContainerApps · resource group rg-trip-state
Home › Create a resource › Azure Functions (Cosmos DB trigger)
Create Function App: trip-events (Cosmos DB trigger)
ⓘ If the service crashes after saving, the change feed still sees the change.
Deployment in progress…
Microsoft.Functions(CosmosDBtrigger) · resource group rg-trip-state
Home › Create a resource › iOS / Android
Remote config: rider app
ⓘ Messages missed while offline are never replayed by the socket.
Deployment in progress…
Microsoft.iOS/Android · resource group rg-trip-state
Everything is deployed. Your architecture is lit up below. Go to Run to send a request through it.
Request: Driver taps Start trip
⚠️ Cosmos DB and Function Apps bill by use. Use serverless Cosmos DB for tests.
- Create a Cosmos DB container for trips (serverless is fine for tests).
- Write updates with If-Match on the document ETag; on 412 re-read and decide again.
- Add an Azure Function with a Cosmos DB trigger that publishes each change to Web PubSub.
- Delete the resource group when done.
* Illustrative prices to compare designs, not a quote.
What breaks, and the fix
| Failure | User sees | Why | Fix |
|---|---|---|---|
| ⚔️ Rider cancels as driver starts | Empty car, or charged for a cancelled trip | Last write wins | If-Match ETag, retry on 412 |
| 🔀 Events arrive out of order | Wrong receipt | Any state could follow any state | Validate every transition |
| 💥 Service restarts right after saving | App stuck on the old status | Events sent from request code | Publish from the Cosmos DB change feed |
| 📵 Rider app offline for a minute | Stale status | Missed socket messages | Re-read the trip after every reconnect |
🎓 Education-only simulation. Nothing is created in Azure and no subscription is needed.
Stream vs command
Live data can lose a point. Commands must happen exactly once. Give them different roads.
GPS points ride the WebSocket every 4 s. One lost? The next one replaces it.
Idempotency key
Send the same ID on every retry. The server returns the first result instead of doing it again.
Book with key k7. The trip is saved… but the reply is lost in the lift.
Outbox + backoff
Save the command on the phone first, then send it. Wait longer after every failure.
The tap is saved to the local outbox. Even if the app dies now, it is not lost.
Geo index + expiry
Keep only the latest position per driver in memory, and let it expire after 30 s.
Every ping overwrites the driver’s last position and resets a 30 s timer.
Pub/sub fan-out
Publish one event to a group. Everyone in the group gets it, however many they are.
The trip service publishes once: “car moved”.
Push to wake, then re-sync
A push only says “something changed”. The app then asks the server for the truth.
The app is in the background, so its socket is closed. The server sends a push.
- The problemThe driver taps Start trip at the same second the rider taps Cancel. The database ends up saying ON_TRIP, the driver drives off, and the rider is charged for a trip she cancelled.
- The design ideaOne owner, allowed moves only, If-Match on every write.
- In real lifeOrder, booking and delivery systems all use the same idea. Teams that draw the state diagram first find most edge cases (“can you cancel after pickup?”) before writing code.
Start with a question
The driver taps Start trip at the same second the rider taps Cancel. The database ends up saying ON_TRIP, the driver drives off, and the rider is charged for a trip she cancelled.
Two people, two phones, one trip. Without rules, the last write wins, and it is often the wrong one.
Explain it like I'm 10
A board game has rules: you cannot jump from start to finish. And if two players move the same piece at once, the referee checks who moved first and says “try again” to the other.
The technical explanation
States and moves. Write the allowed moves down: MATCHED only from REQUESTED, ON_TRIP only from ARRIVED, CANCELLED only before ON_TRIP (with a fee rule after ARRIVED). The trip service rejects anything else.
Concurrency. Read the trip and its _etag from Azure Cosmos DB, decide, then replace with If-Match: <etag>. If someone changed it first, Cosmos DB returns 412 Precondition Failed; re-read and decide again on fresh data.
Events. Do not publish events from request code: a crash after saving loses them. An Azure Functions Cosmos DB trigger reads the change feed and publishes every saved change to Web PubSub and push.
Apps. Phones show whatever the server says. After every reconnect or app open they re-read the trip with GET /trips/{id}, because socket messages missed while offline are gone.
| From | Allowed to |
|---|---|
| REQUESTED | MATCHED, CANCELLED |
| MATCHED | ARRIVED, CANCELLED, REQUESTED (driver declined) |
| ARRIVED | ON_TRIP, CANCELLED (with fee) |
| ON_TRIP | COMPLETED |
| COMPLETED | PAID |
Real-world scenario
Order, booking and delivery systems all use the same idea. Teams that draw the state diagram first find most edge cases (“can you cancel after pickup?”) before writing code.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
Next: Push notifications that arrive →Questions people ask
What is a state machine in app design?
A list of states (like REQUESTED or ON_TRIP) and the allowed moves between them. The server accepts only allowed moves, so the data can never end up in an impossible state.
What is optimistic concurrency?
Read a version number with the data, and when you write, say “only if the version is still X”. If someone changed it first, the write fails and you try again with fresh data.
Is a state machine overkill for a small app?
No. Even a small app has races like cancel versus start. Writing the allowed moves down takes an hour and prevents wrong charges and stuck trips, which cost far more to fix later.
Interview questions
How this topic comes up in system design interviews. Answer out loud first, then open the model answer.
intermediate Rider cancels while the driver starts the trip. What happens?
Both commands read version 7; one write succeeds and moves to version 8; the other gets 412, re-reads, sees the new state and applies the rule (e.g. cancel no longer allowed after ON_TRIP, or start not allowed after CANCELLED).
advanced How do you avoid losing notifications when the service crashes?
Treat the database as the source of events: a change-feed processor publishes every committed change (the outbox idea), with at-least-once delivery and idempotent consumers.
Quick revision
Remember
- States and allowed moves
- ETag and 412 retries
- Events from the change feed
- Apps follow the server
- Store every transition as an event with who, when and from which state. Support teams answer “why was I charged?” from that history.
One line to remember
“One owner, allowed moves only, If-Match on every write.”
Official documentation
- Cosmos DB optimistic concurrency (Microsoft Learn)
- Cosmos DB change feed (Microsoft Learn)