AlgoViz

Design a rate limiter

medium 75 min

A rate limiter inside one process: token bucket behind an interface, exact under threads, several rules at once, and keys that are safely forgotten.

Watch lesson4:49

Where it shows up

The same pattern appears across everyday software.

  • Guava RateLimiter for Java

    Gives out permits at a steady rate and makes callers wait. The cost of a large request is paid by the next one. Its source keeps the time of the next free ticket and works the stored permits out when asked.

  • golang.org/x/time/rate

    A token bucket with three ways in: allow or refuse, reserve a time, or wait. A reservation can be cancelled.

  • Bucket4j for Java

    A token bucket that works with whole numbers only, to avoid rounding errors. The default in memory is lock-free, other ways of locking can be chosen.

  • Resilience4j RateLimiter

    Divides time into cycles with a number of permissions each. The default keeps an immutable state in an atomic reference and skips work for limiters that nobody uses.

  • nginx limit_req

    The leaky bucket method for each key, for example each address. `burst` says how many may wait, `nodelay` lets them through at once.

  • Envoy local rate limit

    A token bucket in each Envoy process, with a 429 answer when it is empty. It needs no other service.

  • .NET System.Threading.RateLimiting

    One abstract limiter with token bucket, fixed window, sliding window and concurrency versions, and partitions for keys. Callers get a lease to dispose.

  • AWS API Gateway

    Throttles with a token bucket: a steady rate and a burst. Its guide says to see the limits as targets and not as guaranteed ceilings.

  • Stripe's API

    Their engineering blog describes a token bucket for request rates and a second limiter for how many requests are in progress at once.

  • Linux traffic control, tbf

    The token bucket filter slows the packets of an interface. Tokens arrive at a steady rate until the bucket is full, and packets queue when none are there.