← 返回 openai 的题目列表Coding: Design a Distributed Rate Limiter with Persistence (Clock Skew, Redis Fallback)
类型:online_judge
Coding: Design a Distributed Rate Limiter with Persistence
Implement a simple rate limiter that supports distributed deployment and persistence.
Functional requirements
Implement the following interfaces (class or functions are both acceptable):
allowRequest(key: str, now_ms: int) -> bool
Given a key (e.g., userId/IP/apiKey) and current time now_ms, decide whether to allow the request.
reset(key: str) -> None
Reset the rate limit state for the given key.
Choose a clear rate limiting strategy (e.g., sliding window log / fixed window / token bucket) and explicitly specify:
The quota (e.g., at most N requests per 60 seconds).
Window size and time unit.
Distributed requirements
Multiple application servers must share the same rate limit state (not just local memory).
You may use Redis as the shared store (e.g., Sorted Set for a sliding-window log).
Follow-ups to address
Clock skew: server clocks may drift; how do you avoid incorrect decisions due to time mismatch?
Redis fallback: if Redis is down, you must fall back to local storage and keep serving (degraded mode).
Persist locally (e.g., to a file) so state survives process restarts.
When Redis comes back, asynchronously replay/sync locally accumulated data back to Redis (e.g., via an async queue).
Constraints and edge cases
Handle concurrency (multiple concurrent requests for the same key).
State any acceptable error bounds (e.g., more conservative/lenient behavior in degraded mode).
Tests
Provide at least 5 test cases covering:
Requests under quota return true.
Exceeding quota returns false.
After the window moves, requests become allowed again.
reset allows requests again.
Degraded mode when Redis is unavailable and replay after recovery (can be mocked).
Example
Input
quota: 3 requests / 10s; key=A; times=[0,1000,2000]
Output
[true,true,true]