Design a Per-User API Rate Limiter with Token Bucket and Leaky Bucket Algorithms

Quick Overview

Design a per-user rate limiter that supports both token bucket and leaky bucket algorithms and answers allow or deny calls at logical timestamps. It tests lazy refill math, a strategy-pattern class design, thread safety and floating-point edge cases.

Design a Per-User API Rate Limiter with Token Bucket and Leaky Bucket Algorithms

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a rate limiter that supports multiple rate limiting algorithms and is configurable per user. The rate limiter must support two algorithms: Token Bucket and Leaky Bucket. In the Token Bucket algorithm, a bucket holds up to `maxTokens` tokens and refills at `refillRate` tokens per second. Each allowed request consumes one token. If no tokens are available, the request is denied. In the Leaky Bucket algorithm, a bucket of fixed `capacity` leaks (processes) requests at `leakRate` requests per second. An incoming request is added to the bucket if there is space after leaking. If the bucket is full, the request is denied. Each user can be registered with a specific algorithm and configuration. Unregistered users are denied by default. Each call receives a logical timestamp in seconds, which keeps the behavior deterministic. All state-modifying operations must be thread-safe. Implement the following methods: - `addUser(userId: str, algorithm: str, maxTokens: int, refillRate: int, capacity: int, leakRate: int)`: Register a user with a rate limiting algorithm, `"TokenBucket"` or `"LeakyBucket"`. For TokenBucket, `maxTokens` and `refillRate` are used. For LeakyBucket, `capacity` and `leakRate` are used. Unused parameters can be set to 0. - `removeUser(userId: str)`: Remove a user's rate limiter configuration. Future requests from this user will be denied. - `isAllowed(userId: str, timestamp: float) -> bool`: Check whether a request from the given user is allowed at the given logical timestamp. Returns false if the user is not registered. - `getTokens(userId: str, timestamp: float) -> int`: Return the current number of available tokens or slots for the user at the given timestamp. Returns -1 if the user is not registered. Example 1: ```text operations = ["RateLimiter", "addUser", "isAllowed", "isAllowed", "isAllowed", "isAllowed", "getTokens", "isAllowed", "getTokens"] arguments = [[], ["alice", "TokenBucket", 3, 1, 0, 0], ["alice", 0], ["alice", 0], ["alice", 0], ["alice", 0], ["alice", 0], ["alice", 1], ["alice", 1]] Output: [null, null, true, true, true, false, 0, true, 0] ``` Alice uses a token bucket with `maxTokens = 3` and `refillRate = 1` per second. At t = 0 she has 3 tokens, so the first three requests succeed and the fourth fails with 0 tokens left. By t = 1 one token has refilled, so the fifth request succeeds and leaves 0 tokens. Example 2: ```text operations = ["RateLimiter", "addUser", "isAllowed", "isAllowed", "isAllowed", "isAllowed", "getTokens", "isAllowed"] arguments = [[], ["bob", "LeakyBucket", 0, 0, 3, 2], ["bob", 0], ["bob", 0], ["bob", 0], ["bob", 0.5], ["bob", 0.5], ["bob", 0.5]] Output: [null, null, true, true, true, true, 0, false] ``` Bob uses a leaky bucket with `capacity = 3` and `leakRate = 2` per second. The three requests at t = 0 fill the bucket. By t = 0.5 one request has leaked out (half a second at 2 per second), so the level is 2 and the request at t = 0.5 is allowed, which fills the bucket again. `getTokens` at t = 0.5 returns 0, and the last request is denied because the bucket is full. ```hint No timers needed Nothing has to run between calls. When a call arrives, work out how far the bucket should have moved since its last update. ``` ```hint Watch the arithmetic Timestamps are floats. Check what your comparison does when an elapsed time such as 0.3 - 0.2 is multiplied by the rate. ``` ### Constraints & Assumptions - `1 <= maxTokens <= 10⁴` - `1 <= refillRate <= 1000` (tokens per second for Token Bucket) - `1 <= capacity <= 10⁴` (for Leaky Bucket) - `1 <= leakRate <= 1000` (requests per second for Leaky Bucket) - Timestamps are non-negative floats and non-decreasing per user. - User IDs are non-empty strings. - A new Token Bucket starts full and a new Leaky Bucket starts empty, as the examples show. - `getTokens` reports whole tokens or slots, so a fractional amount is rounded down. ### Clarifying Questions to Ask - Should `addUser` for a user who is already registered reset that user's bucket, or carry the current level over to the new settings? - What should happen with an unknown algorithm name: ignore the call, keep any old configuration, or raise an error? - Can a user's timestamps ever go backwards (clock skew, retries), and if so, should that count as zero elapsed time? - Does the limiter run in a single process, or must several servers share one user's limit? ### What a Strong Answer Covers - A shared limiter interface with one class per algorithm and a registry that maps each user to an instance. - Lazy refill and leak computed from elapsed time, with the bounds (the cap at `maxTokens` or `capacity`, the floor at zero) applied on every call. - Correct results for unregistered and removed users, for re-registration, and for unknown algorithm names. - What the lock protects, and whether one global lock or per-user locking fits better. - Floating-point behavior on timestamps, plus O(1) time per call and O(n) space for n users. ### Follow-up Questions - How would you add a third algorithm, such as a sliding window log, without changing `RateLimiter`? - How would you enforce these limits across many API servers that share one user's quota? - With millions of mostly idle users, how would you keep memory bounded? - How would you tell a denied client how long to wait before retrying?

