Library

Volume 3 · Coding Problems & Data Structures

Notebook
Sign in

Section 22

Rate Limiter (Sliding Window, Token Bucket, Multi-Window)

774 words · about 4 min

Rate limiting is one of the most commonly asked “build a small system” coding questions at the architect level, because it combines data structures, concurrency, and distributed-systems trade-off reasoning in one place.

Algorithm comparison

Algorithm Burst Handling Memory Precision Typical Use
Fixed Window Counter Allows 2x burst at window edges O(1) per key Low Simple API quotas
Sliding Window Log No burst issue O(requests in window) Exact Strict rate enforcement
Sliding Window Counter Small approximation error O(1) per key High Best default for most APIs
Token Bucket Allows configurable bursts O(1) per key High Traffic shaping, allows short bursts
Leaky Bucket Smooths bursts to constant rate O(queue size) High Strict output rate (e.g., outbound API calls)

Python: Sliding Window Log

from collections import deque
import time

class SlidingWindowRateLimiter:
    def __init__(self, max_requests: int, window_seconds: int):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.requests: dict[str, deque] = {}

    def allow_request(self, user_id: str) -> bool:
        now = time.time()
        window = self.requests.setdefault(user_id, deque())

        while window and window[0] <= now - self.window_seconds:
            window.popleft()

        if len(window) < self.max_requests:
            window.append(now)
            return True
        return False

Python: Token Bucket

import time
import threading

class TokenBucket:
    """
    Allows bursts up to `capacity`, refills at `refill_rate` tokens/sec.
    Thread-safe.
    """

    def __init__(self, capacity: int, refill_rate: float):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = float(capacity)
        self.last_refill = time.monotonic()
        self.lock = threading.Lock()

    def allow_request(self, tokens_needed: int = 1) -> bool:
        with self.lock:
            self._refill()
            if self.tokens >= tokens_needed:
                self.tokens -= tokens_needed
                return True
            return False

    def _refill(self) -> None:
        now = time.monotonic()
        elapsed = now - self.last_refill
        self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
        self.last_refill = now


class MultiWindowRateLimiter:
    """Enforces multiple simultaneous windows, e.g. 1/sec, 10/min, 100/hour."""

    def __init__(self, limits: list[tuple[int, int]]):
        self.limits = limits  # [(max_requests, window_seconds), ...]
        self.user_logs: dict[str, deque] = {}

    def allow_request(self, user_id: str) -> bool:
        now = time.time()
        log = self.user_logs.setdefault(user_id, deque())

        max_window = max(w for _, w in self.limits)
        while log and log[0] <= now - max_window:
            log.popleft()

        for max_requests, window_seconds in self.limits:
            cutoff = now - window_seconds
            count = sum(1 for ts in log if ts > cutoff)
            if count >= max_requests:
                return False

        log.append(now)
        return True

C#: Sliding Window Log + Token Bucket

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

public class SlidingWindowRateLimiter
{
    private readonly int _maxRequests;
    private readonly TimeSpan _window;
    private readonly ConcurrentDictionary<string, Queue<DateTime>> _requests = new();
    private readonly object _sync = new();

    public SlidingWindowRateLimiter(int maxRequests, TimeSpan window)
    {
        _maxRequests = maxRequests;
        _window = window;
    }

    public bool AllowRequest(string userId)
    {
        var now = DateTime.UtcNow;
        var queue = _requests.GetOrAdd(userId, _ => new Queue<DateTime>());

        lock (queue)
        {
            while (queue.Count > 0 && queue.Peek() <= now - _window)
                queue.Dequeue();

            if (queue.Count < _maxRequests)
            {
                queue.Enqueue(now);
                return true;
            }
            return false;
        }
    }
}

public class TokenBucket
{
    private readonly int _capacity;
    private readonly double _refillRatePerSecond;
    private double _tokens;
    private DateTime _lastRefill;
    private readonly object _lock = new();

    public TokenBucket(int capacity, double refillRatePerSecond)
    {
        _capacity = capacity;
        _refillRatePerSecond = refillRatePerSecond;
        _tokens = capacity;
        _lastRefill = DateTime.UtcNow;
    }

    public bool AllowRequest(int tokensNeeded = 1)
    {
        lock (_lock)
        {
            Refill();
            if (_tokens >= tokensNeeded)
            {
                _tokens -= tokensNeeded;
                return true;
            }
            return false;
        }
    }

    private void Refill()
    {
        var now = DateTime.UtcNow;
        var elapsedSeconds = (now - _lastRefill).TotalSeconds;
        _tokens = Math.Min(_capacity, _tokens + elapsedSeconds * _refillRatePerSecond);
        _lastRefill = now;
    }
}

// ASP.NET Core: prefer the built-in System.Threading.RateLimiting library
// (AddRateLimiter middleware) in production — FixedWindow, SlidingWindow,
// TokenBucket, and Concurrency limiters ship out of the box since .NET 7.

Distributed rate limiting (architect follow-up)

A single-process implementation doesn’t work once you have multiple API server instances behind a load balancer. Production answer: back the counter with Redis using INCR + EXPIRE (fixed window) or a Lua script for atomic sliding-window/token-bucket logic (avoids race conditions across the increment-and-check). At extreme scale, use a local in-memory limiter as a fast-fail first line of defense, with Redis as the authoritative shared limiter — trading a small amount of over-admission for latency.