19/32
Part 4 of 6 · Deques and rate limitsLearn and do

A deque per key, cleaned only when that key sends, never forgets a quiet client

The gateway has many clients. The first idea is a dict from each key to its own deque: the one-key limiter, once per client.

It's correct, and it never forgets anyone. A key's deque is only cleaned when that key sends again. So a client that sent one request and went quiet keeps its deque forever.

Measured with tracemalloc on 100,000 clients sending one request each, a second apart, with a 60-second window:

Memory held at the endKeys held
A deque per key84.23 MiB100,000
One shared log0.01 MiB60

Only the last 60 clients still have a request that counts.

The deque-per-key limiter keeps times_by_key, a dict from each key to a deque of its times. Write sweep, the only way that design can forget a quiet client: clean every key's deque, then delete the keys left empty.