Chapter 18 of 27 · Part 8: Cross-cutting concerns

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

Where we are

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.

This chapter

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

Problem

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.

A cascading failure Accounting is slow. Order Service threads all wait on it, and requests pile up at the API Gateway. API Gateway requests pile up Order Service all threads waiting Accounting slow, not down waits waits 30 s Every blocked thread in Order Service is one more request the gateway cannot serve.

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.

Four parts of resiliency Dealing with the expected Robustness: absorb known shocks Rebound: recover after a blow Dealing with the unexpected Graceful extensibility: cope Sustained adaptability: keep changing More robustness adds complexity, which is a new source of failure.
PartWhat it means for FTGOWhere this chapter covers it
RobustnessAbsorb failures we can predict, such as a slow Accounting callTime-outs, retries, circuit breakers, bulkheads, redundancy
ReboundGet back to a good state after an outage or a bad releaseRewinding offsets, tested backups, an outage playbook
Graceful extensibilityCope with a surprise by giving up some features, not allFallbacks and degraded pages
Sustained adaptabilityKeep learning from failures so the system keeps getting betterChaos experiments and blameless game days
Cost

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.

Problem

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.

Solution · Time-out

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.

Solution · Retry with backoff

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.

Cost

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.

Problem

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.

Solution · Idempotent operations

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.

Making a refund idempotent Not idempotent refund 10 to consumer 1234 Replay: 20 refunded Idempotent refund 10, reason: order 77 Replay: ignored, still 10 Add the reason or id, and the receiver can spot a repeat.

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.

Designing an idempotent event StockOut subtracts again on replay. StockChanged carries the current quantity and is safe to repeat. StockOut { Quantity: 1 } replayed twice = stock down by 2 order agnostic, not idempotent StockChanged { CurrentQuantity: 5 } replayed twice = same result needs versioning for order or Trade-off: StockChanged is safe to retry but carries less intent. Or keep StockOut and store processed ids.

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.

Acknowledge after processing, not on receipt. If a consumer auto-commits a message as soon as it arrives and then crashes or is redeployed, the message is lost while it sat in memory (a message leak). Acknowledging late can cause duplicates, which idempotency now makes safe. Losing messages is not safe.
Cost

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.

Problem

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.

Solution · Circuit breaker

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.

Circuit breaker states Closed calls flow through Open fail fast Half-open probe a few calls too many failures after a wait probes healthy: reset If the probes fail, the breaker opens again.

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.

Circuit breaker around a dependency Failures over a threshold open the breaker and stop consumption; after a pause a probe decides whether to close it. Closed events flow Open stop, do not ack Half-open probe dependency threshold hit after a pause probe succeeds: resume consuming Events pile up in the broker during the outage and are processed after recovery. A fallback such as an in-memory cache can replace the dependency.

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.

Solution · Graceful degradation

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.

Degrading functionality Restaurant page Menu up: shown Restaurant page Delivery estimate up: shown Restaurant page Past orders down: hide it One failed service should remove one part of a page, not the whole page.
Cost

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.

Problem

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.

Solution · Bulkhead

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: a connection pool per downstream service Order Service calls 3 services Consumer pool Consumer Kitchen pool Kitchen Accounting pool Accounting Accounting is slow and drains only its own pool. Consumer and Kitchen keep working.

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.

Bulkhead and priority queues A bulk job gets its own low-parallelism queue so it cannot starve live traffic on the shared database. Live menu changes high parallelism Bulk menu import low parallelism Restaurant Service parallelism per queue Shared database one cluster Lower the parallelism or instance count of the noisy work. It runs slower, but nobody else suffers.

Two stronger forms of the same idea:

Pair it with scale: use bulkheads for dependencies you cannot isolate (a shared database cluster, a cache, a synchronous call). Separate clusters are cleaner but often not worth the cost.
Cost

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.

Problem

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.

Solution · Redundancy

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.

A partition forces a choice Data center 1 Data center 2 Restaurant + DB accepts writes Restaurant + DB accepts writes link down AP: keep answering data may be stale, merge later CP: refuse some requests answers stay consistent Choose per capability: the menu can be AP, a dish's stock count may need CP.
ChoiceDuring a partitionFits
CP: stay consistentRefuse requests that could give a wrong answerStock counts, account balances
AP: stay availableKeep answering, possibly with stale data, and reconcile laterMenus, 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.

Do not build your own consistent store. Multi-node consistency is very hard to get right. Use an off-the-shelf data store or lock service built for it, such as Consul.
Cost

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.

Problem

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:

Solution · Rewind the offset

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.

Repairing state by rewinding the offset After a buggy release the service rewinds its offset and reprocesses; only corrected orders produce new events. Bug released offsets 137-141 bad Roll back fix the code Rewind offset from 147 to 137 Reprocess state repaired Idempotency makes the already correct events harmless. Wrong events stay in history; corrected ones follow.

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.

Cost

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.

Problem

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.

Solution · Chaos engineering and game days

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.

A chaos experiment or game day Plan pick a weakness Inject fail a node Observe did users notice? Learn fix it, no blame Chaos engineering = experiments that build confidence in production resilience.

The "observe" step depends on chapter 17: the SLOs and traces tell you whether users noticed. Netflix popularized tools that automate the "inject" step:

PracticeWhat it testsExample
Chaos MonkeyInstance lossTurns off random machines in production
Chaos GorillaZone lossTakes out an availability zone
Latency MonkeySlow networkSimulates slow links between machines
Game dayPeople and processPlanned 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.

Cost

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

PatternProblem it solvesWhat it costs
Time-outThreads hang forever on a slow downstream serviceMust be tuned from metrics; a time-out does not say whether the work was done
Retry with backoff and jitterShort, temporary failures fail the whole requestAdds wait time and load; creates duplicates
Idempotent operationsRetries and at-least-once delivery apply work twiceUnique ids to store, or events reshaped to carry state
Circuit breakerCallers keep waiting on a service that is down, and keep hammering itThresholds to tune; slow-but-alive services can still slip through
Graceful degradationOne failed service blanks a whole page or operationA fallback to design and test for each dependency
BulkheadOne slow dependency or bulk job uses up shared resourcesReserved resources that often sit idle
IsolationA failing callee takes its callers down with itMore infrastructure, such as separate machines or a broker
Load sheddingOverload crashes a service for everyoneSome requests are rejected; priorities must be decided up front
Redundancy across zonesLosing a machine or a zone takes a service offlineExtra capacity; replicated data forces a CAP choice
CP or AP per capabilityA network partition between replicasCP refuses some requests; AP serves stale data and must reconcile
Dead letter queue and offset rewindPoison events block a queue; a bug corrupts processed stateBroker must keep history; consumers must be idempotent
Chaos engineering and game daysResilience mechanisms that have never been exercisedControlled risk in production; needs good observability

Recap

Quick check

Order Service calls Accounting with a 30 s time-out and retries three times with no pause. Accounting slows down and customers start refreshing. What goes wrong, and what helps?
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.

Kitchen Service consumes order events with auto-commit on receipt. It is redeployed in the middle of a busy lunch. What can happen, and what should change?
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.

FTGO replicates restaurant data across two data centers, and the link between them fails. Should the menu and a dish's remaining stock behave the same way?
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.

Still open

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.

Next: 19 Deployment patterns and Kubernetes →

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.