SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Challenges of Distribution
  • Failure Types: Crash vs Byzantine
  • Network Partitions
  • Split Brain Problem
  • Heartbeats
  • Failure Detectors
  • Handling Failures
  • Consistency Models
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed System Fundamentals

Handling Failures

Timeouts, retries, backoff and fallbacks: living with parts that break.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

In a distributed system, something is always broken: a server, a disk, a network link. Handling failures means designing so that a broken part does not break the whole.

  • Detect the failure with timeouts and heartbeats, so nobody waits forever.
  • Retry safe calls, but with backoff and a limit, and only if the call is idempotent.
  • Contain it with circuit breakers and bulkheads, and degrade gracefully with fallbacks and redundancy.

02Concept: What is it?

With one machine, failure is rare and loud: it crashes and everything stops. With hundreds of machines, some part is failing at almost every moment. Disks die, processes run out of memory, networks drop packets, deployments go wrong. The goal is no longer "never fail" but "keep working while parts fail".

The hardest part is that failures are often partial and silent. A call to another service might return an error, or take 30 seconds, or never return, or succeed but lose the reply. From the caller's side, these can look the same. So every remote call needs a plan.

The toolbox for a failing call
⏱️Timeoutstop waiting
→↓
🔁Retrywith backoff
→↓
🔌Circuit breakerstop calling
→↓
🪂Fallbacka lesser answer
Each tool covers one step. Most real systems use several together.
🧠Failure is a normal state
Do not treat failure as an exception to avoid. Treat it as a case to design for, test, and practise, just like the happy path.

03Real-Life Example

🍵The Delivery Company
A parcel company knows that trucks break down, roads close and drivers get sick. So it does not hope for the best. A driver who cannot deliver waits a sensible time, then tries again later (not every second). If a road is closed all day, dispatch stops sending trucks that way and picks another route. There are spare trucks on standby. If nothing works, the customer gets a note: "We will try tomorrow", which is better than silence. And a parcel that was delivered twice by mistake is detected by its tracking number.
Delivery company
Handling failures
Waiting only a set time for a door to open
Timeout
Trying again later, with longer gaps
Retry with backoff
Closing a road that keeps failing
Circuit breaker
A separate truck fleet per city
Bulkhead
Spare trucks on standby
Redundancy and failover
A note saying “Will deliver tomorrow”
Fallback or graceful degradation
The tracking number that stops double delivery
Idempotency key

04Why Do We Need It?

📈Failure grows with size
If one machine fails once a year, a fleet of 1,000 sees a failure about every 9 hours.
🧯Stop the spread
One slow service can fill the threads of every service that calls it. A plan stops that chain.
😊Keep users happy
A page with one missing box is better than an error page.
⏱️Fast failure
A quick, clear error is easier to handle than a call that hangs for minutes.
🔄Recover without humans
Automatic retries and failover fix many problems before anyone wakes up.
📏Meet your promises
Availability targets (like 99.99%) are impossible without planning for failure.
Every network call can fail in many ways. Decide in advance how long to wait, whether to try again, and what to show if it still fails.

05Where Do We Use It?

🔗Service-to-service calls
Every HTTP or gRPC call to another service needs a timeout and a retry policy.
🗄️Database and cache calls
Connections drop, replicas lag, caches go down. Clients retry and fail over.
📨Message processing
Failed messages are retried and finally parked in a dead letter queue.
☁️Cloud infrastructure
Instances are replaced automatically, and traffic moves to another zone when one fails.
💳Payments and orders
Retries must not charge twice. Idempotency keys and sagas keep money safe.
📱Client apps
Mobile and web apps retry with backoff and show cached data while offline.

06Types / Parts / How It Works

Kinds of failures

FailureWhat it looks likeTypical answer
CrashA process or machine stops and sends nothingHeartbeats, restart, failover to a replica
OmissionA message is lost or a request gets no replyTimeout and retry
Timing (slow)It answers, but far too lateTimeouts, deadlines, load shedding
Partial failurePart of a request worked and part did notIdempotency, sagas, compensation
Network partitionTwo groups of machines cannot talkQuorums, choosing consistency or availability
ByzantineA node lies or sends wrong dataChecksums, signatures, byzantine-tolerant protocols (rare)

