LLD

Full Designs

Rate Limiter

A weak answer counts requests in a map and stops. We build the limiter an API server actually needs: two ways of counting behind one interface, exact arithmetic for a bucket that refills a little every nanosecond, a refusal that says when to try again, idle clients forgotten without changing a single answer, and one lock per client that holds up when many threads ask at once.

"Design a rate limiter" sounds like a counting problem. A weak answer keeps a map from client to a count, resets it every minute, and stops. That code works until a client sends five requests at 59 seconds and five more at 60, or two threads read the same count at once, or the map holds every client who ever called.

The interviewer is checking whether you can turn a limit like "5 requests per minute" into code that is exact, testable and safe under many threads. What does each way of counting let through? Where does time come from, so a test does not wait a minute? What does a refused client hear? When can a client be forgotten? What stops two threads from both taking the last permit?

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

This is the limiter inside one server. Limiting across many servers with a shared store is a different question, and the System Design course covers it.

The limiter at a glance
A server thread asks the RateLimiter whether asha-app on the FREE tier may make one request (1). Before any lock is taken, tryAcquire checks the request and the RuleBook gives the tier's rule, 5 per minute counted with a sliding log (2). Holding the map's lock for this client, the limiter reads the Ticker (3). The client's Limiter, made on its first request, decides and returns an Outcome (4). The Outcome goes back to the server, refused with a retry time of 30 s, so the server can answer 429 (5). Every few minutes a job forgets clients whose limiters are idle (6).A server thread asks the RateLimiter whether asha-app on the FREE tier may make one request (1). Before any lock is taken, tryAcquire checks the request and the RuleBook gives the tier's rule, 5 per minute counted with a sliding log (2). Holding the map's lock for this client, the limiter reads the Ticker (3). The client's Limiter, made on its first request, decides and returns an Outcome (4). The Outcome goes back to the server, refused with a retry time of 30 s, so the server can answer 429 (5). Every few minutes a job forgets clients whose limiters are idle (6).
One rule per tier, one limiter per client, one lock per client. A server thread asks the RateLimiter whether asha-app on the FREE tier may make one request (1). Before any lock is taken, tryAcquire checks the request and the RuleBook gives the tier's rule, 5 per minute counted with a sliding log (2). Holding the map's lock for this client, the limiter reads the Ticker (3). The client's Limiter, made on its first request, decides and returns an Outcome (4). The Outcome goes back to the server, refused with a retry time of 30 s, so the server can answer 429 (5). Every few minutes a job forgets clients whose limiters are idle (6).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
Who is limited?Each client, found by its API key, on its tierA map from client and tier to that client's limiter
What is the limit?So many requests per period, set per tier in configurationA Rule per tier, checked at startup
Can a quiet client send a short burst?It depends on the tier, so both behaviours are neededTwo ways of counting behind one interface
What happens to a request over the limit?It is refused at once, with the time to retryAn answer that carries the retry time; nobody waits
Can one request cost more than one permit?Yes, a batch call costs one permit per itemtryAcquire takes a number of permits, all or none
One server or many?One server, everything in memoryNo shared store; that is a different design
How many clients?Millions over a day, most of them idleLimiters are made on first use and forgotten when idle
Do many threads ask at once?Yes, often for the same clientOne lock per client, not one for the whole limiter
Where does the time come from?A clock we can control in testsA Ticker interface instead of reading the system clock

The question about bursts matters most. "5 per minute" can mean "never more than 5 in any 60 seconds" or "5 at once, then one every 12 seconds". Those are two different algorithms, and they let different traffic through.

Requirements

Functional:

  1. tryAcquire(client, tier, permits) allows the request if the client's limit has room for all the permits, and takes them. Otherwise it refuses and takes none.
  2. A refusal says how long until the same request would be allowed, if nothing else used the limit first. Every answer says how many permits are left.
  3. Each tier has a rule: a limit, a period and a way of counting. The rules come from configuration, and a bad rule or a missing tier stops the server at startup.
  4. Two ways of counting: a sliding window log, which never allows more than the limit in any period, and a token bucket, which allows a full burst and then refills steadily.
  5. A request that costs 0 permits, or more than the whole limit, is refused with an exception, because it is a bug in the caller.
  6. A client whose limiter is idle can be forgotten, and forgetting it never changes an answer.

Out of scope: limits shared by many servers, rules that change while the server runs, a limit per endpoint, and requests that wait for a permit. We come back to these at the end, because each is a natural follow-up, and a design that bends towards them is part of the answer.

Everything lives in memory, in one process.

What the code itself must handle:

  • Many threads at once. Requests for one client arrive on many threads together, and no permit may be granted twice.
  • A rule that changes. A tier may move from one way of counting to the other, and the limiter class should not change for that.
  • Time. Refills and windows must be testable to the nanosecond, so the code never reads the system clock itself.

Finding the classes

A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.

