Start learning free

LESSON 15 OF 33 · OBJECT-ORIENTED DESIGN - INTERVIEWS

Rate Limiter in Java: Sliding Window with a Deque per User

Practice O(1) Read the full explanation

This is a design round. You write the classes, and the interviewer checks that they behave.

Here you build a rate limiter. It stops a user from making too many calls in a short time.

Implement the class:

  • new RateLimiter(limit, window) makes a limiter. Each user may make limit calls in any window seconds.
  • allow(user, time) is a call by user at second time. It returns true if the call is allowed, and false if not.

A call looks back over a window of seconds. The window starts after second time - window and ends with second time. With a window of 10, a call at second 11 looks at seconds 2 to 11.

The call is allowed when the user made fewer than limit allowed calls in that window. An allowed call counts for the later calls. A refused call does not count.

Each user has their own count. The times never go down from one call to the next.

The calls run in order on one new limiter. The output has one line for each call, with what it returns. Booleans are written as True and False.

 

Example 1:

Input:
new RateLimiter(2, 10)
1. allow("ana", 1)
2. allow("ana", 5)
3. allow("ana", 8)
4. allow("bob", 8)
5. allow("ana", 11)
6. allow("ana", 12)
Output:
True
True
False
True
True
False
Explanation:
Calls 1 and 2 use up ana's two calls.
So call 3 is refused.
Bob has his own count, so call 4 is allowed.
At second 11, the window is seconds 2 to 11.
The call at second 1 has left it, so call 5 is allowed.
Call 6 is refused. The calls at 5 and 11 are still in its window.

Example 2:

Input:
new RateLimiter(1, 3)
1. allow("max", 0)
2. allow("max", 2)
3. allow("max", 3)
4. allow("max", 3)
Output:
True
False
True
False
Explanation:
The window is 3 seconds long.
Call 2 is refused, and a refused call does not count.
At second 3, the window is seconds 1 to 3.
The call at second 0 is out, so call 3 is allowed.

Example 3:

Input:
new RateLimiter(3, 100)
1. allow("kim", 50)
2. allow("kim", 50)
3. allow("kim", 50)
4. allow("kim", 50)
5. allow("lee", 50)
6. allow("kim", 149)
7. allow("kim", 150)
Output:
True
True
True
False
True
False
True
Explanation:
Calls at the same second all count.
Kim uses up her three calls at second 50, so call 4 is refused.
Lee has her own count, so call 5 is allowed.
At second 149, the calls at 50 are still in the window.
At second 150, the window is seconds 51 to 150, so call 7 is allowed.

 

Constraints:

  • limit is a whole number from 1 to 100,000.
  • window is a whole number from 1 to 1,000,000,000.
  • time is a whole number from 0 to 1,000,000,000.
  • A user name has 1 to 10 lowercase letters.
  • At most 100,000 calls are made on one limiter.

Note:

Each call should take O(1) time on average (amortized). Counting all of a user's past calls on every call would take O(n) time.

