Algo-Sim › Low-Level Design

Rate Limiter: Sliding Window Log

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

At most limit requests in any window of window seconds: keep a queue of accepted times and drop the ones that slid out.

Problem

Design a rate limiter that accepts at most limit requests in any window of window seconds. A request at time t is accepted if fewer than limit accepted requests happened after time t − window; otherwise it is rejected. Return the decision for each request.

Constraints

Edge cases to test

Follow-up questions

How do you save memory?
A sliding window counter: weight the previous fixed window’s count by its overlap and add the current one. O(1) memory, approximate.
What is the cost of the log?
O(limit) memory per client and O(1) amortized per request.

Solution

Java

class SlidingWindowLog {
    private final Deque<Integer> log = new ArrayDeque<>();   // accepted request times
    private final int limit, window;

    public SlidingWindowLog(int limit, int window) {
        this.limit = limit;
        this.window = window;
    }

    public boolean allow(int t) {
        while (!log.isEmpty() && log.peekFirst() <= t - window)
            log.pollFirst();
        if (log.size() < limit) {
            log.addLast(t);
            return true;
        }
        return false;
    }
}

Python

from collections import deque


class SlidingWindowLog:
    def __init__(self, limit, window):
        self.log = deque()                  # accepted request times
        self.limit = limit
        self.window = window

    def allow(self, t):
        while self.log and self.log[0] <= t - self.window:
            self.log.popleft()
        if len(self.log) < self.limit:
            self.log.append(t)
            return True
        return False

C++

#include <bits/stdc++.h>
using namespace std;

class SlidingWindowLog {
  public:
    deque<int> log = {}; // accepted request times
    int limit, window;

    SlidingWindowLog(int limit, int window) {
        this->limit = limit;
        this->window = window;
    }

    bool allow(int t) {
        while (!log.empty() && log.front() <= t - window)
            log.pop_front();
        if (int(log.size()) < limit) {
            log.push_back(t);
            return true;
        }
        return false;
    }
};

More Low-Level Design problems