The main tools

Where each tool sits
Detect
⏱️Timeouts
💓Heartbeats
Recover
🔁Retries + backoff
🔀Failover
Contain
🔌Circuit breaker
🚢Bulkhead
Degrade
🪂Fallbacks
🚰Load shedding
Detect first, then recover, then contain, then degrade.

Retry strategies

StrategyHow it waitsGood and bad
Immediate retryNo waitFast for a single lost packet. Dangerous when the service is overloaded.
Fixed delaySame wait each timeSimple. Many clients retry at the same moments together.
Exponential backoff1 s, 2 s, 4 s, 8 s ...Gives the service room to recover. Needs a maximum delay and a maximum count.
Backoff + jitterBackoff with a random part addedSpreads clients out so they do not all come back at once. The usual best choice.
VisualizerOutage lab: retries can help, or finish off the serviceStart with instant retries and a long outage and watch the load pass the capacity line, so the service cannot recover. Then switch to backoff, and then to backoff plus breaker plus fallback.
How does the client handle a failing service?

On failure, try again at once, up to the number of retries you pick. Looks helpful, but multiplies the load on a service that is already struggling.

Calls reaching the service each second (the line is its capacity, 150/s; red bars are above it)
What users got each second (green = answer, amber = fallback answer, red = error)
The real fault (dark = the dependency is broken, or still overloaded after the fault)
0 s15 s30 s
Served
20%
real answers
Fallback
0%
degraded answers
Errors
80%
~4 s wait each
Peak load
240
capacity 150/s
Recovery
never
after the fault ended
Retry storm: during the outage the service received 240 calls per second, above its 150. Even after the real fault ended it could not catch up, so it never recovered in the 30 seconds shown. The retries that were meant to help are now the problem.

A simplified model with a simulated clock (no random numbers). The service is down from second 6 for the outage length, and it stays down afterwards while it receives more than 150 calls per second. Backoff is modelled as spreading the retries, so about a third of them land in any one second. The breaker opens on the second failing second.

07How to Use It / Steps / Implementation

A checklist for every remote call

  1. 1
    Always set a timeout
    No call should wait forever. Choose it from what users can accept, and make deadlines shrink as a request travels deeper, so a lower service does not work on a request nobody waits for.
  2. 2
    Retry only what is safe
    Retry reads and idempotent writes. For others, add an idempotency key so repeating cannot do the work twice.
  3. 3
    Use exponential backoff with jitter
    Wait longer after each failure and add a random part. Cap both the delay and the number of tries (often 2 to 4).
  4. 4
    Retry in one place only
    If 3 layers each retry 3 times, one user request becomes 27 calls to the bottom service. Retry at the edge, or use a retry budget.
  5. 5
    Add a circuit breaker
    After many failures, stop calling for a while and fail at once. This protects both sides.
  6. 6
    Isolate with bulkheads
    Give each dependency its own pool of threads or connections, so one slow dependency cannot use them all.
  7. 7
    Plan the fallback
    Cached data, default values, a simpler feature, or a clear message. Decide this with the product team, not in the middle of an incident.
  8. 8
    Test failure on purpose
    Kill servers, add delay, drop packets (chaos testing). Failure handling that was never run usually does not work.
⚠️Retries multiply load
When a service is slow because it is overloaded, retries add more load, which makes it slower, which causes more retries. This is a retry storm. Backoff, jitter, retry budgets and breakers exist to stop it.
💡Fail fast, degrade gracefully
A quick "no" lets the caller try something else. Shedding some low-priority work during an overload keeps the important work alive.

08Key Terms to Know

TermMeaning in easy words
Fault vs failureA fault is a broken part. A failure is when the system as a whole stops giving the right service
TimeoutA limit on how long to wait for a reply
RetryTrying a failed call again
Exponential backoffWaiting twice as long after each failed try
JitterA random amount added to a wait, so clients do not retry in step
Retry stormRetries that overload a service and keep it down
IdempotentAn action that has the same result if it is done once or many times
Graceful degradationKeeping a smaller, simpler service when a part is down
FailoverMoving work from a failed machine to a standby
Load sheddingRejecting some requests on purpose so the rest can succeed
Chaos engineeringBreaking things on purpose in a controlled way to find weak spots

