Video in progress
What data structures do you use to build a per-client "N requests in the last 60 seconds" rate limiter in memory?
An exact sliding log needs a queue of timestamps per client, but it eats a lot of memory. In practice I choose a sliding window counter (counters for the previous and current window) or a token bucket, built inside a ConcurrentHashMap with eviction.
📖 Answer
Three classic approaches:
-
Sliding log: an
ArrayDeque<Long>of timestamps per client. When a request arrives, you drop the old timestamps from the head and check the size. It is exact, but if the limit is 1000, that is 1000Longs per client. With 100,000 clients, that is gigabytes. -
Fixed window:
(windowStart, count)per client. Cheap, but twice the load can get through at a window boundary. -
Sliding window counter: counters for the current and previous window, adding the previous one with a weight:
prev * (1 - elapsed/window) + current. Memory is O(1), and the accuracy is enough in most cases.
record Window(long start, int prev, int curr) {}
ConcurrentHashMap<String, Window> state = new ConcurrentHashMap<>();
boolean tryAcquire(String client, long now) {
var allowed = new boolean[1];
state.compute(client, (k, w) -> {
Window cur = roll(w, now); // shift the window if needed
double est = cur.prev() * weight(cur, now) + cur.curr();
allowed[0] = est < LIMIT;
return allowed[0] ? new Window(cur.start(), cur.prev(), cur.curr() + 1) : cur;
});
return allowed[0];
}
compute is atomic for a single key, and other clients run in parallel.
Staff-level questions:
- Eviction. If you don't remove inactive clients, the map grows without limit. Use Caffeine with
expireAfterAccess, or periodic cleanup. - Several instances. A local limiter counts separately on every copy, so with 10 pods the real limit is 10 times higher. The solutions: divide the limit by the pod count (approximate), sticky routing, or central counting in Redis (but that means a network call per request).
- A hot key. One big client puts constant lock pressure on a single bucket; if needed, split its count into several
LongAddercells.
I usually do two layers: a coarse global limit at the API gateway, and a cheap local limiter inside the service.
Sign up to mark studied questions and save your progress.