Skip to the content

Lesson 238 of 296

Rate limiting, timeouts, retries and circuit breakers

What you will learn

  • Why systems need protection from too much traffic and from slow dependencies
  • Rate limiting algorithms, with code
  • Distributed rate limiting with Redis
  • Timeouts
  • Retries done safely
  • Circuit breakers, bulkheads and graceful degradation
On this page

Why?

Two kinds of danger:

  1. Too much incoming traffic: a bug in a client looping requests, a scraper, a brute-force login attack, a sudden spike. Without limits, one client can take the service down for everyone.
  2. Slow or failing dependencies: a payment API or database becomes slow. Requests pile up waiting, threads and connections run out, and the failure spreads to your service and the services calling it (a cascading failure).

Rate limiting

A rate limiter allows a client a certain number of requests per time window and rejects the rest with 429 Too Many Requests and a Retry-After header (Lesson 194). Limits can be per IP, per user, per API key, per tenant or per endpoint (stricter for login and password reset).

AlgorithmHow it worksProsCons
Fixed windowCount requests per clock window (per minute); reset at the boundaryVery simple, little memoryBursts at boundaries: 100 at 12:00:59 and 100 at 12:01:00 = 200 in two seconds
Sliding window logStore the timestamp of each request; count those in the last 60 secondsExactMemory grows with traffic
Sliding window counterWeighted mix of the current and previous fixed windowsClose to exact, little memoryApproximate
Token bucketA bucket holds up to N tokens, refilled at a steady rate; each request takes oneAllows bursts up to N while enforcing an average rate. Widely used (AWS API Gateway, Stripe)Two parameters to tune
Leaky bucketRequests enter a queue processed at a constant rateSmooth outputBursts are delayed rather than served

A token bucket:

TypeScript
export class TokenBucket {
  private tokens: number;
  private lastRefillMs: number;

  constructor(
    private readonly capacity: number,
    private readonly refillPerSecond: number,
    private readonly now: () => number = Date.now
  ) {
    this.tokens = capacity;
    this.lastRefillMs = now();
  }

  tryRemove(cost = 1): { allowed: boolean; retryAfterSeconds: number } {
    const current = this.now();
    const elapsedSeconds = (current - this.lastRefillMs) / 1000;
    this.tokens = Math.min(this.capacity, this.tokens + elapsedSeconds * this.refillPerSecond);
    this.lastRefillMs = current;

    if (this.tokens >= cost) {
      this.tokens -= cost;
      return { allowed: true, retryAfterSeconds: 0 };
    }
    const missing = cost - this.tokens;
    return { allowed: false, retryAfterSeconds: Math.ceil(missing / this.refillPerSecond) };
  }
}

With capacity = 10 and refillPerSecond = 1, a client can burst 10 requests at once, then make about one per second. The clock is injected (now), so tests can control time (Lesson 206). Keep one bucket per client key, for example in a Map with clean-up of idle entries.

A sliding window log, exact and simple for low limits such as login attempts:

TypeScript
export class SlidingWindowLimiter {
  private hits = new Map<string, number[]>();

  constructor(
    private readonly limit: number,
    private readonly windowMs: number,
    private readonly now: () => number = Date.now
  ) {}

  allow(key: string): boolean {
    const current = this.now();
    const recent = (this.hits.get(key) ?? []).filter((t) => t > current - this.windowMs);
    if (recent.length >= this.limit) {
      this.hits.set(key, recent);
      return false;
    }
    recent.push(current);
    this.hits.set(key, recent);
    return true;
  }
}

Distributed rate limiting

With 10 servers behind a load balancer, in-memory counters give each server its own limit, so a client gets 10 times the allowance. Use a shared store, usually Redis:

  • Fixed window: INCR rate:{user}:{minute} then EXPIRE on the first increment; reject if the count exceeds the limit.
  • Sliding window log: a sorted set per key, with timestamps as scores: ZREMRANGEBYSCORE old entries, ZCARD to count, ZADD the new one.
  • Token bucket: a small Lua script in Redis that reads, refills and takes a token atomically (separate GET and SET commands would race).

