Implement a thread-safe in-memory rate limiter
Quick Overview
Build a thread-safe token bucket rate limiter in Python that supports multiple named buckets, configurable rates and capacities, and provides both blocking and non-blocking consumption modes.
Affirm
6
Build a thread-safe token bucket rate limiter in Python that supports multiple named buckets, configurable rates and capacities, and provides both blocking and non-blocking consumption modes.
Rate limiting is essential for protecting Affirm's payment APIs. This phone screen problem tests your understanding of concurrency, data structures, and the token bucket algorithm in a practical context.
What the Interviewer Expects
- Implement the token bucket algorithm correctly with proper time-based token refill
- Ensure thread safety using appropriate Python synchronization primitives
- Support multiple independent rate limit buckets keyed by name
- Provide both try_consume (non-blocking) and consume (blocking) methods
- Handle edge cases: burst capacity, bucket not found, zero rate
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you persist bucket state across process restarts?
- How would you extend this to work across multiple processes using Redis?
- What are the trade-offs between token bucket and sliding window approaches?
- How would you add monitoring to track rejection rates per bucket?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem requires us to implement a thread-safe token bucket rate limiter that can effectively manage multiple named buckets with configurable rates and capacities. The token bucket algorithm is su...
Approach
- Define the Bucket Class: Each bucket will hold its capacity, rate, and the current number of tokens, along with a timestamp to track the last refill time.
- Replenish Tokens: Implement a m...