09Pros, Cons and Trade-offs

✅ Pros
  • The system keeps working when parts break
  • Users see fewer errors and shorter waits
  • Automatic recovery reduces night-time pages
  • Failures stay small instead of spreading
  • Needed to meet high availability goals
⚠️ Cons
  • More code, more settings, more things to test
  • Retries and failover can hide a real problem
  • Wrong settings make things worse (retry storms)
  • Fallbacks may show old or reduced data
  • Redundancy costs money

Trade-offs

ChoiceWe gainWe lose
Short timeoutFast failure, fewer stuck threadsSlow but healthy calls are cut off
Long timeoutFewer false failuresThreads and users wait, and queues build up
More retriesHide short glitchesHigher load and longer worst-case wait
No retriesSimple and no extra loadEvery small glitch reaches the user
Aggressive circuit breakerStrong protectionMay stay open when the service has already recovered
Fallback dataA working pagePossibly stale or incomplete information

10Common Problems and Mistakes

Common mistakes

  1. No timeout. A hung dependency uses up every thread, and the caller freezes too.
  2. Retrying non-idempotent calls. The customer is charged twice or two emails are sent.
  3. Retries at every layer. Load multiplies at each level and brings the bottom service down.
  4. Retrying instantly, all together. Without backoff and jitter, every client returns at the same moment.
  5. Retrying errors that will never succeed. A 400 (bad request) or 403 (forbidden) will fail every time.
  6. Untested fallbacks. The backup path was never run and fails during the real incident.
  7. Hiding failures. Swallowing errors means nobody knows the system is limping.

Things to watch

🌪️Retry storm
Watch retry rate against normal traffic. A jump means trouble.
🔗Cascading failure
One slow service stalls its callers, which stall theirs. Use timeouts, breakers and bulkheads.
🐌Slow is worse than down
A server that answers very slowly ties up callers longer than one that fails fast.
🎭Gray failure
Something is partly broken, so health checks pass while users suffer. Measure real user requests.

11Real-World Examples

🎬Netflix
Made Hystrix (circuit breakers and bulkheads) and Chaos Monkey, which kills servers on purpose to prove the system survives.
☁️AWS SDKs
Built-in retries with exponential backoff and jitter for most calls.
🔎Google
Uses deadlines that pass down a request chain, and hedged requests that send a second copy if the first is slow.
💳Stripe
Idempotency keys let clients retry payment requests safely.
🛒Amazon
Product pages degrade (for example, hiding recommendations) when a side service is down, so you can still buy.
📨Message systems
Kafka and SQS consumers retry, then send poison messages to a dead letter queue.
📝Note
Defaults such as retry counts and timeouts depend on each library. Read the docs of your client before you rely on them.
Mini case: a product page with a failing reviews service
📱Product page
→↓1 s timeout
⭐Reviews servicefailing
⇢⇣breaker open
🗃️Cached reviewsfallback
Caller Failing Fallback
The page still loads, with the failing part replaced by a fallback.

12Related Topics to Read Next

Challenges of Distribution→

Why failure is the normal case in a distributed system.

Heartbeats→

How a failure is first noticed.

Circuit Breaker→

Stop calling a failing service for a while.

Bulkhead→

Keep one failing part from using up shared resources.

Idempotency→

What makes a retry safe.

Dead Letter Queues→

Where messages go after the retries run out.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Assume: something is always failing. Design for it.
  • ✔Timeout: on every call. Pass a shrinking deadline down the chain.
  • ✔Retry: only idempotent or keyed calls, with exponential backoff, jitter and a cap.
  • ✔One layer: retry in one place, or the load multiplies.
  • ✔Contain: circuit breaker plus bulkhead stop cascades.
  • ✔Degrade: cached data, defaults, shed low-priority work.
  • ✔Danger: retry storms, untested fallbacks, hiding errors.
  • ✔One line: “Wait a limited time, retry politely, stop when it is hopeless, and always have a plan B.”
← Previous
Failure Detectors
Next →
Consistency Models