Coding questions · Snapchat
Implement a thread-safe rate limiter
This question evaluates a candidate's ability to design and implement a thread-safe per-user API rate limiter, focusing on concurrency control, synchronization techniques, and time-based request accounting in the Coding & Algorithms domain.
Design and implement a per-user API rate limiter.
Requirements:
- Method:
boolean allow(String userId, long nowMillis)returns whether the request is allowed at timenowMillis. - Policy: allow at most N requests per W milliseconds per user.
- Choose any standard algorithm (e.g., fixed window, sliding window, token bucket).
Follow-ups:
- How do you make it safe under concurrency (multiple threads calling
allowfor the sameuserId)? - Discuss tradeoffs between using locks vs lock-free/low-lock approaches (e.g.,
ConcurrentHashMap, atomics) and performance implications.
Per-User Sliding-Window Rate Limiter
For each (user,time) request, allow at most limit requests per user in the previous window_ms interval.
Constraints
- requests are processed in arrival order
Examples
Example 1
Input: ([('u', 0), ('u', 10), ('u', 20)], 2, 100)
Output: [True, True, False]
Explanation: Third rejected.
Example 2
Input: ([('u', 0), ('v', 1), ('u', 100)], 2, 100)
Output: [True, True, True]
Explanation: Boundary evicts old request.
Hints
- Use one deque of accepted timestamps per user.