Distributed Rate Limiting

video locked
Enroll to watch

27 mins

The Oracle and the Timer Wheel

Rate limiting is taking in requests in proportion to how many the server can serve.

Without it, one crash collapses the system. Four servers serve 300 requests each. S2 dies and its requests are distributed, so S3 serves 400 against a capacity of 350 and crashes. S4 gets 600 and crashes. S1 gets 1200 against a capacity of 1000 and crashes too.

The gateway asks an oracle whether to process a request. Each service registers its capacity with the oracle on startup. On a no, the gateway drops the request and sends a 503.

  1. A sliding window. The oracle keeps each request ID and timestamp and allows three requests per minute. It is simple and correct, but the memory footprint is high and expired requests have to be found on every request.
  2. A timer wheel. The wheel's size is the request timeout, six seconds. A request goes to the slot at time mod wheel size. When the pointer reaches a slot, every request in it has expired and is kicked out. The memory footprint is small.

Partitioning and Real-life Optimisations

A service that gets requests from internal services limits their rate itself, because asking the oracle for every internal message is a big deal.

Three metrics show a service under load: the average response time, the age of messages in the queue, and the count of the dead letter queue.

A bad actor S2 fills the queue. The queue is partitioned: the hash of the request ID, mod the number of queues, gives the queue ID. S2's requests all hash to one queue, and the others are fine. With five queues, 20 percent of the users are still affected. More queues, larger queues, or a hierarchical split with a second hash function mitigate this.

  1. Request collapsing. On a cache miss the request is stored against a future object. Clients asking for the same expensive computation wait on the same future, so the database gets one request.
  2. Client side rate limiting. A permanent error is not retried. A temporary error is retried with exponential backoff: a wait of one second, then two, then four, up to 10 seconds.