Skip to content

Timeouts and circuit breakers

Working knowledgeConcept

Your service calls a payment provider. One day the provider does not fail, it just gets slow, and your service falls over too. A timeout stops each wait; a circuit breaker stops the calls.

01 Slow is worse than down

When a dependency is down, calls to it fail at once with "connection refused". Your code handles the error and moves on. When it is slow, each call just waits, and holds something while it waits: a thread, a connection, memory.

Watch a small pool of workers meet a provider that has gone from fast to 30 seconds per call.

No timeout: the pool runs dry
Step 1 of 7
Worker threads (a toy pool of 4)
free
free
free
free
Requests waiting for a worker
Empty
  • just started waiting
  • stuck waiting
  • just queued

Your checkout service has 4 worker threads. Each request holds one while it calls the payment provider, which normally answers in well under a second.

healthy provider

This is a cascading failure: the problem spreads from the provider to you, and from you to whoever calls you. Two tools stop it. A timeout caps how long one call may wait. A circuit breaker stops making calls that are likely to fail.

02 A timeout: stop waiting

A timeout turns "wait forever" into "wait at most this long, then raise an error". Many HTTP clients have no timeout by default. Python’s requests is one: without timeout=, a call can block indefinitely.

Python
import requests
# (connect timeout, read timeout) in seconds
r = requests.post(PROVIDER_URL, json=charge, timeout=(3, 2))
r.raise_for_status()

Pick the number from what the dependency normally does, not from hope. Look at its slow end, its 99th percentile latency, and set the timeout a little above it. If 99% of calls finish in 400 ms, waiting 30 seconds for the rest only holds threads.

No timeoutThread held 30 sFour slow calls fill the pool, and the service stops answering anything.
2-second timeoutThread freed after 2 sCheckout fails with a clear error; basket pages and health checks keep working.

03 Budgets, not separate numbers

A request often calls several services in a row. If each call has its own fixed timeout, the total can be far longer than your user will wait. Give the whole request a deadline and pass the time that is left to each call.

A checkout request with a 1-second deadline
CallTime usedTime left for the next call
(start)0 ms1000 ms
Load basket120 ms880 ms
Check stock200 ms680 ms
Charge cardat most 680 ms0 ms: give up

gRPC builds this in: a client sets a deadline, the remaining time travels with the call (the grpc-timeout header), and a server can hand the same deadline to its own calls. In Go, context.WithTimeout does the same job inside one process.

04 A circuit breaker: stop calling

Timeouts free your threads, but you still spend up to 2 seconds on every call while the provider is sick, and you keep sending it traffic it cannot handle. A circuit breaker watches the results. After enough failures, it stops calling for a while and fails at once instead.

  • Closed: calls pass through. Failures are counted.
  • Open: calls are rejected without being made, for a cool-down period.
  • Half-open: after the cool-down, a trial call is let through. Success closes the breaker; failure opens it again.
A breaker that trips after 3 failures
Step 1 of 10
Breaker state
tripswaitokfail
Closedcalls pass
Openfail fast
Half-openone trial
Calls to the provider
Empty
  • breaker state now
  • transition taken
  • call failed
  • rejected, not sent
  • call succeeded

The breaker starts closed: calls go through to the provider as normal. It trips after 3 failures in a row and stays open for 10 seconds.

0 of 3 failures in a row

05 A breaker in 30 lines

Here is the whole idea in Python. It counts failures in a row and remembers when it opened. Libraries such as resilience4j (Java), Polly (.NET) and pybreaker (Python) add sliding windows, metrics and thread safety on top of the same three states.

breaker.py
import time
class CircuitOpen(Exception):
pass
class CircuitBreaker:
def __init__(self, max_failures=3, cool_down=10.0):
self.max_failures = max_failures
self.cool_down = cool_down
self.failures = 0
self.opened_at = None # None means closed
def call(self, fn, *args, **kwargs):
if self.opened_at is not None:
Python
breaker = CircuitBreaker(max_failures=3, cool_down=10.0)
def charge(order):
def call():
r = requests.post(PROVIDER_URL, json=order, timeout=(3, 2))
r.raise_for_status() # count 5xx answers as failures too
return r.json()
return breaker.call(call)

This toy lets every caller through once the cool-down ends. Under real traffic, hundreds of requests would hit the provider at the same moment. A real half-open state lets through one call, or a small number, and rejects the rest until they report back.

06 What to do when the breaker is open

Failing fast is only half the job. Decide what the user gets instead, per feature.

  • Serve something older: recommendations or prices from a cache, marked as possibly stale.
  • Leave a part out: show the page without the reviews panel.
  • Queue it for later: accept an email request and send it when the provider recovers.
  • Say so clearly: for a payment, never pretend it worked. Return a clear "try again in a minute".

07 Where timeouts and breakers go wrong

timeout=2A read timeout is not a total timeoutIn requests, the read timeout is the longest gap between bytes, not the time for the whole response. A server that trickles one byte a second never trips it. Enforce an overall deadline separately when that matters.
Inner timeout longer than the outer oneIf your caller gives up after 1 second but you wait 5 seconds on your dependency, you keep working on an answer nobody will read. Inner timeouts should be shorter.
404, 400Counting client errors as failuresA 404 means the provider is healthy and the thing is missing. Count timeouts, connection errors and 5xx, or one bad input pattern can trip the breaker for everyone.
One breaker for everythingOne breaker around a whole provider opens when a single slow endpoint fails, and blocks the healthy ones too. Use one per dependency and endpoint group, sometimes per host.
Retries inside the breakerIf each call retries 3 times before the breaker sees a result, the provider gets three times the load just as it is failing. Put retries outside, so an open breaker stops them too.

08 Check yourself

Question

A dependency’s calls take 200 ms at the 99th percentile. Which timeout makes most sense?

Question

The breaker is open. What happens to a call?

Question

The provider has just come back, but it is still warming up. Why does a good half-open state let only one call (or a few) through, not every waiting caller?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?