Your order service calls the payment service to charge a customer ₹2,000. You wait. Nothing comes back. After 30 seconds, the call times out.
Was the customer charged?
Maybe the request never arrived. Maybe the payment service crashed before charging. Maybe it charged the card and then crashed. Maybe it charged the card and the reply got lost on the way back.
From your side, all four look exactly the same: silence. You don’t know. And if you simply retry, you might charge the customer twice.
Welcome to distributed systems. In the last article we looked at splitting an application into services. This one is about what that split really costs, and the small set of ideas that make it safe.
What makes a system “distributed”?
A system is distributed when three things are true:
- It runs as several processes on different machines.
- They talk over a network.
- They fail independently: one can die while the others keep running.
This is not only microservices. A web app with its database on another server is already distributed. So is anything using a cache server, a message queue or a cloud storage bucket.
We accept all this trouble because one machine has hard limits. It can only handle so many requests, hold so much in memory and store so much data. And if it dies, everything dies. Spreading work across machines gives you:
- Scale: share the load across many machines.
- Availability: if one machine fails, others carry on.
- Geography: serve users from a machine near them.
- Isolation: a problem in one part stays in that part.
But it brings problems that simply do not exist inside one process.
Three things a network takes away
Inside a single program, you get three promises for free. Over a network, you lose all three.
| Inside one process | Across a network |
|---|---|
| A call works or the program crashes. You always know which. | A call can work, fail, or end in “I don’t know”. |
| Everything shares memory. Data is just there. | Each machine has its own memory. Data must be copied and can be out of date. |
| There is one clock. “Before” and “after” are clear. | Every machine has its own clock, and they drift. “Which happened first?” gets hard. |
Most of what makes system design hard comes from those three losses.
Latency: the network is very, very slow
Reading something from memory takes about 100 nanoseconds. A call to another server in the same data centre takes about half a millisecond. That sounds tiny, until you compare them.
Here is a famous table of rough latency numbers, with one trick: pretend a memory read takes one second, and scale everything else the same way.
So a single call to another continent costs about as much as 1.5 million memory reads. That changes how you design:
- You can’t make hundreds of network calls per request. Each one adds real time.
- Caching stops being optional. Keep hot data close to where it’s used.
- Every call needs a timeout. You can’t wait forever for an answer.
- Data has to live near its users. Global services keep copies of data in every region and serve video from a CDN, because a cross-world round trip on every click is far too slow.
The most common latency mistake is the N+1 call: fetch a list, then make one network call per item.
// Java · OrderHistory.java
// Bad: 1 call for orders + 100 calls for products = 101 network round trips
List<Order> orders = orderClient.getOrders(userId);
for (Order order : orders) {
Product p = productClient.getProduct(order.productId()); // one network call per order
}
// Better: 2 round trips, however many orders there are
List<String> ids = orders.stream().map(Order::productId).toList();
Map<String, Product> products = productClient.getProducts(ids); // one batch call
Inside one process, the first version is fine. Over a network, it’s a hundred times slower.
Partial failure: the third answer
This is the single biggest change. Go back to the payment call that timed out. There are three possible endings, not two:
You can’t tell these apart from the outside. That’s why distributed systems need ideas that one-process programs never do.
Make retries safe with idempotency keys
If you can’t know whether a request worked, you’ll want to retry it. Retries are only safe if doing something twice has the same effect as doing it once. That property is called idempotency.
For a payment, the client creates a unique idempotency key once, and sends the same key with every retry. The server remembers keys it has already handled:
// Java · PaymentController.java
@PostMapping("/payments")
public Payment charge(@RequestHeader("Idempotency-Key") String key,
@RequestBody PaymentRequest request) {
return payments.findByIdempotencyKey(key) // seen this key before?
.orElseGet(() -> payments.save(gateway.charge(request).withKey(key))); // no: charge once
}
Retry ten times and the customer is still charged once. (In a real system, a unique database constraint on the key makes this safe even when two retries arrive at the same moment.) This is exactly how payment providers like Stripe handle retries.
Slow is worse than dead
Here’s something surprising. A server that crashes is fairly easy to handle: health checks notice, the load balancer stops sending it traffic, and callers get a fast error.
A server that is slow is far more dangerous. It still looks alive, so traffic keeps flowing to it. Every caller waits, holding a thread. Then the callers run out of threads, and their callers start waiting too:
Three tools stop the spread:
- Timeouts: never wait longer than you can afford. A 2-second limit means a stuck call costs 2 seconds, not 30.
- Circuit breakers: after many failures in a row, stop calling that service for a while and fail fast instead. This gives it room to recover.
- Bulkheads: like the sealed compartments in a ship, give each dependency its own small pool of threads. If payments hang, only that pool fills up. Search, browsing and login still work.
And always plan what the user sees. “Your order is placed; payment is processing” is a far better failure than a blank error page.
The eight fallacies of distributed computing
Back in the 1990s, engineers at Sun Microsystems wrote down eight assumptions that developers new to distributed systems make, and that are all false. They’re still the best checklist there is:
| The false assumption | What goes wrong in real life |
|---|---|
| 1. The network is reliable | Packets get lost, connections drop, calls time out |
| 2. Latency is zero | Chatty services turn a 5 ms page into a 500 ms page |
| 3. Bandwidth is infinite | Sending whole objects when you need two fields clogs the pipe |
| 4. The network is secure | Traffic can be read or changed unless it’s encrypted |
| 5. The topology doesn’t change | Servers come and go, and IP addresses change all the time |
| 6. There is one administrator | Different teams own different services, with different rules |
| 7. Transport cost is zero | Turning objects into JSON and back costs CPU and money |
| 8. The network is the same everywhere | Different protocols, versions and hardware behave differently |
Every one of these, assumed true, eventually becomes a production incident. The first one alone explains most outages.
No more single transaction
In a monolith, placing an order is one database transaction. Check stock, charge the card, save the order. If anything fails, the database rolls back everything, as if nothing happened.
Across services, there is no shared database and no shared transaction. If the payment succeeds and then the order service crashes, nothing undoes the payment for you.
The common answer is a saga: a sequence of local steps, where each step has a matching undo step (called a compensation). If a later step fails, you run the undo steps for everything that already happened, in reverse order.
Two details matter. First, each undo is a new action, not a rewind: a refund is a second transaction, so the customer may briefly see both the charge and the refund. Second, slow and non-essential steps, like the confirmation email, go through a queue. If the email service is down, the order still goes through, and the email goes out when it’s back.
Split brain: when both sides think they’re in charge
Many systems have one leader node that accepts writes, with other nodes ready to take over. Now the network between them breaks. The others can’t reach the leader and decide it must be dead, so one of them becomes the new leader.
But the old leader isn’t dead. It’s just cut off. Now there are two leaders, both accepting writes, and the data splits into two versions that disagree. This is called split brain. GitHub hit a version of this in 2018: a network outage of under a minute led to writes landing in two data centres, and the clean-up took about a day.
The standard protection is a quorum: a node can only become leader if a majority of the cluster votes for it. With 5 nodes, you need 3 votes. When the network splits, at most one side can have 3 nodes, so at most one side can elect a leader. The smaller side stops accepting writes and waits.
This is why clusters usually have an odd number of nodes (3 or 5): an even split, 2 and 2, would leave neither side with a majority. Tools like etcd, ZooKeeper and Kafka’s controller all work this way.
Puzzle: a “like” button in two regions
If each region only stored a number, both say 1, and you can’t tell whether that’s the same like twice or two different likes. The answer should be 2.
You have three choices:
- Stay consistent: send every like to one main region. During the outage, EU users can’t like posts at all.
- Stay available: accept likes locally and sync later. Simple, but merging two plain numbers gives the wrong answer.
- Store data that merges correctly: keep the set of user IDs who liked the post, not just a number. US has
{alice}, EU has{bob}. Merging is just a union:{alice, bob}, so the count is 2, whatever order the merges happen in.
That last idea has a name, a CRDT (conflict-free replicated data type): data shaped so that copies can always be merged without conflicts. The bigger lesson: once data lives in two places, even a like button needs design. The choice between staying consistent and staying available is the heart of the CAP theorem, which this notebook covers in depth later.
Key takeaways
- Distribution is not free. You get scale and availability, and you pay with latency, partial failures and harder debugging.
- The network is slow. A call is thousands of times slower than memory. Batch calls, cache, and keep data near users.
- Every call has three outcomes: success, failure and “I don’t know”. Design for the third with timeouts and idempotency keys.
- Slow is worse than dead. Timeouts, circuit breakers and bulkheads stop one sick service from taking down the rest.
- There’s no shared transaction. Use sagas with undo steps, and queues for anything that can wait.
- Use majorities to decide who’s in charge. Quorums prevent split brain.
That completes the Architecture styles thread: monoliths, modular monoliths and microservices decide the shape of your system, and the network decides how it fails. Next, we’ll look at how services actually talk to each other: synchronous calls, messages and events.
Comments