8/17
Part 4 of 7 · Many serversLearn

One limit across many servers needs a shared count

The shop runs 5 API servers behind a load balancer. Each could keep its own buckets, holding a fifth of each customer's limit. Envoy's local rate limits work that way: per process, by default.

Here's a script that asks once a second for 10 minutes, against the shop's limit of a burst of 5, then 10 a minute. The first two runs split the limit across 5 servers. The last one shares a single bucket.

import random


def served(route, servers=5, seconds=600):
    """A script asks once a second for 10 minutes. Its limit: a burst of 5, then 10 a minute."""
    local = [TokenBucket(5 / servers, 1 / 6 / servers) for _ in range(servers)]
    return sum(local[route()].allow(t) for t in range(seconds))


rng = random.Random(7)
print("5 local buckets, requests spread at random:", served(lambda: rng.randrange(5)))
print("5 local buckets, one connection to one server:", served(lambda: 0))
shared = TokenBucket(5, 1 / 6)
print("one shared bucket:", sum(shared.allow(t) for t in range(600)))
Predict

One shared bucket lets 104 of the script's requests through. All of them ride one connection, so one server sees every request. About how many get through the 5 local buckets?

Pick one to see what it prints.
Pick an answer above to see the rest