Building a Resilient HTTP Client with Retries and Rate Limiting
System DesignModel answerLast updated
Design and implement a production-grade HTTP client that handles network failures, respects rate limits, and ensures safe retries.
You're implementing a client library that calls an external HTTP API in a production environment. The service you're integrating with experiences occasional failures, enforces rate limits, and expects clients to handle errors intelligently.
Design a make_request(url, method, payload, headers) function that demonstrates production-ready practices for HTTP communication.
Your Solution Should Address
Error Classification and Recovery
- Which HTTP status codes and exceptions warrant a retry, and which should fail immediately?
- How do you implement exponential backoff without creating retry storms?
Rate Limit Management
- How do you respect the server's
Retry-Afterheader? - What client-side mechanisms prevent your code from overwhelming the API?
Safe Retry Semantics
- Why are POST requests different from GET requests when retrying?
- How do you prevent duplicate operations (duplicate charges, double-creates) when network errors make the outcome ambiguous?
Production Observability
- What metrics and logs would you emit to diagnose issues in a live system?
Constraints and Expectations
- Implement retry logic from scratch (no third-party retry libraries)
- Handle
429 Too Many Requestsand503 Service Unavailableexplicitly - Provide concrete code demonstrating the retry mechanism
- Explain the reasoning behind your design choices, including what could go wrong if you skip each safeguard
Hints
Hint 1
Classify every failure into three categories: success, transient (worth retrying), and permanent (will never succeed). Only transient failures should trigger retries.
Hint 2
For POST and PATCH operations, generate an idempotency token once before the first attempt and reuse it on every retry. This lets the server deduplicate safely.
Hint 3
Add jitter to your exponential backoff—if all clients retry at the same interval, they'll hammer the recovering service simultaneously.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Building a Resilient HTTP Client
Core Strategy
A production HTTP client needs four interrelated mechanisms working together:
1. Outcome Classification
Every call produces one of three outcomes:
- Success (2xx responses)
- Transient failure — temporary conditions worth retrying: connection errors, timeouts, 408 Request Timeout, 429 Too Many Requests, 500/502/503/504 server errors
- Permanent failure — problems that won't resolve with retries: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, invalid JSON in a 2xx response
The distinction matters. Retrying a 401 wastes API quota and delays the inevitable failure. Failing immediately on a 503 throws away requests that would have succeeded moments later.
2. Exponential Backoff with Jitter
Start with a short delay (e.g., 500ms) and double it after each failed attempt, up to a maximum (e.g., 8 seconds). Critically, add full jitter: pick a random delay between 0 and the computed maximum.
Without jitter, all clients that failed at the same instant will retry at the same instant, creating synchronized retry waves that prevent the service from recovering (the "thundering herd" problem). Jitter spreads requests over time.
3. Server-Driven Rate Limiting
When a server returns 429 Too Many Requests, it often includes a Retry-After header specifying how long to wait (in seconds or as an HTTP date). Your backoff logic must honor this value—it overrides your exponential calculation.
Add a client-side token bucket throttle to stay below the rate limit proactively. The bucket refills at the API's documented rate (e.g., 20 requests/second) and blocks attempts when empty. This prevents you from ever seeing 429s in steady-state.
4. Idempotency for Unsafe Methods
GET, PUT, and DELETE are idempotent by HTTP semantics—repeating them produces the same server state. POST and PATCH are not. If you POST a payment, get a read timeout, then retry, you risk charging the customer twice.
Solution: generate a unique Idempotency-Key header before the first attempt and include it on every retry of the same logical request. The server uses this key to deduplicate: if it receives the same key twice, it returns the original result without re-executing.
This makes retries safe even when you cannot determine whether the first attempt succeeded.
Implementation
import email.utils
import logging
import random
import threading
import time
import uuid
import requests
logger = logging.getLogger(__name__)
MAX_RETRIES = 4
TOTAL_TIMEOUT = 25.0
CONNECTION_TIMEOUT = 2.5
READ_TIMEOUT = 10.0
INITIAL_BACKOFF = 0.4
MAX_BACKOFF = 10.0
TRANSIENT_STATUSES = {408, 429, 500, 502, 503, 504}
IDEMPOTENT_VERBS = {"GET", "HEAD", "PUT", "DELETE", "OPTIONS"}
class RequestError(Exception):
"""Base exception for all request failures."""
def __init__(self, msg, status_code=None, response_body=None):
super().__init__(msg)
self.status_code = status_code
self.response_body = response_body
class PermanentError(RequestError):
"""Non-retryable failure (4xx client error, parse failure)."""
class TransientError(RequestError):
"""Temporary failure that may succeed on retry."""
class TokenBucket:
"""Rate limiter using token bucket algorithm."""
def __init__(self, rate, burst):
self.rate = rate # tokens per second
self.burst = burst # max tokens
self.tokens = float(burst)
self.last_update = time.monotonic()
self.lock = threading.Lock()
def try_acquire(self, timeout):
"""Block until a token is available or timeout expires."""
end_time = time.monotonic() + timeout
while True:
with self.lock:
now = time.monotonic()
elapsed = now - self.last_update
self.tokens = min(self.burst, self.tokens + elapsed * self.rate)
self.last_update = now
if self.tokens >= 1.0:
self.tokens -= 1.0
return True
needed = (1.0 - self.tokens) / self.rate
if time.monotonic() + needed > end_time:
return False
time.sleep(needed)
session = requests.Session()
rate_limiter = TokenBucket(rate=15.0, burst=30)
def parse_retry_after(header_value):
"""Parse Retry-After header (seconds or HTTP date)."""
if not header_value:
return None
try:
return max(0, int(header_value))
except ValueError:
try:
date = email.utils.parsedate_to_datetime(header_value)
return max(0, date.timestamp() - time.time())
except (TypeError, ValueError):
return None
def calculate_backoff(attempt, retry_after_header):
"""Compute delay with exponential backoff and full jitter."""
if retry_after_header:
return retry_after_header + random.uniform(0, 0.2)
max_delay = min(MAX_BACKOFF, INITIAL_BACKOFF * (2 ** attempt))
return random.uniform(0, max_delay)
def is_retryable(exc=None, status=None):
"""Determine if an error warrants a retry."""
if exc:
return isinstance(exc, (requests.ConnectionError,
requests.Timeout,
requests.exceptions.ChunkedEncodingError))
return status in TRANSIENT_STATUSES
def make_request(url, method, payload, headers):
"""
Execute HTTP request with automatic retries, rate limiting,
and idempotency protection.
"""
method = method.upper()
headers = dict(headers or {})
# Non-idempotent methods need an idempotency key
if method not in IDEMPOTENT_VERBS:
if "Idempotency-Key" not in headers:
headers["Idempotency-Key"] = str(uuid.uuid4())
start_time = time.monotonic()
last_exception = None
for attempt in range(MAX_RETRIES + 1):
remaining = TOTAL_TIMEOUT - (time.monotonic() - start_time)
if remaining <= 0:
raise TransientError(f"Total timeout exceeded after {attempt} attempts")
# Wait for rate limit token
if not rate_limiter.try_acquire(timeout=remaining):
raise TransientError("Rate limit token unavailable within deadline")
try:
timeout = (CONNECTION_TIMEOUT, min(READ_TIMEOUT, remaining))
if method in ("GET", "DELETE"):
resp = session.request(method, url, params=payload,
headers=headers, timeout=timeout)
else:
resp = session.request(method, url, json=payload,
headers=headers, timeout=timeout)
# Success cases
if 200 <= resp.status_code < 300:
if resp.status_code == 204 or not resp.content:
return {}
try:
return resp.json()
except ValueError as e:
raise PermanentError(f"Invalid JSON in successful response: {e}",
resp.status_code, resp.text)
# Decide retry vs fail
if not is_retryable(status=resp.status_code):
raise PermanentError(f"HTTP {resp.status_code}: {resp.text}",
resp.status_code, resp.text)
# Transient error — will retry
last_exception = TransientError(
f"HTTP {resp.status_code}", resp.status_code, resp.text
)
# Check for backoff instruction
retry_after = parse_retry_after(resp.headers.get("Retry-After"))
except requests.RequestException as e:
if not is_retryable(exc=e):
raise PermanentError(f"Request failed: {e}")
last_exception = TransientError(f"Network error: {e}")
retry_after = None
# Don't sleep after the last attempt
if attempt < MAX_RETRIES:
delay = calculate_backoff(attempt, retry_after)
if time.monotonic() + delay > start_time + TOTAL_TIMEOUT:
break # Would exceed deadline
logger.warning(f"Retry {attempt + 1}/{MAX_RETRIES} after {delay:.2f}s: {last_exception}")
time.sleep(delay)
raise last_exception or TransientError("All retries exhausted")
Why This Works
Bounded execution: The total timeout caps wall-clock time. Each retry's timeout is clipped to remaining budget, so we never block indefinitely.
No duplicate side effects: The idempotency key is created once, outside the retry loop. If a POST times out after the server processed it, the retry delivers the same key, and the server returns the original result without double-charging.
No retry amplification: Permanent errors (bad auth, malformed request) fail immediately. Transient errors back off exponentially with jitter, so retry traffic decays instead of compounding an outage.
Rate limit compliance: The token bucket prevents us from hitting the limit. Retry-After handles cases where our estimate is wrong.
Common Mistakes
- Retrying 4xx errors: A 400 or 403 will never become a 200. Retrying wastes quota and delays the failure.
- No jitter: Synchronized retries create thundering herds that prevent recovery.
- New idempotency key per retry: Defeats the purpose—each attempt looks like a new request to the server.
- Ignoring
Retry-After: Causes your client to be blocked or banned for not respecting the server's explicit instruction. - Unbounded retries: Without a deadline, a persistently failing dependency can make your service hang indefinitely.
Observability
Emit these metrics for every request:
- Counter:
http_requests_total{method, host, status, outcome}where outcome ∈ {success, client_error, server_error, timeout, network_error} - Histogram:
http_request_duration_seconds{method, host}(includes all retries) - Counter:
http_retries_total{method, host, reason}
Log: method, URL, final status, attempt count, total duration, idempotency key (for correlation). On transient failures, log each retry with the backoff delay.
This lets you detect: rate limit exhaustion (high 429 rate), service degradation (rising 5xx or timeouts), client misconfiguration (steady 4xx rate), and retry effectiveness (what fraction of requests succeed after N attempts).
Time Complexity
O(R) attempts where R = MAX_RETRIES. Wall-clock time bounded by TOTAL_TIMEOUT. Space: O(1) beyond request/response bodies.