Microservices Mania
The setup
Alice is stuck in a lecture and wants bubble tea from the canteen. Luckily, Bob is already there. On FoC, the errand app we built for CS3219, Alice posts the errand with a 40-credit reward. Bob accepts it, picks up the drink, and hands it over. Then Bob gets paid.
Everyone starts with 100 credits, which only move between students.
Behind the app, FoC is five services. You can click one to see what it owns:
The usual decisions
Where to split
We split FoC by business area and gave each service its own data. That meant Order could reach Credit's data only by asking Credit. From then on, every question that spans two services needed a call or a copy, on top of five databases, a message broker, and the plumbing between them.
Calls or events
Order talks to Credit twice. First, when Alice posts, Credit has to hold 40 of her credits. Later, when Bob delivers, Credit pays him. We had to decide whether Order should call and wait, or announce an event on Kafka and move on. You can try each one, and see what happens when Credit goes down:
We made holding a call, because we wanted the errand to open only once the money was held. Paying became an event, since Bob's delivery is finished even while Credit is down. The price was a short moment where the order says Completed while Bob's balance still shows his old total.
Saving and announcing
Now Bob delivers. Order has to save the order as Completed and publish the outcome. The trouble is that the database and Kafka commit separately. What happens if the service dies between the two?
We ended up writing the event into an outbox table in the same transaction as the order, for a relay to publish afterwards. Even so, the relay can crash after sending and before marking the row sent. So any event might arrive twice. Later we tested exactly that crash: the row stayed unpublished until its 30-second lease ran out. Then the relay sent it again, without any extra payout from Credit.
Undoing a step could fail
Accepting an errand runs as a small saga across Order and Credit, with an undo for when a later step fails. We had to think about what happens when the undo itself fails.
The hold only goes up
Bob can offer to do the errand for more than the reward. Once his offer is accepted, Alice's hold moves from 40 to his price. If anything fails after that, Credit puts the hold back to 40.
Now imagine a courier could offer less. You can step through what happens:
A lower offer frees some of Alice's credits. Meanwhile, she can spend them before the revert comes. The revert then has to take back credits she has already spent. Credit's database refuses, since an account's balance must always cover what it holds. That leaves the saga stuck halfway.
So we decided every offer had to at least match the reward. Since an accepted offer can then only raise the hold, a revert only ever lowers it. Lowering a hold always works, which made the undo safe by construction.
A cancel can overtake what it cancels
Order asks Credit to hold Alice's 40 credits. Unluckily, the request is slow. Eventually Order times out, gives up on the errand, and asks Credit to release the hold. Now those two messages can arrive in either order. What do you think happens if the release gets there first?
Tombstones
When a release arrives for an order that's new to Credit, we have Credit leave a tombstone, an empty record marked released. Later, when the slow hold finally arrives, it finds the tombstone and is turned away. Undoing an acceptance before it reaches Credit works the same way.
Timeouts mean "unknown"
After a timeout, the hold might have worked and only the reply got lost. So before every call, Order writes down what it's about to do. A timeout or a "not found" counts as unknown until Order has checked the real state. For the same reason, we reject an errand that expired before opening only once Credit has confirmed the release.
Everything can arrive twice
Because Kafka delivers at least once and phones retry when a reply gets lost, the same message can arrive twice. Whatever happened, we wanted Bob paid exactly once.
Repeats caught by state
We made Credit treat a settled or released reservation as final, with a database trigger to enforce it. A repeated outcome then just finds the work already done. Credit changes the reservation, the ledger entry, and the balances in one transaction, which means a crash leaves all of them or none. That even covers the same outcome sent under a different event ID, which a table of handled event IDs would pay out again. As a second guard, Order's outbox allows one outcome per order:
CREATE UNIQUE INDEX order_terminal_outcome
ON order_outbox (order_id) WHERE kind = 'order.outcome';
That index stops Order from ever creating a second outcome. Delivering that one outcome twice is still possible. Handling that is Credit's job. We tested it too: replaying 400 outcomes, under their original event IDs and under fresh ones, left every balance exactly as it was.
A key for every acceptance
Requests from the app carry an idempotency key. When a request comes in again with the same key and body, the server returns the result it recorded the first time instead of doing the work again. Most keys last 24 hours. Can you see why acceptance needs longer?
So we kept acceptance keys for as long as the order exists. Two details made that safe:
- a courier's first rejected acceptance also gets a permanent key, which stops its retry from turning into a new assignment once the errand reopens;
- each courier keeps at most one rejected attempt per errand, which caps 50 couriers racing for one drink at 50 rows.
Any further tries from the same courier are refused without storing a key. Those refusals are meant to be final: retrying one after the errand reopens could assign the courier again.
A new key aimed at an errand that's already taken gets "not found", exactly like a missing errand. That way, taken errands stay private.
No calls under a lock
When Bob and Carol tap Accept in the same second, Order locks the errand's row so only one of them wins. Accepting also needs Credit, though. Holding the lock across a network call would keep the errand blocked for as long as Credit took to answer. So we split acceptance into three short steps:
The queue that looked empty
Before the demo, we load-tested FoC on our own machines. Afterwards, one create-then-cancel failed. Order had cancelled the errand, while Credit still held Alice's credits well past their 30-second deadline.
Kafka itself looked healthy, with zero lag on Credit's consumer. The problem sat one step earlier, in Order's outbox table: 3,503 events waiting to be published, the oldest 437 seconds old. Press play to watch a scaled-down version:
A one-second default
The cause turned out to be a default. Our Kafka library waits up to one second to fill a batch of 100 messages before sending it. Meanwhile, the relay sent one event and waited for Kafka's acknowledgement before sending the next. So every event sat out the full second, which held the relay to about one event a second.
A teammate's fix flushes a batch after 10 ms and keeps draining while there's work left. On the rerun, 400 cancellations offered at 80 events a second for ten seconds all settled. Publishing averaged about 35 events a second. Only 114 of the 400 settled within our 5-second target, though.
The lesson went into the repo's list of landmines: measure the outbox's size and its oldest event alongside Kafka's lag.
A lock that returned old data
Most of our writes start by locking a row with SELECT ... FOR UPDATE, so the row stays ours until we commit. Now picture locking a Location and reading its categories, which live in another table, in the same query. What do you think comes back if someone else is editing both?
Locking before reading
In Postgres's default isolation level, the wait refreshes the locked row and leaves the rest of the query on its old snapshot. So the Location comes back as it is now, with its categories as they were. An approval could then create a Location with last version's categories.
We caught it with an integration test that holds the lock, edits both, and checks what the waiting read returns. The fix was to lock the parent first, then read its relationships in a separate statement while still holding the lock. Writers of the categories take the same parent lock, which keeps that separate read consistent. That became a team rule, which Credit's reservations and Order's lifecycle both follow.
On time by whose clock?
Bob's delivery has a deadline of twice the expected time after pickup. He submits a photo as proof one minute before it. However, checking the photo takes three minutes. So is Bob late?
The database decides the time
We decided to trust the server's clock. After locking the order, Order stamps the submission with the database's own clock, and only for a photo the server has already confirmed as uploaded. A proof that waits on the lock counts from the moment it gets it. If that stamp is before the deadline, the order stays protected while the photo is checked, however long that takes.
If checking finds the photo invalid, that submission is rejected. Bob can then try again before the original deadline. And if Alice cancels in the meantime, her cancel can take the same lock and supersede the pending proof.
Who notices a deadline
Behind all this, two workers poll the database every second for overdue orders. We chose polling over timers in memory, because deadlines saved with the orders survive a restart. Each overdue order is locked and checked again against the database's clock before anything changes. As a result, two workers finding the same order do no harm.
Telegram goes down
I built the communication service. It links your Telegram, sends notifications ("Bob accepted your errand"), and relays chat between Alice and Bob. For chat we leaned on Telegram, which already has push notifications, phone apps, and delivery. Our bot relays each message, which keeps everyone's handle private. The catch is that chat goes down whenever Telegram does.
Sending at least once
For each notification, I check it's new, send it, and then record it. A crash after Telegram accepts a message and before the record means Bob gets it twice. Recording first would only move the crash, and lose the message instead. Between the two, I'd rather Bob read a message twice than miss it.
Some messages go stale
Messages can wait hours while Telegram is down. When they finally go, a plain retry would send news about things that already happened. So I gave each kind of message its own rule. For example, progress updates are dropped once they're more than 30 minutes old. Likewise, "Head to pickup" goes only while the order is still at that step. "You've been unassigned" goes only if the courier is still off the errand. Outcomes I always send, since you'd want to know how your errand ended even hours later. Emails, which can sit in a queue, get the same check again just before sending.
Two readers of the same events
To answer "has the order moved on?", Communication keeps its own narrow copy of each order, built from Order's events. Here's the bug that taught us to give that copy its own reader:
After the fix, each consumer group gets every event and keeps its own place. That way, the copy keeps up while notifications wait for Telegram. The notification reader also applies each event to the copy just before checking it, which keeps the copy at least as new as the message in hand. So both groups write the same table. Since a write only applies when its revision is newer, they can land in any order. The copy can only catch a stale message once it has seen the newer revision, which leaves a brief window where one still slips out.
The whole system
Here's FoC again, now with every decision from this post pinned where it lives. The second tab lists the course's ideas and where we used each one:
Further reading
- Chris Richardson, Microservices Patterns (2018). Sagas, compensations, the transactional outbox, and idempotent consumers.
- Hector Garcia-Molina and Kenneth Salem, Sagas, SIGMOD (1987). Where compensating steps come from.
- Pat Helland, Life beyond Distributed Transactions, ACM Queue (2016). Messages that arrive twice, late, or out of order.
- Martin Kleppmann and Chris Riccomini, Designing Data-Intensive Applications, 2nd edition. At-least-once delivery and why idempotence matters.