Where to rate limit: at the edge (CDN, API gateway, WAF) for crude protection against floods, and in the application for business limits per user, tenant or plan. Return headers such as RateLimit-Limit, RateLimit-Remaining and Retry-After so well-behaved clients can slow down. Lesson 240 designs a full rate limiter service.

Timeouts

Every network call needs a timeout. Without one, a hung dependency holds your request (and its memory, connection and thread) forever.

TypeScript
export async function fetchWithTimeout(url: string, timeoutMs: number): Promise<Response> {
  return fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
}

Choose timeouts from measured latency (a little above the dependency's 99th percentile), and keep them shorter than the caller's timeout, so inner calls fail before the outer request gives up. Also set database statement timeouts and connection timeouts.

Retries, safely

Lesson 204 covered retries with exponential backoff and jitter. In system design add:

  • Retry only idempotent operations or those protected by idempotency keys (Lesson 195).
  • Retry at one layer: if the browser, the API gateway, your service and the SDK all retry 3 times, one failure can become 81 calls (retry amplification).
  • Use a retry budget: for example retries may add at most 10% extra load.

Circuit breakers

When a dependency is failing, continuing to call it wastes time and makes its recovery harder. A circuit breaker wraps calls and stops calling after repeated failures:

StateBehaviour
Closed (normal)Calls go through; failures are counted
OpenAfter too many failures (for example 50% of the last 20 calls), calls fail immediately without contacting the dependency, for a cool-down period
Half-openAfter the cool-down, a few trial calls go through. Success closes the circuit; failure opens it again
TypeScript
type State = "closed" | "open" | "half-open";

export class CircuitBreaker {
  private state: State = "closed";
  private failures = 0;
  private openedAt = 0;

  constructor(
    private readonly failureThreshold: number,
    private readonly coolDownMs: number,
    private readonly now: () => number = Date.now
  ) {}

  get currentState(): State {
    return this.state;
  }

  async call<T>(fn: () => Promise<T>): Promise<T> {
    if (this.state === "open") {
      if (this.now() - this.openedAt < this.coolDownMs) throw new Error("Circuit open: failing fast");
      this.state = "half-open";
    }
    try {
      const result = await fn();
      this.state = "closed";
      this.failures = 0;
      return result;
    } catch (err) {
      this.failures++;
      if (this.state === "half-open" || this.failures >= this.failureThreshold) {
        this.state = "open";
        this.openedAt = this.now();
      }
      throw err;
    }
  }
}

Libraries such as opossum (Node.js) and resilience4j (Java) provide production-ready versions with rolling windows and metrics; service meshes (Istio, Envoy) can do it at the network level.

Bulkheads and graceful degradation

  • Bulkheads: separate resources per dependency (separate connection pools, worker queues or concurrency limits), so one slow dependency cannot use up everything. Named after the compartments in a ship's hull.
  • Load shedding: when overloaded, reject low-priority work early (return 503) to keep critical paths working.
  • Graceful degradation: return a reduced but useful response when a dependency fails: show the product page without personalised recommendations; show cached prices with a "may be out of date" notice; queue the email instead of failing the sign-up.

How to say it in an interview

"I protect services from too much traffic with rate limiting, typically a token bucket per user or API key, which allows bursts but enforces an average rate, or a sliding window for strict limits like login attempts, stored in Redis with atomic operations so the limit is shared across servers, returning 429 with Retry-After. I protect them from slow dependencies with timeouts on every call, shorter than the caller's, retries with backoff and jitter only for idempotent work and only at one layer, and circuit breakers that fail fast when a dependency keeps failing and probe it after a cool-down. Bulkheads isolate resources, load shedding protects critical paths, and graceful degradation keeps the product useful."

Key words

WordMeaning
Rate limiterRestricts how many requests a client may make
Token bucketTokens refill steadily; each request uses one; allows bursts
Sliding windowCounts requests in the last N seconds
Cascading failureOne failing component bringing down others
TimeoutA maximum time to wait for a response
Retry amplificationRetries at many layers multiplying load
Circuit breakerStops calling a failing dependency for a while
BulkheadIsolated resources so one failure does not spread
Graceful degradationReduced but useful behaviour during failures

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.