Overview: Design a per-user rate limiter that supports both token bucket and leaky bucket algorithms and answers allow or deny calls at logical timestamps. It tests lazy refill math, a strategy-pattern class design, thread safety and floating-point edge cases.

Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a rate limiter that supports multiple rate limiting algorithms and is configurable per user. The rate limiter must support two algorithms: Token Bucket and Leaky Bucket.

In the Token Bucket algorithm, a bucket holds up to maxTokens tokens and refills at refillRate tokens per second. Each allowed request consumes one token. If no tokens are available, the request is denied.

In the Leaky Bucket algorithm, a bucket of fixed capacity leaks (processes) requests at leakRate requests per second. An incoming request is added to the bucket if there is space after leaking. If the bucket is full, the request is denied.

Each user can be registered with a specific algorithm and configuration. Unregistered users are denied by default. Each call receives a logical timestamp in seconds, which keeps the behavior deterministic. All state-modifying operations must be thread-safe.

Implement the following methods:

  • addUser(userId: str, algorithm: str, maxTokens: int, refillRate: int, capacity: int, leakRate: int) : Register a user with a rate limiting algorithm, "TokenBucket" or "LeakyBucket" . For TokenBucket, maxTokens and refillRate are used. For LeakyBucket, capacity and leakRate are used. Unused parameters can be set to 0.
  • removeUser(userId: str) : Remove a user's rate limiter configuration. Future requests from this user will be denied.
  • isAllowed(userId: str, timestamp: float) -> bool : Check whether a request from the given user is allowed at the given logical timestamp. Returns false if the user is not registered.
  • getTokens(userId: str, timestamp: float) -> int : Return the current number of available tokens or slots for the user at the given timestamp. Returns -1 if the user is not registered.

Example 1:

operations = ["RateLimiter", "addUser", "isAllowed", "isAllowed", "isAllowed", "isAllowed", "getTokens", "isAllowed", "getTokens"]
arguments  = [[], ["alice", "TokenBucket", 3, 1, 0, 0], ["alice", 0], ["alice", 0], ["alice", 0], ["alice", 0], ["alice", 0], ["alice", 1], ["alice", 1]]

Output: [null, null, true, true, true, false, 0, true, 0]

Alice uses a token bucket with maxTokens = 3 and refillRate = 1 per second. At t = 0 she has 3 tokens, so the first three requests succeed and the fourth fails with 0 tokens left. By t = 1 one token has refilled, so the fifth request succeeds and leaves 0 tokens.

Example 2:

operations = ["RateLimiter", "addUser", "isAllowed", "isAllowed", "isAllowed", "isAllowed", "getTokens", "isAllowed"]
arguments  = [[], ["bob", "LeakyBucket", 0, 0, 3, 2], ["bob", 0], ["bob", 0], ["bob", 0], ["bob", 0.5], ["bob", 0.5], ["bob", 0.5]]

Output: [null, null, true, true, true, true, 0, false]

Bob uses a leaky bucket with capacity = 3 and leakRate = 2 per second. The three requests at t = 0 fill the bucket. By t = 0.5 one request has leaked out (half a second at 2 per second), so the level is 2 and the request at t = 0.5 is allowed, which fills the bucket again. getTokens at t = 0.5 returns 0, and the last request is denied because the bucket is full.

Constraints & Assumptions

  • 1 <= maxTokens <= 10⁴
  • 1 <= refillRate <= 1000 (tokens per second for Token Bucket)
  • 1 <= capacity <= 10⁴ (for Leaky Bucket)
  • 1 <= leakRate <= 1000 (requests per second for Leaky Bucket)
  • Timestamps are non-negative floats and non-decreasing per user.
  • User IDs are non-empty strings.
  • A new Token Bucket starts full and a new Leaky Bucket starts empty, as the examples show.
  • getTokens reports whole tokens or slots, so a fractional amount is rounded down.

Clarifying Questions to Ask Guidance

  • Should addUser for a user who is already registered reset that user's bucket, or carry the current level over to the new settings?
  • What should happen with an unknown algorithm name: ignore the call, keep any old configuration, or raise an error?
  • Can a user's timestamps ever go backwards (clock skew, retries), and if so, should that count as zero elapsed time?
  • Does the limiter run in a single process, or must several servers share one user's limit?

What a Strong Answer Covers Guidance

  • A shared limiter interface with one class per algorithm and a registry that maps each user to an instance.
  • Lazy refill and leak computed from elapsed time, with the bounds (the cap at maxTokens or capacity , the floor at zero) applied on every call.
  • Correct results for unregistered and removed users, for re-registration, and for unknown algorithm names.
  • What the lock protects, and whether one global lock or per-user locking fits better.
  • Floating-point behavior on timestamps, plus O(1) time per call and O(n) space for n users.

Follow-up Questions Guidance

  • How would you add a third algorithm, such as a sliding window log, without changing RateLimiter ?
  • How would you enforce these limits across many API servers that share one user's quota?
  • With millions of mostly idle users, how would you keep memory bounded?
  • How would you tell a denied client how long to wait before retrying?