Skip to content

Practical software architecture · Part 9 of 10

Timeouts, retries and circuit breakers

Calls to other systems fail. Set timeouts, retry with backoff and jitter, and use a circuit breaker so one slow dependency does not take everything down.

· 2 min read

architectureresilience

The moment your code calls another system, it inherits that system's bad days. Three small patterns keep a failure from spreading.

Timeouts

A call without a timeout can wait forever and hold a thread, a connection and a user. Set a timeout on every network call, and make it short enough to matter: slightly above the normal worst case, not 60 seconds. Remember to set both a connect timeout and a read timeout.

Retries

Many failures are temporary: a dropped packet, a restarting server. A retry fixes them, but careless retries make outages worse.

  • Retry only idempotent operations, or operations protected by an idempotency key, so a repeat does not charge a card twice.
  • Retry only errors that can be temporary, such as timeouts and 503, not 400 or 404.
  • Limit the attempts, usually two or three.
  • Use exponential backoff with jitter: wait 1, 2, 4 seconds, each with a random variation, so thousands of clients do not retry at the same instant.
Python
import random
import time

def call_with_retries(fn, attempts=3, base=0.2):
    for attempt in range(attempts):
        try:
            return fn()
        except TimeoutError:
            if attempt == attempts - 1:
                raise
            time.sleep(base * (2 ** attempt) * random.uniform(0.5, 1.5))

Circuit breaker

If a dependency is failing, calling it again only wastes time and adds load. A circuit breaker watches recent calls and has three states:

  1. Closed: calls pass normally, failures are counted.
  2. Open: after too many failures, calls fail immediately without touching the dependency.
  3. Half-open: after a pause, a few trial calls are allowed. If they succeed the breaker closes, otherwise it opens again.

Fallbacks

When a call fails, decide what the user sees: a cached value, a default, a reduced feature, or a clear error. A recommendation box that is empty is better than a page that does not load.

Takeaway

Always set timeouts, retry sparingly with backoff and jitter on safe operations, break the circuit when a dependency is down, and decide a graceful fallback in advance.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.