Resilience and stability patterns
In a system of many services, something is always failing. This chapter shows how to stop one slow or broken service from taking the rest of FTGO down with it, and how to recover when it does.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 17 we made FTGO observable: aggregated logs, metrics and traces, health checks, and alerts on SLOs that measure what users feel. Now the team can see a failure as it happens. That left one problem open: seeing a failure does not stop it from spreading.
How does each FTGO service keep working when the services it depends on are slow, down or wrong? By the end you can pick time-outs, retries, circuit breakers and bulkheads for a call, make repeated work safe, choose between consistency and availability, and test all of it on purpose.
One slow service drags down the rest
On Friday evening the card processor behind the Accounting service slows down. Accounting is not down; each call just takes 30 seconds. Order Service calls Accounting to authorize the card for every new order, so its request threads sit waiting. Soon every thread is busy, and Order Service stops answering anything, even order history. The API Gateway queues requests behind it. Customers see a spinning wheel, press refresh, and send even more requests.
This is a cascading failure: one sick service passes its sickness to every caller up the chain. In the monolith, a slow function was one problem. With microservices, every network call from chapter 4 is a place where this can start.
Adding a retry here or there does not fix this. Resiliency is a wider idea with four parts. Two deal with failures you expect, two with failures you do not.
| Part | What it means for FTGO | Where this chapter covers it |
|---|---|---|
| Robustness | Absorb failures we can predict, such as a slow Accounting call | Time-outs, retries, circuit breakers, bulkheads, redundancy |
| Rebound | Get back to a good state after an outage or a bad release | Rewinding offsets, tested backups, an outage playbook |
| Graceful extensibility | Cope with a surprise by giving up some features, not all | Fallbacks and degraded pages |
| Sustained adaptability | Keep learning from failures so the system keeps getting better | Chaos experiments and blameless game days |
Every resilience mechanism is more code and more configuration, and each one can itself fail. Add them where a failure would hurt, not everywhere by reflex. The first and cheapest one is to stop waiting forever.
Stop waiting forever: time-outs and retries
The Friday outage started because Order Service was willing to wait as long as Accounting took.
Order Service has no time-out on its call to Accounting, so threads hang until the card processor answers. The team adds a 30-second time-out, but that is still far longer than a customer waits. Customers refresh after a few seconds, and every refresh starts another 30-second wait.
Give every network call a time-out that matches how long the caller can afford to wait, and cap the whole operation too. When the time runs out, give up and return an error or a fallback.
Pick the number from your metrics (chapter 17), not from a guess: a little above the normal slow response of the downstream service. Then set an overall budget for the user request. If placing an order may take 2 seconds in total, a call to Accounting that has already used 1.8 of them should not start a fresh 1-second attempt.
Many failures are short: a pod restarting, a brief network blip. Trying again often succeeds.
Retry only errors that can succeed next time, such as a 503 or 504, never a 404 or a validation error. Cap the number of attempts, wait longer before each one (exponential backoff), and add a small random delay (jitter) so callers do not retry in lockstep.
Retries are not free time. Three attempts plus the pauses between them can stretch one call to around 3.5 seconds, so they must fit inside the time-out budget. A smarter variant sends a second request only when the first is unusually slow: Google found that retrying requests that had waited past the 95th percentile latency added only about 2 percent extra load.
A retry sends the same request again, and a time-out does not tell you whether the first request was processed. If Accounting charged the card but its reply was lost, a retry charges it twice. Retries are only safe if repeating the work is safe.
Make repeats harmless: idempotency
Retries create duplicates on purpose, and the messaging from chapter 5 creates them anyway: at-least-once delivery means a consumer can see the same message twice, or see old messages replayed.
A customer complains about a cold meal, and Accounting sends a "refund 10 to consumer 1234" command. The broker delivers it, the consumer crashes before acknowledging, and the broker delivers it again. The customer gets 20 back.
Design each operation so that doing it twice has the same effect as doing it once. Usually this means carrying a unique id or reason with the request, so the receiver can recognize a repeat and ignore it.
A second way is to change what the message says. Take a side example: a restaurant's stock count for a dish. A StockOut event says "subtract one", so a replay subtracts again. A StockChanged event states the new quantity, so a replay sets the same value twice and nothing changes.
The general rule behind this is sometimes called ACID 2.0: operations that are associative, commutative and idempotent, in a distributed system. The CALM theorem gives the reason it works: data built only from facts that accumulate, and never retract, stays correct on an eventually consistent store, whatever order or how many times the facts arrive.
Each operation needs a unique id, and the receiver must store the ids it has processed or reshape its events. Idempotency makes repeats safe, but it does nothing for a service that is down: Order Service still spends a full time-out on every call to a dead Accounting service.
Stop calling a service that is down: circuit breakers
Time-outs bound each wait. They do not stop the next request from waiting just as long.
Accounting is fully down. Order Service now has a 2-second time-out, so each order fails after 2 seconds instead of 30. But at a few hundred orders a minute, Order Service still spends most of its threads waiting for a service that will not answer, and the retries keep hammering Accounting just as it tries to restart.
Wrap the call in a breaker that counts failures. After enough failures it opens and fails every call at once, without touching the network. After a wait it lets a few probe calls through, and closes again only if they succeed.
An open breaker protects both sides. Order Service gets its threads back at once, and Accounting gets quiet time to recover. Because a sick synchronous dependency is the most common start of a cascade, make a breaker mandatory on every synchronous call to another service, typically through the service chassis from chapter 16 or a service mesh.
The same idea works for event consumers. Say Kitchen Service consumes order events and must call a downstream service for each one. When that dependency fails, the consumer stops consuming and does not acknowledge. Events wait safely in the broker and are processed after recovery.
Failing fast is better than hanging, but an error page is still an error page. What should the caller do while the breaker is open? Often it can fall back: use a cached value, a default, or simply leave part of the screen out. This is graceful extensibility in practice.
Build each page and operation so that one failed service removes one feature, not the whole page. Decide the fallback for each dependency in advance.
A breaker needs tuning: open too eagerly and a short blip blocks good traffic, open too late and the threads are already gone. Every fallback is extra behavior to design and test. And a breaker only opens after failures pile up. A service that is merely slow can still exhaust resources that the healthy calls need.
Keep a failure in its compartment: bulkheads
A ship's hull is divided into watertight compartments called bulkheads, so one hole floods one compartment, not the ship. Services need the same thing.
Order Service calls Consumer Service, Kitchen Service and Accounting through one shared HTTP connection pool. Accounting turns slow, but not slow enough to trip its breaker. Its calls hold most of the connections, so calls to Consumer and Kitchen, which are perfectly healthy, wait for a free connection and time out too.
Give each downstream dependency its own limited pool of resources: connections, threads or queue slots. A slow dependency can use up only its own pool.
Bulkheads also work inside a service, between kinds of work. Suppose Restaurant Service handles live menu changes from restaurants and also a nightly bulk import of a large chain's full menu. Both write to the same database cluster. Run the bulk work from its own queue with low parallelism, so it cannot starve live traffic.
Two stronger forms of the same idea:
- Isolation. Run a service on its own machines, or put middleware such as a message broker between caller and callee so the broker buffers calls while the callee is down.
- Load shedding. When a service is overloaded, reject some requests on purpose so it survives for the rest. FTGO might keep accepting orders and drop requests for order history first. That means deciding in advance which work matters most.
Separate pools and queues reserve resources that sit idle most of the time, and full isolation means more infrastructure to run. All of these patterns also assume the service itself is still running somewhere. They do not help when the only machine running Kitchen Service dies.
Survive losing a machine or a zone: redundancy and CAP
So far we protected callers from a sick callee. Now the callee itself must survive hardware and network failures.
All instances of Kitchen Service and its database run in one availability zone of the cloud provider. A power problem takes that zone offline for an hour. Restaurants stop receiving tickets, even though every other zone in the region is fine.
Run several instances of every service, spread across availability zones. A cloud provider promises uptime for a region, not for one machine or one zone.
Stateless instances are easy to copy. The data is the hard part. Once a database has replicas in two places, the network link between them can fail while both sides keep running. This is a network partition, and the CAP theorem describes what it forces on you: a distributed data store cannot give consistency, availability and partition tolerance all at once. Networks do fail, so partition tolerance is not optional. The real choice, during a partition, is between consistency and availability.
| Choice | During a partition | Fits |
|---|---|---|
| CP: stay consistent | Refuse requests that could give a wrong answer | Stock counts, account balances |
| AP: stay available | Keep answering, possibly with stale data, and reconcile later | Menus, product catalogs |
AP systems are eventually consistent, so the useful question for the business is "how stale is acceptable?" Prefer AP where the business allows it: if a dish is occasionally sold after it ran out, the restaurant can apologize and offer a refund. The choice is per capability, not per system. In a side example, a loyalty-points service can show a slightly stale balance, but must be consistent at the moment points are spent. One system can mix AP and CP services.
Redundancy needs capacity for the extra copies. AP means stale reads and merge logic; CP means some requests fail during a partition. And no amount of redundancy helps when the failure is in our own code: a bad release copies bad data to every replica.
Recover after the blow: poison events and rewinding
Robustness keeps failures out. Rebound is about getting back to a good state when they got in anyway.
A new release of Kitchen Service has a bug in how it reads order events. Before anyone notices, it processes the events at offsets 137 to 141 and creates tickets with the wrong items. Separately, one malformed event makes the consumer crash every time it reads it, so the whole queue behind it stops.
Handle the two cases differently:
- Poison events. An event that fails validation will never succeed, so log it and skip it instead of retrying forever. If the event is valid but our code has a bug, fix the code and reprocess. When many good events have already arrived after the bad one, a dead letter queue lets you park the bad event and keep going.
- Bad processing. If the service consumes from a log-based broker that keeps history, you can repair state by replaying.
Roll back or fix the code, move the consumer's offset back to before the bug, and reprocess. Because processing is idempotent, events that were already handled correctly are harmless; only the corrected results produce new events.
Rebound is also about people. It needs backups that have actually been restored in a test, and an outage playbook written before the stress hits: who leads the response, how fast FTGO tells customers and restaurants, and through which channel.
Replay needs a broker that keeps history long enough, and consumers that are truly idempotent. Wrong events stay in the log forever, with corrections after them. And a playbook, a backup or a breaker setting that has never been exercised is only a hope: we will not know whether any of it works until the next real outage.
Prove it before the outage: chaos engineering and game days
Every pattern in this chapter is configuration and code that only runs when something goes wrong, which is exactly the code nobody exercises.
FTGO has breakers, time-outs and three availability zones on paper. Then a zone really fails. The time-outs turn out to be longer than the gateway's, the failover script has a typo, and the one engineer who knows the Accounting database is on holiday.
Break things on purpose, in a controlled way, to find weaknesses before customers do. Chaos engineering runs experiments that build confidence in how the system behaves in production. Game days are planned drills that test the people and the process too.
The "observe" step depends on chapter 17: the SLOs and traces tell you whether users noticed. Netflix popularized tools that automate the "inject" step:
| Practice | What it tests | Example |
|---|---|---|
| Chaos Monkey | Instance loss | Turns off random machines in production |
| Chaos Gorilla | Zone loss | Takes out an availability zone |
| Latency Monkey | Slow network | Simulates slow links between machines |
| Game day | People and process | Planned outage drill; the key expert is kept out of the room |
The "learn" step is blameless: the aim is to fix the system, not to find a culprit. That loop of experiment, learn and change is what sustained adaptability looks like day to day.
Experiments in production carry real risk, so start small, with a clear way to stop, and only once monitoring can show the impact. Every fix the experiments reveal is another change to ship, across dozens of services, without breaking production in the process.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Time-out | Threads hang forever on a slow downstream service | Must be tuned from metrics; a time-out does not say whether the work was done |
| Retry with backoff and jitter | Short, temporary failures fail the whole request | Adds wait time and load; creates duplicates |
| Idempotent operations | Retries and at-least-once delivery apply work twice | Unique ids to store, or events reshaped to carry state |
| Circuit breaker | Callers keep waiting on a service that is down, and keep hammering it | Thresholds to tune; slow-but-alive services can still slip through |
| Graceful degradation | One failed service blanks a whole page or operation | A fallback to design and test for each dependency |
| Bulkhead | One slow dependency or bulk job uses up shared resources | Reserved resources that often sit idle |
| Isolation | A failing callee takes its callers down with it | More infrastructure, such as separate machines or a broker |
| Load shedding | Overload crashes a service for everyone | Some requests are rejected; priorities must be decided up front |
| Redundancy across zones | Losing a machine or a zone takes a service offline | Extra capacity; replicated data forces a CAP choice |
| CP or AP per capability | A network partition between replicas | CP refuses some requests; AP serves stale data and must reconcile |
| Dead letter queue and offset rewind | Poison events block a queue; a bug corrupts processed state | Broker must keep history; consumers must be idempotent |
| Chaos engineering and game days | Resilience mechanisms that have never been exercised | Controlled risk in production; needs good observability |
Recap
- In microservices a single slow service can cascade through every caller, so each network call needs a time-out within an overall budget and retries that are capped, backed off and limited to temporary errors.
- Retries and at-least-once messaging both repeat work, so operations must be idempotent and consumers must acknowledge only after processing.
- A circuit breaker fails fast when a dependency is down, a fallback degrades the page instead of breaking it, and bulkheads keep one slow dependency or bulk job from draining shared resources.
- Redundancy across availability zones survives hardware loss, but replicated data forces a choice between consistency and availability during a partition, made per capability.
- Rebound needs a plan: skip or park poison events, rewind offsets to repair state after a bug, and keep tested backups and an outage playbook.
- Chaos experiments and game days exercise all of this on purpose, and blameless learning from them keeps the system adapting.
Quick check
Show answer
Slow calls tie up Order Service threads, and the refreshes and immediate retries add even more load, so a sick Accounting drags Order Service down with it. Use a shorter time-out inside an overall request budget, retry only temporary errors with backoff and jitter, add a circuit breaker so calls fail fast while Accounting is down, and give Accounting its own bulkhead pool. Make the authorization idempotent so a retry cannot charge the card twice.
Show answer
Messages that were received and acknowledged but not yet processed are lost when the old instance stops, so some orders never become tickets (a message leak). Acknowledge only after processing. That can deliver a message twice after a crash, so ticket creation must be idempotent, for example by ignoring an order id it has already handled.
Show answer
No. The choice between consistency and availability is per capability. The menu can stay available and serve slightly stale data (AP). The stock count may need to stay consistent (CP), refusing some updates during the partition, unless the business accepts the occasional oversold dish and apologizes.
FTGO's services can now survive slow, failed and buggy neighbors. But surviving failure is not enough: the team must ship dozens of services, each with its own fixes and settings, to production safely and often.
Resilience patterns: common questions
What does a circuit breaker do?
After repeated failures it stops calling the failing service for a while and fails fast, then lets a few test calls through to see if it has recovered.