STEP 1 OF 11
    Ctrl + Enter to check

    JAVA · OBJECT-ORIENTED DESIGN - INTERVIEWS

    Rate Limiter in Java, explained

    Problem overview

    A rate limiter stops a user from making too many calls in a short time. You write the class RateLimiter. The constructor new RateLimiter(limit, window) sets the rule: each user may make limit calls in any window seconds. The method allow(user, time) reports a call by user at second time and returns true if it is allowed, false if it is refused.

    The call looks back over a window that starts just after second time - window and ends with second time. With a window of 10, a call at second 11 looks at seconds 2 to 11. The call is allowed when the user made fewer than limit allowed calls in that window. An allowed call counts for later calls, and a refused call does not. Each user has their own count, and the times never go down from one call to the next.

    Take new RateLimiter(2, 10). Ana calls at seconds 1 and 5, and both are allowed. At second 8 she is at her limit of 2, so that call is refused. Bob's call at second 8 is allowed, because he has his own count. At second 11 the window is seconds 2 to 11, so Ana's call at second 1 has left it, and the call is allowed. At second 12 the calls at 5 and 11 are both in the window, so it is refused. The results are true true false true true false; the tests print them as True and False.

    Approach: a queue of allowed call times for each user

    The simple solution stores every call a user made and, on each new call, counts how many fall inside the window. That is O(n) per call for n past calls, and with 100,000 calls on one limiter it is too slow. The statement asks for O(1) amortized time.

    The key observation is that times never go down. For one user, the allowed calls are stored in the order they happened, so the oldest is always the first. When a new call arrives at time, the calls that have left the window are exactly the ones at the front with a time of time - window or earlier. Those can never matter again, because later calls have even later windows. So the limiter drops them from the front, and what remains is exactly the user's allowed calls in the window. The size of the queue is then the count.

    The queue is a Deque<Integer> implemented by ArrayDeque: it gives peek() for the oldest time, poll() to drop it and add to append the newest. A HashMap from user name to queue gives every user a separate count.

    Why is this O(1) amortized? A single call may drop many old times, but each time is added once and dropped at most once. Over all calls, the total dropping work is at most the total number of adds, so the average work per call is constant.

    Step by step

    1. Declare the private fields limit and window, and the map calls from user to a queue of times.
    2. The constructor stores both parameters with this.limit and this.window.
    3. In allow, create an empty queue for a user seen for the first time.
    4. Take the user's queue into the variable times.
    5. While the queue is not empty and its oldest time is at most time - window, drop the oldest time. The window starts after time - window, so a call made exactly at that second is already out.
    6. If the queue now holds fewer than limit times, the call is allowed: add time to the queue and return true.
    7. Otherwise return false, without adding anything.

    The solution in Java

    class RateLimiter {
        private int limit;
        private int window;
        private Map<String, Deque<Integer>> calls = new HashMap<>();
    
        public RateLimiter(int limit, int window) {
            this.limit = limit;
            this.window = window;
        }
    
        public boolean allow(String user, int time) {
            if (!calls.containsKey(user)) {
                calls.put(user, new ArrayDeque<>());
            }
            Deque<Integer> times = calls.get(user);
            while (!times.isEmpty() && times.peek() <= time - window) {
                times.poll();
            }
            if (times.size() < limit) {
                times.add(time);
                return true;
            }
            return false;
        }
    }
    

    The Java details worth a closer look:

    • times is the same object as the map's queue. calls.get(user) returns a reference, so poll() and add on times change what the map keeps. No put is needed afterwards.
    • times.peek() <= time - window compares an Integer from the queue with an int; Java unboxes it for the comparison. The !times.isEmpty() test comes first, and && skips the second test when the first is false, because peek() on an empty queue returns null, and unboxing that would throw a NullPointerException.
    • No overflow here. time and window are at most 1,000,000,000, so time - window stays between -1,000,000,000 and 1,000,000,000, inside the range of an int (about 2.1 billion). Adding them instead could pass that range.
    • containsKey and then put. A user's first call has no queue, so one is created. Later calls skip the put.

    Complexity

    Each call does one map lookup, drops some old times from the front, and adds at most one time. Every time is dropped at most once, so the cost per call is O(1) amortized. The space is the total number of times still queued: at most limit per user, plus the times that have not been dropped yet because their user has not called again.

    Edge cases and common mistakes

    • Window boundary. At second 3 with a window of 3, the window is seconds 1 to 3. A call at second 0 is out. Using < instead of <= when dropping would keep it and refuse a call that should be allowed. With new RateLimiter(1, 3), the calls at seconds 0, 2, 3 and 3 give true false true false.
    • Adding refused calls. If a refused call were stored, a user who keeps trying could never get back in. Only allowed calls go in the queue.
    • Calls in the same second. They all count. With new RateLimiter(3, 100), four calls by Kim at second 50 give true true true false.
    • One shared queue. A single queue for all users would make Bob's calls count against Ana. Each user gets a queue of their own, and Lee's call at second 50 is allowed after Kim's refusal.
    • Dropping before counting. The order matters: drop the old times first, then compare the size with the limit. Counting first would include calls that have already left the window.
    • Time in the window versus the limit. Kim's call at second 149 is refused, because the three calls at second 50 are still inside seconds 50 to 149. At second 150 the window is seconds 51 to 150, so the call is allowed.

    Testing

    RateLimiter r = new RateLimiter(3, 100);
    System.out.println(r.allow("kim", 50));
    System.out.println(r.allow("kim", 50));
    System.out.println(r.allow("kim", 50));
    System.out.println(r.allow("kim", 50));
    System.out.println(r.allow("lee", 50));
    System.out.println(r.allow("kim", 149));
    System.out.println(r.allow("kim", 150));
    

    This prints true, true, true, false, true, false, true. The fourth call is over Kim's limit, Lee has her own count, the call at 149 still sees the three calls at 50, and the call at 150 does not.

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free