A rate limiter and a cache, with tests

: the Redis board on what to throw away when a store is full. The cache you build here makes the same choice, and adds a second reason to throw an entry away: it has expired.
On 2017-03-30, Paul Tarjan of Stripe published a post called “Scaling your API with rate limiters”. It says Stripe runs four kinds of limiter: a request rate limiter, a concurrent requests limiter, a fleet usage load shedder and a worker utilization load shedder. For the first one, the post says: “We use the token bucket algorithm to do rate limiting.” Every company that offers an API faces the same problem. One caller sends too many requests, and everyone else gets slow answers.
A cache has the opposite problem. It exists to keep answers close, but memory is small and old answers go stale. Both tools are short, and both fail in the same quiet way when two threads use them at once.
By the end you will be able to write a token bucket, a sliding window, and an LRU cache with expiry. You will also be able to prove, with tests, that they stay correct when sixteen threads hit them together.
Before you start. HTTP 08: Everything ended with a server that must refuse work it cannot finish, so this lesson builds two tools for that. Design a rate limiter drew the limiter as a design, and Design an LRU cache (a map and a list that keep each other honest) drew the cache. Here you write both as running code. Eviction: Memory Is Full showed how Redis picks what to evict. HTTP Server: Concurrency showed one server answering many callers at once, which is the situation that makes locks necessary.
The history (optional)
Stripe’s 2017 post is the source for the four limiter types and for the sentence about the token bucket. Nothing later in this lesson depends on it. The code below is written from the ideas, not copied from that post.