AI Hints
Home›System Design Tutorial›Resilience Patterns
System Design · Lesson 79 of 120

Retries and Backoff

Try again, politely.

⏱ 2 min read▶ Video at 1:35:04🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Many failures are brief. A network hiccup, or a server restarting. Trying again often works. But if a thousand clients all retry instantly, they can flatten a service that was just recovering.

Retries and Backoff
From the video: Retries and Backoff
  • Many failures are brief
  • Retrying often works
  • But not all at once

Exponential backoff with jitter

The fix is exponential backoff. Wait a little before the first retry, then double the wait each time. And add jitter, a random amount, so clients don't all retry at the same moment. Run it. The waits roughly double each time. Each client's numbers are slightly different, so the retries spread out.

backoff.pypython
import random
random.seed(3)

BASE, CAP = 0.5, 8.0

def backoff(attempt):
    wait = min(CAP, BASE * 2 ** attempt)
    return random.uniform(wait / 2, wait)   # jitter

for client in ["client A", "client B"]:
    waits = [f"{backoff(a):.2f}" for a in range(4)]
    print(f"{client}: waits {waits} seconds")
Output
client A: waits ['0.31', '0.77', '1.37', '3.21'] seconds
client B: waits ['0.41', '0.53', '1.01', '3.67'] seconds

Retry rules

A few rules make retries safe. Only retry errors that might go away, like timeouts and five oh threes, not a four hundred bad request. Only retry idempotent operations, or use idempotency keys. Limit the number of attempts. And add backoff with jitter, always.

keyvalue
Retrytimeouts, 503s
Don't retry400 bad request
Idempotentor use a key
Limit3–5 attempts

Summary

Retries fix brief failures, but must use exponential backoff with jitter, and a limit. Only retry what's safe. Next, what to do when a service is really down.

Key takeaways
  • Wait, then double
  • Add jitter
  • Limit attempts
Next up: Circuit Breakers — stop calling a broken service