From nouns to classes
The rate limiter becomes the RateLimiter class and the configuration the RuleBook. The limit and period become a Rule record and the plan a Tier enum. The way of counting becomes the Limiter interface, with TokenBucket and SlidingWindowLog behind it. A client on a tier becomes a LimitKey record, the answer an Outcome record, and time the Ticker interface. Four nouns are dropped. A client is only a key. A request is a call that is never stored. The 429 response is the server's job. A waiting line is not needed, because a refusal says when to retry.The rate limiter becomes the RateLimiter class and the configuration the RuleBook. The limit and period become a Rule record and the plan a Tier enum. The way of counting becomes the Limiter interface, with TokenBucket and SlidingWindowLog behind it. A client on a tier becomes a LimitKey record, the answer an Outcome record, and time the Ticker interface. Four nouns are dropped. A client is only a key. A request is a call that is never stored. The 429 response is the server's job. A waiting line is not needed, because a refusal says when to retry.
Most nouns become classes. The client does not. The rate limiter becomes the RateLimiter class and the configuration the RuleBook. The limit and period become a Rule record and the plan a Tier enum. The way of counting becomes the Limiter interface, with TokenBucket and SlidingWindowLog behind it. A client on a tier becomes a LimitKey record, the answer an Outcome record, and time the Ticker interface. Four nouns are dropped. A client is only a key. A request is a call that is never stored. The 429 response is the server's job. A waiting line is not needed, because a refusal says when to retry.

The client needs the most thought. It is the thing being limited, so it sounds like the centre of the design.

Decision

Should a client be a class?

A Client class with its tier and its own limiter

The client and its limit sit together, which reads well. But the limiter does not own clients: accounts, keys and tiers live in another service. A Client here would copy that data, and the limiter would need to keep the copy up to date.

A key: the client's id and its tier, in a map to its limiterOur pick

LimitKey is a record of two fields, and the map is the only place that ties a client to its limiter. A client that moves to another tier gets a new key and a fresh limit. The cost is that the limiter knows nothing about a client beyond its id, which is all it needs.

Data or behaviour?

Some classes only carry data and never change once created. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString without writing them.

limiter/LimitKey.javalines 7–14 of 14
/** Whose limit this is: one client on one tier. */record LimitKey(String clientId, Tier tier) {     LimitKey {        Objects.requireNonNull(clientId, "clientId");        Objects.requireNonNull(tier, "tier");    }}

LimitKey is package-private, because only RateLimiter uses it. Its equals and hashCode come from both fields, which is exactly what a map key needs. Rule and Outcome are records too.

The class diagram

The classes and how they connect
RateLimiter owns a map from LimitKey to Limiter, and uses a RuleBook and a Ticker. TokenBucket and SlidingWindowLog implement Limiter, and every Limiter creates Outcome records. RuleBook owns one Rule per Tier, and Rule.newLimiter creates a Limiter: a TokenBucket or a SlidingWindowLog, depending on its Algorithm. SystemTicker implements Ticker. LimitKey, Rule and Outcome are records; Tier and Algorithm are enums.RateLimiter owns a map from LimitKey to Limiter, and uses a RuleBook and a Ticker. TokenBucket and SlidingWindowLog implement Limiter, and every Limiter creates Outcome records. RuleBook owns one Rule per Tier, and Rule.newLimiter creates a Limiter: a TokenBucket or a SlidingWindowLog, depending on its Algorithm. SystemTicker implements Ticker. LimitKey, Rule and Outcome are records; Tier and Algorithm are enums.
RateLimiter owns the limiters. Each Limiter owns one client's count. RateLimiter owns a map from LimitKey to Limiter, and uses a RuleBook and a Ticker. TokenBucket and SlidingWindowLog implement Limiter, and every Limiter creates Outcome records. RuleBook owns one Rule per Tier, and Rule.newLimiter creates a Limiter: a TokenBucket or a SlidingWindowLog, depending on its Algorithm. SystemTicker implements Ticker. LimitKey, Rule and Outcome are records; Tier and Algorithm are enums.

The classes fall into three groups:

  • Data: LimitKey, Rule and Outcome are records, and Tier and Algorithm are enums. RuleBook is a small class that checks the configuration once.
  • The core: RateLimiter, which owns the map of limiters and decides which lock each request takes.
  • Rules and outside code: Limiter, with TokenBucket and SlidingWindowLog behind it, and Ticker, with SystemTicker for production and a hand-moved ticker for tests.

The rest of the article builds these one at a time.

Building it

The rules

A rule is three facts: how many permits, per how long, counted which way. It checks itself when it is made:

rule/Rule.javalines 10–29 of 38
/** At most {@code limit} permits per {@code period}, counted by {@code algorithm}. */public record Rule(int limit, Duration period, Algorithm algorithm) {    public static final int MAX_LIMIT = 100_000;    public static final Duration MIN_PERIOD = Duration.ofMillis(1);    public static final Duration MAX_PERIOD = Duration.ofHours(1);     public Rule {        Objects.requireNonNull(period, "period");        Objects.requireNonNull(algorithm, "algorithm");        if (limit < 1 || limit > MAX_LIMIT) {            throw new IllegalArgumentException("a limit must be between 1 and " + MAX_LIMIT + ", not " + limit);        }        if (period.compareTo(MIN_PERIOD) < 0 || period.compareTo(MAX_PERIOD) > 0) {            throw new IllegalArgumentException("a period must be between 1 ms and 1 hour, not " + period);        }    }     public long periodNanos() {        return period.toNanos();    }

A limit runs from 1 to 100,000, and a period from 1 ms to 1 hour. The upper bounds are not taste. The token bucket below multiplies the limit by the period in nanoseconds, and these bounds keep that product at most 3.6 × 1017, far below the largest long. RuleBook reads one rule per tier from the configuration:

rule/RuleBook.javalines 7–27 of 27
/** One rule per tier, read from configuration and checked once at startup. */public final class RuleBook {    private final Map<Tier, Rule> rules;     public RuleBook(Map<Tier, Rule> rules) {        Objects.requireNonNull(rules, "rules");        Map<Tier, Rule> copy = new EnumMap<>(Tier.class);        for (Tier tier : Tier.values()) {            Rule rule = rules.get(tier);            if (rule == null) {                throw new IllegalArgumentException("no rule for tier " + tier);            }            copy.put(tier, rule);        }        this.rules = copy;    }     public Rule ruleFor(Tier tier) {        return rules.get(Objects.requireNonNull(tier, "tier"));    }}

It copies the map into its own EnumMap and refuses a tier with no rule. A server with a broken configuration stops at startup, not on the first request from a partner. Changing the caller's map later changes nothing here.

Time

A limiter is all about time: how long since the last request, and when the next permit is free. The code takes its time from an interface:

limiter/Ticker.javalines 3–11 of 11
/** * A clock that only moves forwards, in nanoseconds from an arbitrary start. * Only the difference between two readings means anything. */@FunctionalInterfacepublic interface Ticker {     long nanos();}
Decision

Where does the time come from?

A java.time.Clock, the wall clock

It is the usual way to make time testable in Java. But the wall clock can be set back by a time sync, and a bucket that sees time go backwards would refill wrongly or not at all. A limiter only needs to know how much time has passed, not the date.

Call System.nanoTime() directly

It never goes backwards, which is right. But tests then have to wait for real seconds to pass, and no test can check what happens at exactly 60 s.

A Ticker interface: monotonic nanoseconds, moved by hand in testsOur pick

SystemTicker returns System.nanoTime() in production, and tests use a ticker they move themselves. Only differences between readings mean anything, so the code always compares now - then, never two raw readings. The cost is one small interface. As a guard, a bucket or a log that is given a reading earlier than its last one treats it as no time passing.

The answer

Every request gets an Outcome: allowed or not, how many permits are left, and the retry time for a refusal.

algorithm/Outcome.javalines 5–35 of 35
/** * The answer to one request: allowed or not, how many permits are left, and, * when it was refused, how long until the same request would be allowed if * nothing else used the limit first. */public record Outcome(boolean allowed, int remaining, long retryAfterNanos) {     public Outcome {        if (remaining < 0) {            throw new IllegalArgumentException("remaining cannot be negative: " + remaining);        }        if (allowed && retryAfterNanos != 0) {            throw new IllegalArgumentException("an allowed request has no retry time");        }        if (!allowed && retryAfterNanos <= 0) {            throw new IllegalArgumentException("a refused request needs a retry time above zero");        }    }     public static Outcome allow(int remaining) {        return new Outcome(true, remaining, 0);    }     public static Outcome reject(int remaining, long retryAfterNanos) {        return new Outcome(false, remaining, retryAfterNanos);    }     public Duration retryAfter() {        return Duration.ofNanos(retryAfterNanos);    }}

The record refuses nonsense: a refusal with no retry time, or an allowed request with one. The server turns a refusal into a 429 response with a Retry-After header, and the remaining count into another header.

Decision

Refuse at once, or make the caller wait?

An acquire method that blocks the thread until a permit is free

The caller's code is simpler: one call and the request goes ahead. But a waiting request holds a server thread, and a busy client can tie up every thread the server has. The waiting also has to happen outside every lock, or one client stalls the others.

Refuse at once, and say how long until a retry would workOur pick

tryAcquire returns straight away. The server answers 429, and the client decides whether to wait. A caller that wants to wait can sleep for the retry time and ask again, with no lock held. The cost is that every caller must handle a refusal.

Two ways of counting

The limiter must count in two ways, picked per tier. So the counting sits behind an interface:

algorithm/Limiter.javalines 3–14 of 14
/** * Counts and decides for one client. It is not thread-safe on its own: * RateLimiter only calls it while it holds that client's lock. */public interface Limiter {     /** Takes all the permits if all are free at {@code now}, or none of them. */    Outcome tryAcquire(int permits, long now);     /** True when the limiter is back to how a new one starts, so dropping it changes nothing. */    boolean isIdle(long now);}

A Limiter holds one client's count. tryAcquire takes all the permits or none and says what happened. isIdle says whether the limiter is back where a new one starts, which matters for forgetting clients later. A limiter is not thread-safe on its own: RateLimiter only calls it while it holds that client's lock.

The two ways let different traffic through for the same "5 per minute":

Same limit, three ways of counting
Each row applies 5 per minute to one client. The first two rows get the same requests. The sliding window log allows 5 at 0 s, refuses at 30 s and 59 s, and allows 5 more at exactly 60 s, when the first five leave the window. The token bucket allows 5 at 0 s, 1 at 30 s and 3 at 59 s, which is 9 in 59 seconds, then 1 at 60 s. The third row gets a different burst, 5 requests at 59 s and 5 more at 60 s. A fixed window counter, which we do not build, counts per clock minute, so it allows all 10 in one second.Each row applies 5 per minute to one client. The first two rows get the same requests. The sliding window log allows 5 at 0 s, refuses at 30 s and 59 s, and allows 5 more at exactly 60 s, when the first five leave the window. The token bucket allows 5 at 0 s, 1 at 30 s and 3 at 59 s, which is 9 in 59 seconds, then 1 at 60 s. The third row gets a different burst, 5 requests at 59 s and 5 more at 60 s. A fixed window counter, which we do not build, counts per clock minute, so it allows all 10 in one second.
The log never passes 5 in a minute. The bucket and the fixed window can. Each row applies 5 per minute to one client. The first two rows get the same requests. The sliding window log allows 5 at 0 s, refuses at 30 s and 59 s, and allows 5 more at exactly 60 s, when the first five leave the window. The token bucket allows 5 at 0 s, 1 at 30 s and 3 at 59 s, which is 9 in 59 seconds, then 1 at 60 s. The third row gets a different burst, 5 requests at 59 s and 5 more at 60 s. A fixed window counter, which we do not build, counts per clock minute, so it allows all 10 in one second.
Decision

Which way of counting?

A fixed window counter: one count per clock minute

It is two numbers per client and the simplest code. But the count resets on the minute, so a client can send the whole limit at the end of one minute and again at the start of the next: twice the limit in a second.

A sliding window counter: this minute's count plus a share of the last one

It is two numbers per client and smooths out the reset. But it guesses how the last minute's requests were spread, so it can let a few too many through or refuse a few too early.

Both a token bucket and a sliding window log, chosen per tierOur pick

The log is exact: never more than the limit in any period. The bucket allows bursts and costs two numbers per client. Each tier picks the behaviour it is sold with. The cost is two classes to write and test, and a log that keeps one number per permit, so its memory grows with the limit.

A rule makes the limiter for a new client:

rule/Rule.javalines 31–37 of 38
    /** A limiter for one client, as a new client starts: nothing used yet. */    public Limiter newLimiter(long now) {        return switch (algorithm) {            case TOKEN_BUCKET -> new TokenBucket(limit, periodNanos(), now);            case SLIDING_WINDOW_LOG -> new SlidingWindowLog(limit, periodNanos());        };    }

The token bucket

A bucket holds up to 5 tokens and refills 5 per minute, one token every 12 seconds. A request takes a token per permit. The hard part is the twelve seconds: after 7 seconds, the bucket has gained 7/12 of a token, and a long cannot hold 7/12.

algorithm/TokenBucket.javalines 10–30 of 68
public final class TokenBucket implements Limiter {    private final long limit;    private final long periodNanos;    private final long capacityUnits;    private long units;    private long refilledAt;     public TokenBucket(int limit, long periodNanos, long now) {        if (limit < 1 || periodNanos < 1) {            throw new IllegalArgumentException("limit and period must be above zero");        }        // A full bucket plus one period of refill must still fit in a long.        if (periodNanos > Long.MAX_VALUE / 2 / limit) {            throw new IllegalArgumentException("limit times period is too large");        }        this.limit = limit;        this.periodNanos = periodNanos;        this.capacityUnits = limit * periodNanos;        this.units = capacityUnits;        this.refilledAt = now;    }

The bucket counts in units: one token is the period in nanoseconds, 60,000,000,000 units for a minute. In those units, one nanosecond refills exactly limit units, 5 for this rule, with nothing left over.

Decision

How does the bucket count part of a token?

Tokens as a double

It is the obvious code: add elapsed × rate each time. But a double rounds, and the rounding adds up over millions of small refills, so the bucket drifts from the rule it was given.

Whole tokens only, added when a full twelve seconds has passed

It is all whole numbers. But the time since the last whole token has to be kept separately, or a client that asks every 7 seconds never gets a refill at all.

Count units of one token times the period, as a longOur pick

Every refill is an exact whole number, so the bucket never drifts, however often a client asks. The retry time is exact too. The cost is that the limit times the period must fit in a long, which is why Rule caps both.

algorithm/TokenBucket.javalines 32–63 of 68
    @Override    public Outcome tryAcquire(int permits, long now) {        if (permits < 1 || permits > limit) {            throw new IllegalArgumentException("permits must be between 1 and " + limit + ", not " + permits);        }        refill(now);        long needed = permits * periodNanos;        if (units >= needed) {            units -= needed;            return Outcome.allow(remaining());        }        long missing = needed - units;        long waitNanos = (missing + limit - 1) / limit;        return Outcome.reject(remaining(), waitNanos);    }     @Override    public boolean isIdle(long now) {        refill(now);        return units == capacityUnits;    }     private void refill(long now) {        long elapsed = now - refilledAt;        if (elapsed <= 0) {            return;        }        // A whole period refills the whole bucket, so a longer gap adds nothing more.        long added = Math.min(elapsed, periodNanos) * limit;        units = Math.min(capacityUnits, units + added);        refilledAt = now;    }

tryAcquire refills first, then takes all the units the request needs, or none. A refusal works out how many units are missing and how many nanoseconds refill them, rounded up: 12 s for one token when the bucket is empty. refill caps the time since the last refill at one period, because a whole period fills the whole bucket. That cap also keeps the multiplication small after a client is idle for days.

The sliding window log

The log remembers the time of every permit granted in the last period, oldest first:

algorithm/SlidingWindowLog.javalines 28–68 of 86
    @Override    public Outcome tryAcquire(int permits, long now) {        if (permits < 1 || permits > limit) {            throw new IllegalArgumentException("permits must be between 1 and " + limit + ", not " + permits);        }        long at = notBeforeLatest(now);        forgetOld(at);        if (count + permits <= limit) {            for (int i = 0; i < permits; i++) {                append(at);            }            return Outcome.allow(limit - count);        }        // The request fits once this many of the oldest permits have left the window.        int mustLeave = count + permits - limit;        long leavesAt = times[(oldest + mustLeave - 1) % times.length] + periodNanos;        return Outcome.reject(limit - count, leavesAt - at);    }     @Override    public boolean isIdle(long now) {        forgetOld(notBeforeLatest(now));        return count == 0;    }     /** A reading earlier than the latest one counts as the latest, so time never runs backwards here. */    private long notBeforeLatest(long now) {        if (anyReading && now - latest < 0) {            return latest;        }        anyReading = true;        latest = now;        return now;    }     private void forgetOld(long now) {        while (count > 0 && now - times[oldest] >= periodNanos) {            oldest = (oldest + 1) % times.length;            count--;        }    }

notBeforeLatest treats a reading earlier than the latest one as the latest, so time never runs backwards inside the log. forgetOld drops every time that is at least one period old. A permit granted at 0 s still counts at 59.999 s and is gone at exactly 60 s. The request fits if the permits still in the window plus the new ones stay within the limit. If not, mustLeave is how many of the oldest permits must leave first, and the retry time is when the last of those leaves.

The times sit in a ring buffer: an array, the index of the oldest time, and a count. It starts with 8 slots and doubles up to the limit as a client gets busier, so a client that sends one request costs about 120 bytes for the log and its 8 slots, and about 176 with its map entry and key. A client that uses a limit of 100,000 keeps 100,000 times, 800 KB. That is the price of being exact, and it is why the bucket suits large limits.

Asking for permits

RateLimiter puts it together. It checks the request, finds the rule, and does the work inside ConcurrentHashMap.compute:

limiter/RateLimiter.javalines 28–46 of 71
    /** Takes {@code permits} from the client's limit if all of them are free, and says what happened. */    public Outcome tryAcquire(String clientId, Tier tier, int permits) {        Objects.requireNonNull(clientId, "clientId");        if (clientId.isBlank()) {            throw new IllegalArgumentException("a client id cannot be blank");        }        Rule rule = rules.ruleFor(tier);        if (permits < 1 || permits > rule.limit()) {            throw new IllegalArgumentException("permits must be between 1 and " + rule.limit() + ", not " + permits);        }        Outcome[] outcome = new Outcome[1];        limiters.compute(new LimitKey(clientId, tier), (key, limiter) -> {            long now = ticker.nanos();            Limiter current = limiter != null ? limiter : rule.newLimiter(now);            outcome[0] = current.tryAcquire(permits, now);            return current;        });        return outcome[0];    }

compute runs the function with that client's entry locked. It reads the ticker, makes the limiter with that reading on the client's first request, asks the limiter, and keeps it in the map. The ticker is read after the entry is locked, so a retry time is measured from when the request actually runs, and no request decides with a reading older than one already applied for that client.

Decision

What if a request costs more than the whole limit?

Refuse it with a retry time, like any other refusal

It looks consistent. But no retry time is ever right: a batch of 6 on a limit of 5 can never fit, and the client would retry for ever.

Throw an IllegalArgumentException before anything is touchedOur pick

The server decides what a request costs, so a cost of 0 or above the limit is a bug in the server, and an exception says so. The check runs before the map is touched, so a bad request leaves no limiter behind. The cost is that the server must know the limit before it splits a big batch.

There are two kinds of error, and each says what it is for. An exception, IllegalArgumentException or NullPointerException, is for a programmer: a bad rule, a missing tier, a blank client id, a cost of 0 or above the limit. A refusal is an Outcome, an answer for a client who sent too much.

Forgetting idle clients

Each client that ever called keeps a limiter in the map. Over a day that is millions of entries, most of them for clients long gone.

limiter/RateLimiter.javalines 48–65 of 71
    /** Forgets every client whose limiter is back to how a new one starts. Returns how many it forgot. */    public int evictIdle() {        int forgotten = 0;        for (LimitKey key : limiters.keySet()) {            boolean[] dropped = new boolean[1];            limiters.computeIfPresent(key, (k, limiter) -> {                if (limiter.isIdle(ticker.nanos())) {                    dropped[0] = true;                    return null;                }                return limiter;            });            if (dropped[0]) {                forgotten++;            }        }        return forgotten;    }

evictIdle walks the keys and asks each limiter, under that client's lock, whether it is idle. A bucket is idle when it is full again; a log is idle when it is empty. An idle limiter is removed. A job calls evictIdle every few minutes.

Decision

When is a client forgotten?

Never

Nothing is lost. But the map grows with every client the server has ever seen, until it runs out of memory.

When it has been quiet for a fixed time, such as ten minutes

It is easy to explain. But a client whose bucket is half empty after ten quiet minutes, on a rule of 5 per hour, would get a full new bucket: forgetting it hands out free permits.

Only when its limiter is back where a new one startsOur pick

A full bucket or an empty log behaves exactly like a new one, so forgetting it changes no answer: the next request makes a fresh limiter that says the same thing. Because the check and the removal run under the same lock as requests, a request can never slip in between. The cost is a walk over every key, so a server with millions of keys spreads it over a job, not a request.

Many threads, one client

A popular client sends requests on many threads at once, and each thread asks the limiter for the same key.

Two first requests for one client
On the left, the limiter uses get and then put. Thread A looks up ravi and finds nothing. Before A stores a bucket, thread B looks up ravi and finds nothing too. Each makes its own bucket and takes its token, so a limit of 1 allows 2. On the right, compute holds the lock for ravi while A makes the bucket and takes the token. B waits, finds A's bucket empty, and is refused.On the left, the limiter uses get and then put. Thread A looks up ravi and finds nothing. Before A stores a bucket, thread B looks up ravi and finds nothing too. Each makes its own bucket and takes its token, so a limit of 1 allows 2. On the right, compute holds the lock for ravi while A makes the bucket and takes the token. B waits, finds A's bucket empty, and is refused.
Without one lock for the client, looking up, creating and taking are separate steps. On the left, the limiter uses get and then put. Thread A looks up ravi and finds nothing. Before A stores a bucket, thread B looks up ravi and finds nothing too. Each makes its own bucket and takes its token, so a limit of 1 allows 2. On the right, compute holds the lock for ravi while A makes the bucket and takes the token. B waits, finds A's bucket empty, and is refused.

The project includes a check, demo/RaceCheck.java. Sixteen threads ask at the same moment for one permit at a time, eight times each, for one client on a rule of 50 per 10 seconds. Time stands still while they ask, so the right count is known exactly. Each round asks again 5 seconds later and 10 seconds after the start, with a new client every round, while another thread keeps calling evictIdle.

$ java demo.RaceCheck
16 threads ask at once, 400 rounds per rule, a new client each round, 50 per 10s
token bucket: rounds allowing exactly 50, then 25 after 5 s, then 25 after 10 s: 400
token bucket: rounds with any other count: 0, rounds where a thread crashed: 0
sliding window log: rounds allowing exactly 50, then 0 after 5 s, then 50 after 10 s: 400
sliding window log: rounds with any other count: 0, rounds where a thread crashed: 0
clients still tracked once all were idle and evictIdle ran: 0

Every round gave exactly the counts the rules allow. The bucket allowed 50, then the 25 it refilled in 5 seconds, then 25 more. The log allowed 50, then nothing while the first 50 were in the window, then 50 once they had left. We also ran the same check with compute replaced by a get, a put, and a call to the limiter with no lock. In every run we tried, many rounds of both kinds let more requests through than the rule allows, some of them more than twice as many, and some sliding log rounds crashed. The exact numbers change from run to run, and none of it shows when one thread tests the limiter alone.

Decision

Where does the lock go?

One lock around the whole limiter

It is the simplest to get right. But every request for every client waits for every other, so the busiest client slows all the rest.

A lock inside each limiter, found with computeIfAbsent

Clients never wait for each other. But evictIdle can remove a limiter just after a thread has found it and before it takes the lock. That thread takes a permit from a limiter no longer in the map, and the next request gets a fresh one, so the client gets more permits than the rule allows. Fixing it needs a "retired" flag and a retry loop.

An atomic state changed with compare-and-set in a loop

No thread ever blocks. It fits a token bucket, whose state is two numbers. But the log's state is an array, and under heavy contention threads spin, retrying the same update.

ConcurrentHashMap.compute: the map's own lock for that keyOur pick

Making a limiter, asking it and removing it all run under the same per-key lock, so nothing can slip in between. Clients with different keys almost never wait for each other. The cost is that compute locks a small part of the map's table, so a few other keys that share it wait briefly too. The function changes the limiter, so this relies on ConcurrentHashMap running it exactly once under the lock; the field is typed ConcurrentHashMap, not ConcurrentMap, for that reason. The function must also stay short and never call back into the map. Ours reads the ticker once and changes one client's count, though a first request allocates the limiter and a large batch on a log copies its array, both under the lock.

The final design

RateLimiter is the core. It owns the map of limiters and the lock for each client, made on first use and forgotten when idle. It reaches the counting only through Limiter, the rules only through RuleBook, and time only through Ticker, so a new way of counting or a test clock changes nothing in RateLimiter.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. LimitKey carries 1, Ticker 2, Outcome 3, Limiter 4 and TokenBucket 5. RateLimiter carries 6, 7 and 8. Limiter carries a Strategy tag, and Rule a Factory tag.The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. LimitKey carries 1, Ticker 2, Outcome 3, Limiter 4 and TokenBucket 5. RateLimiter carries 6, 7 and 8. Limiter carries a Strategy tag, and Rule a Factory tag.
Each decision lands on one class. Two classes carry a pattern. The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. LimitKey carries 1, Ticker 2, Outcome 3, Limiter 4 and TokenBucket 5. RateLimiter carries 6, 7 and 8. Limiter carries a Strategy tag, and Rule a Factory tag.
S.No.The questionWhat we choseWhy
1Should a client be a class?A key: the client's id and its tier, in a map to its limiterAccounts live elsewhere, and the map is the only link a limiter needs
2Where does the time come from?A Ticker interface: monotonic nanoseconds, moved by hand in testsIt never goes back, and tests check exact nanoseconds
3Refuse at once, or make the caller wait?Refuse at once, and say how long until a retry would workNo server thread is held by a waiting client
4Which way of counting?Both a token bucket and a sliding window log, chosen per tierEach tier gets exact limits or bursts, as it is sold
5How does the bucket count part of a token?Count units of one token times the period, as a longEvery refill is a whole number, so the bucket never drifts
6What if a request costs more than the whole limit?Throw an IllegalArgumentException before anything is touchedIt can never fit, so it is a bug in the caller
7When is a client forgotten?Only when its limiter is back where a new one startsForgetting it changes no answer
8Where does the lock go?ConcurrentHashMap.compute: the map's own lock for that keyMaking, asking and forgetting a limiter share one lock per client

Here is the demo's request from asha-app at 30 seconds on the FREE tier, end to end:

  1. A server thread calls tryAcquire("asha-app", FREE, 1). It checks the client id and the cost with no lock held, and RuleBook.ruleFor gives the FREE rule: 5 per minute, counted with a sliding log.
  2. limiters.compute locks the entry for asha-app on FREE. Inside it, ticker.nanos() reads the time; the ticker is the one outside call made under the lock.
  3. The entry already holds a SlidingWindowLog, so no new one is made. Its tryAcquire calls forgetOld, which keeps all five permits from 0 s, because none of them is a minute old.
  4. Five plus one is over the limit, so mustLeave is 1. The oldest permit leaves at 60 s, and the log returns Outcome.reject with 0 left and a retry time of 30 s.
  5. compute keeps the log in the map and unlocks the entry. tryAcquire returns the Outcome, and the server answers 429 with Retry-After: 30.

A request on the PARTNER tier takes the same path. Only the Limiter behind the interface differs: a TokenBucket, which refills for the 30 seconds that have passed before it decides, and allows the request.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

limiterRateLimiter.java
package limiter; import java.util.Objects;import java.util.concurrent.ConcurrentHashMap; import algorithm.Limiter;import algorithm.Outcome;import rule.Rule;import rule.RuleBook;import rule.Tier; /** * Decides, for each request, whether a client is within its tier's limit. * One limiter per client and tier, made on the client's first request and * forgotten once it is idle. All the work for one client runs inside * ConcurrentHashMap.compute, which locks that key's entry while it runs. */public final class RateLimiter {    private final RuleBook rules;    private final Ticker ticker;    private final ConcurrentHashMap<LimitKey, Limiter> limiters = new ConcurrentHashMap<>();     public RateLimiter(RuleBook rules, Ticker ticker) {        this.rules = Objects.requireNonNull(rules, "rules");        this.ticker = Objects.requireNonNull(ticker, "ticker");    }     /** Takes {@code permits} from the client's limit if all of them are free, and says what happened. */    public Outcome tryAcquire(String clientId, Tier tier, int permits) {        Objects.requireNonNull(clientId, "clientId");        if (clientId.isBlank()) {            throw new IllegalArgumentException("a client id cannot be blank");        }        Rule rule = rules.ruleFor(tier);        if (permits < 1 || permits > rule.limit()) {            throw new IllegalArgumentException("permits must be between 1 and " + rule.limit() + ", not " + permits);        }        Outcome[] outcome = new Outcome[1];        limiters.compute(new LimitKey(clientId, tier), (key, limiter) -> {            long now = ticker.nanos();            Limiter current = limiter != null ? limiter : rule.newLimiter(now);            outcome[0] = current.tryAcquire(permits, now);            return current;        });        return outcome[0];    }     /** Forgets every client whose limiter is back to how a new one starts. Returns how many it forgot. */    public int evictIdle() {        int forgotten = 0;        for (LimitKey key : limiters.keySet()) {            boolean[] dropped = new boolean[1];            limiters.computeIfPresent(key, (k, limiter) -> {                if (limiter.isIdle(ticker.nanos())) {                    dropped[0] = true;                    return null;                }                return limiter;            });            if (dropped[0]) {                forgotten++;            }        }        return forgotten;    }     /** How many client and tier pairs have a limiter right now. */    public int trackedClients() {        return limiters.size();    }}
Click a class name in the code to open its fileJava · 71 lines · 685 in the project

demo/Main.java runs a public API with two tiers that have the same numbers, 5 per minute, counted two ways. It sends the same requests under both, then shows a batch call, the inputs the limiter refuses, and idle clients being forgotten:

$ java demo.Main
== The same requests from asha-app under both rules, 5 per minute ==
   FREE counts with a sliding window log, PARTNER with a token bucket
    0s  5 requests  FREE: allowed 5, 0 left
                    PARTNER: allowed 5, 0 left
    0s  1 more      FREE: refused, retry after 60s
                    PARTNER: refused, retry after 12s
   30s  1 request   FREE: refused, retry after 30s
                    PARTNER: allowed 1, 1 left
   59s  5 requests  FREE: refused, retry after 1s
                    PARTNER: allowed 3, then refused, retry after 1s
   59s  allowed from 0s to 59s: FREE 5, PARTNER 9
   60s  5 requests  FREE: allowed 5, 0 left
                    PARTNER: allowed 1, then refused, retry after 12s

== A batch call costs 3 permits, and gets all 3 or none ==
   61s  3 single requests: allowed 3, 2 left
   61s  a batch of 3: refused, retry after 60s, still 2 left
   61s  2 single requests: allowed 2, 0 left

== Inputs the limiter refuses ==
   asking for 0 permits: permits must be between 1 and 5, not 0
   asking for 6 permits: permits must be between 1 and 5, not 6
   a blank client id: a client id cannot be blank
   a rule of 5 per 2 hours: a period must be between 1 ms and 1 hour, not PT2H
   a rule book with no PARTNER rule: no rule for tier PARTNER

== Forgetting idle clients ==
   70s  1,000 new clients send one request each; tracking 1,003
  130s  evictIdle forgot 1,003; still tracking 1
  190s  a minute later, evictIdle forgot 1; still tracking 0

Notice four things in the output. From 0 s to 59 s the log allowed 5 requests and the bucket allowed 9, so the bucket let almost twice the limit through in one minute, as the figure showed. At exactly 60 s the log allowed all 5 again, because its first five permits left the window together. The batch of 3 was refused with 2 permits left and took neither of them, so the 2 single requests after it went through. At 130 s every client that had gone quiet was forgotten, 1,003 of them, while meera-app, which had asked 5 seconds earlier, was kept until the next sweep.

Follow-up questions

After the core design, the interviewer adds requirements to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Limit each endpoint as well as each client."LimitKey gains the endpoint, RuleBook is keyed by endpoint and tier, and tryAcquire takes the endpoint.The limiters, the lock, evictIdle.
"Change the rules without a restart."RateLimiter holds the RuleBook in an AtomicReference, and the map's value becomes a small record of the rule and its limiter. Inside compute, a limiter made from an older rule is replaced by a new one from the current rule, so a busy client picks up the change at once; the new limiter starts fresh, which gives each busy client one fresh period. evictIdle reads the limiter out of the record.TokenBucket, SlidingWindowLog.
"Share one limit across many servers."The count moves to a shared store, and the map of limiters goes away. That is a different design, with its own problems: a network call per request and a store that can fail.Rule, RuleBook, Outcome.
"Use less memory for big limits."A new SlidingWindowCounter behind Limiter, with two counts per client, a third Algorithm value, and its case in Rule.newLimiter.RateLimiter, the other limiters.
"Let a request wait instead of failing."A new acquire(client, tier, permits, maxWait) on RateLimiter that sleeps for the retry time with no lock held and asks again.The limiters, which already say how long to wait.
"Let partners burst more than their steady rate."Rule gains a burst size. TokenBucket uses it as its capacity, caps a refill at capacity ÷ limit periods instead of one, and its overflow bound becomes the burst times the period. RateLimiter checks a cost against the burst, not the limit.SlidingWindowLog.
"Send the remaining permits in a header."Nothing in the limiter: every Outcome already carries them.Everything.
"Limit clients that have no API key."Nothing in the limiter: the server passes another id, such as the IP address.Everything.

In most rows the change lands in one class or behind one interface. The shared limit is the one to say out loud as a different question, because it replaces the map with a store and brings failures the in-memory design never has.

What the interviewer looks for

Mid-level

A mid-level candidate shows a working limiter for one client: a map from client to a counter or a bucket, a refusal over the limit, and a reset or a refill. They explain one way of counting clearly and test it at the boundary.

Senior

A senior candidate shows everything above and gives the reasons. They compare a token bucket with a sliding window and say what each lets through, put the counting behind an interface, and take time from an injected ticker. They make the refill exact, return a retry time, and guard each client with its own lock.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They explain why only an idle limiter can be forgotten, why the lookup, the creation and the removal must share one lock, and why the ticker is read under it. They say where the in-memory design stops and what a shared store would change.

Common mistakes

  • A fixed window called a sliding one. A count that resets on the minute lets twice the limit through where two minutes meet.
  • Tokens as a double. Rounding adds up over many small refills, and the bucket drifts from its rule.
  • Reading the wall clock. A time sync can move it backwards, and tests have to wait for real time to pass.
  • Get, then put. Two first requests each make a limiter, and a limit of 1 allows 2.
  • Forgetting clients by age. A half-empty bucket replaced by a full one hands out free permits.
  • Blocking the thread until a permit is free. One busy client can hold every thread the server has.
  • A refusal with no retry time. The client can only guess, and guessing clients retry too often.

Summary

  • Ask what "5 per minute" means. "Never more than 5 in any minute" and "5 at once, then one every 12 seconds" are different algorithms.
  • Put the counting behind one interface, with a sliding window log for exact limits and a token bucket for bursts, chosen per tier.
  • Count the bucket in units of one token times the period, so every refill is a whole number and nothing drifts.
  • Take time from an injected monotonic ticker, and compare only differences between readings.
  • Refuse at once with a retry time, and throw for a cost that can never fit.
  • Forget a client only when its limiter is back where a new one starts, so forgetting changes no answer.
  • Do every step for one client inside ConcurrentHashMap.compute, so making, asking and forgetting a limiter share one lock.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.