Atomic Multi-Quota Job Rate Limiter
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build a thread-safe job admission limiter (RateLimiter) that enforces three simultaneous, epoch-aligned fixed-window quotas whenever a caller submits a job of integer weight effort on behalf of user_id:
- Per-user window cap (
user_limit): A singleuser_idmay spend at mostuser_limittotal effort inside each fixed window of lengthuser_window_seconds(default86400seconds). - Global 1-hour cap (
hourly_limit): Across all users combined, total accepted effort may not exceedhourly_limitinside each3600-second fixed window. - Global 24-hour cap (
daily_limit): Across all users combined, total accepted effort may not exceeddaily_limitinside each86400-second fixed window.
Implement the RateLimiter class with the following interface:
RateLimiter(user_limit: int, hourly_limit: int, daily_limit: int, user_window_seconds: int = 86400, clock: Callable[[], float] = time.time)— initializes the three quota dimensions usingclock()as the source of Unix timestamps in seconds.allow_request(user_id: str, effort: int) -> bool— evaluates whether the job fits all three quotas and returnsTrueif admitted orFalseif rejected.
Your implementation must obey these exact rules:
- Input validation: If
effort < 1, raiseValueErrorimmediately without charging any quota. - Epoch-aligned fixed windows: A timestamp
nowmaps to window indexint(now // window_length). When a newer window index is observed (candidate_index > current_index), that bucket's accumulated usage resets to0. - Non-monotonic clock safety: Even if
clock()temporarily jumps backward to an older timestamp, no bucket may revert to an earlier window or reset its current window's count. Advancing window indices happens before quota checks so even a rejected request moves window high-water marks forward. - All-or-nothing atomicity: Admit a request if and only if
already_used + effort <= limitholds for all three buckets simultaneously. Accepted requests deducteffortfrom all three buckets atomically; rejected requests leave every bucket untouched. - Concurrency & distributed extension:
allow_requestmust be safe under concurrent calls from multiple threads without overshooting any cap. Alongside the in-memory class, consider how the same atomic check-and-charge pattern extends across multiple stateless servers sharing a store such as Redis (without distributed locks) and how to absorb bursts from high-volume users.
Examples
Example 1
Input:
clock = FakeClock(0.0)
limiter = RateLimiter(user_limit=12, hourly_limit=18, daily_limit=50,
user_window_seconds=86400, clock=clock)
1. t = 0: limiter.allow_request("dev_maya", 9)
2. t = 100: limiter.allow_request("dev_maya", 5)
3. t = 200: limiter.allow_request("dev_noah", 9)
4. t = 500: limiter.allow_request("dev_noah", 2)
5. t = 3600: limiter.allow_request("dev_noah", 2)
Output:
[True, False, True, False, True]
Walk-through:
- Call 1 (t = 0): "dev_maya" spends 9 (<= 12 user, <= 18 hour, <= 50 day) -> True. Totals: dev_maya = 9, hour = 9, day = 9.
- Call 2 (t = 100): 9 + 5 = 14 > 12 exceeds "dev_maya"'s user cap -> False. Neither hour nor day is charged (hour = 9, day = 9).
- Call 3 (t = 200): "dev_noah" spends 9; global hour reaches 9 + 9 = 18 <= 18 -> True. Totals: dev_noah = 9, hour = 18, day = 18.
- Call 4 (t = 500): "dev_noah" still has user capacity (9 + 2 <= 12), but global hour would hit 18 + 2 = 20 > 18 -> False. "dev_noah" stays at 9 and day stays at 18.
- Call 5 (t = 3600): int(3600 // 3600) = 1 resets hour to 0 while user and day remain in day window 0. Now dev_noah = 9 + 2 = 11 <= 12, hour = 0 + 2 = 2 <= 18, and day = 18 + 2 = 20 <= 50 -> True.
Example 2
Input:
clock = FakeClock(3590.0)
limiter = RateLimiter(user_limit=6, hourly_limit=10, daily_limit=14,
user_window_seconds=60, clock=clock)
1. t = 3590: limiter.allow_request("svc_etl", 6)
2. t = 3610: limiter.allow_request("svc_etl", 6)
3. t = 3595: limiter.allow_request("svc_etl", 1)
4. t = 3670: limiter.allow_request("svc_etl", 4)
Output:
[True, True, False, False]
Walk-through:
- Call 1 (t = 3590): Fills "svc_etl"'s 60-second window 59 (6 / 6), hour 0 (6 / 10), and day 0 (6 / 14) -> True.
- Call 2 (t = 3610): Advances "svc_etl" to 60-second window 60 (0 -> 6) and global hour to 1 (0 -> 6), while day 0 accumulates 6 + 6 = 12 <= 14 -> True.
- Call 3 (t = 3595): Clock steps backward, so window 60 and hour 1 stay active (svc_etl = 6); 6 + 1 = 7 > 6 -> False.
- Call 4 (t = 3670): "svc_etl" enters 60-second window 61 (0 + 4 <= 6) and hour 1 fits (6 + 4 = 10 <= 10), but day 0 would reach 12 + 4 = 16 > 14 -> False.
Constraints
1 <= user_limit, hourly_limit, daily_limit <= 10^91 <= user_window_seconds <= 86400 * 30user_idis a non-empty string.effortis an integer; anyeffort < 1must raiseValueError.clock()returns afloatorinttimestamp in seconds (>= 0).allow_requestmust run inO(1)time per call and be thread-safe across concurrent threads.
Step-by-step walkthrough
Pin down the rules and window model
Every incoming job carries a positive integer
effort(its computational weight) and must fit inside three independent quota buckets at the same time:Bucket Dictionary key Max effort Window length ------------- -------------------- --------------- --------------------------------- Per-user user_id ("dev_maya") user_limit user_window_seconds (default 1d) Global hourly "*" (shared) hourly_limit 3,600 seconds (1 hour) Global daily "*" (shared) daily_limit 86,400 seconds (24 hours)Before writing code, we lock down four contract rules:
- Epoch-aligned fixed windows. A fixed window divides the timeline into non-overlapping blocks of length
Lseconds starting from Unix time0. Any timestampnowbelongs to window numberint(now // L). For example, withL = 3600,now = 3599.9is in hour window0, andnow = 3600.0starts hour window1. Every server can compute this window number locally without coordinating with other machines. - All-or-nothing atomicity. A job is accepted if and only if
already_used + effort <= limitholds for all three buckets. If even one bucket would exceed its limit, the call returnsFalseand zero buckets are charged. - Strict positive effort.
effort < 1raisesValueError. Allowing negative effort would let a caller add quota back instead of spending it. - Injectable clock. Passing
clock: Callable[[], float] = time.timelets unit tests jump cleanly to exact window boundaries without sleeping.
- Epoch-aligned fixed windows. A fixed window divides the timeline into non-overlapping blocks of length
Why naive check-then-act breaks under concurrency
The first thing most people write is: read each counter, check whether
used + effort <= limit, and then addeffort. When two threads or two application servers run that logic at the same moment, two bugs appear immediately.First, check-then-act race conditions allow bursts past the limit:
hourly_limit = 100, current hour usage = 95 Server A: reads hour usage -> 95. Checks 95 + 5 <= 100 -> OK! Server B: reads hour usage -> 95. Checks 95 + 5 <= 100 -> OK! Server A: adds 5 -> hour usage becomes 100 Server B: adds 5 -> hour usage becomes 105 (overshot the 100 limit!)Second, charging buckets one at a time leaks quota on rejected jobs: if you add
effortto the user bucket first and then discover the global daily bucket is full, the user has already paid for a job that never ran. Trying to subtracteffortafterward in a separate step can race with window rollovers and corrupt the new window's count.The cure for both bugs is to make "advance windows -> check all three -> charge all three" one indivisible step: - Inside a single Python process, we guard the entire decision with one
threading.Lock(a mutex, short for mutual exclusion lock, which lets only one thread inside the block at a time). - Across multiple servers, we move the counters to Redis and run the exact same check-and-charge sequence inside one Redis Lua script, which Redis runs atomically from start to finish without interleaving other clients' commands.Build a single fixed-window counter
Each quota dimension needs the same helper: track how much effort each key has used in the current window, and wipe old counts automatically as soon as time enters a newer window.
Why wipe the whole dictionary on rollover? Because every entry in
self.used_by_keybelonged to the finished window, so dropping the dictionary resets every user at once and keeps memory proportional only to users active in the current window.Watch out for one clock subtlety: real server clocks adjusted by NTP (Network Time Protocol) can occasionally step slightly backwards. If
advancereset whenevercandidate_window != self.window_index, a stray timestamp from3599sarriving after3600swould reset the counter back to hour0, and the next3600scall would wipe hour1all over again! Checkingcandidate_window > self.window_indexensures the window index only ever moves forward.from typing import Callable, Dict, List, Optional, Tuple import threading import time HOUR_SECONDS = 3600 DAY_SECONDS = 86400 GLOBAL_KEY = "*" class FixedWindowCounter: """Tracks effort spent per key inside the current epoch-aligned fixed window.""" def __init__(self, window_seconds: int) -> None: self.window_seconds = window_seconds # window_index: integer index int(now // window_seconds), or None before the first call self.window_index: Optional[int] = None # used_by_key: maps bucket key -> effort spent in window_index (e.g., {"alice": 8} or {"*": 15}) self.used_by_key: Dict[str, int] = {} def advance(self, now: float) -> None: candidate_window = int(now // self.window_seconds) # Use strict '>' so a backward clock jump never resets or reverts to an older window. if self.window_index is None or candidate_window > self.window_index: self.window_index = candidate_window self.used_by_key = {} def get_used(self, key: str) -> int: return self.used_by_key.get(key, 0) def add_effort(self, key: str, effort: int) -> None: self.used_by_key[key] = self.used_by_key.get(key, 0) + effortImplement atomic multi-bucket checking in RateLimiter
Inside
RateLimiter.allow_request, we validateeffort >= 1, acquireself.lock, readself.clock(), and run three separate tiny loops over our 3(counter, bucket_key, limit)triples:- Phase 1 (Advance all windows): Advance all three counters to
nowbefore checking any quota. Why not combine Phase 1 and Phase 2 into one loop? Supposedev_mayais out of daily user quota and submits a request atnow = 3600(the start of hour1). If we returnedFalseright after checkinguser_counter,hour_counterwould never learn that3600happened — so if a slightly delayed clock read3599arrived next,hour_counterwould still charge stale hour0instead of hour1. - Phase 2 (Read-only check): Check
already_used + effort > limitfor every bucket. ReturningFalsehere is completely safe because nothing has been mutated yet. - Phase 3 (Charge all buckets): Add
effortto all three counters and returnTrue.
Notice also why
now = self.clock()sits insidewith self.lock:: if two threads read the clock before waiting on the lock, the thread with the newer timestamp might win the lock first, making the second thread look like a backward clock jump.class RateLimiter: def __init__(self, user_limit: int, hourly_limit: int, daily_limit: int, user_window_seconds: int = DAY_SECONDS, clock: Callable[[], float] = time.time) -> None: self.user_limit = user_limit self.hourly_limit = hourly_limit self.daily_limit = daily_limit self.clock = clock # Separate fixed-window counters for the three independent quota dimensions self.user_counter = FixedWindowCounter(user_window_seconds) self.hour_counter = FixedWindowCounter(HOUR_SECONDS) self.day_counter = FixedWindowCounter(DAY_SECONDS) # Mutex serializing clock read + check + charge across concurrent caller threads self.lock = threading.Lock() def allow_request(self, user_id: str, effort: int) -> bool: # Reject zero or negative effort up front so a bad input can never refund quota. if effort < 1: raise ValueError("effort must be a positive integer") # Read the clock inside the lock so threads are processed in monotonic lock order. with self.lock: now = self.clock() # buckets_to_check: list of (counter, bucket_key, max_limit) triples buckets_to_check: List[Tuple[FixedWindowCounter, str, int]] = [ (self.user_counter, user_id, self.user_limit), (self.hour_counter, GLOBAL_KEY, self.hourly_limit), (self.day_counter, GLOBAL_KEY, self.daily_limit), ] # Phase 1: Advance every counter first, even if an early quota check will fail, # so a rejected call at a new timestamp still moves all windows forward. for counter, bucket_key, limit in buckets_to_check: counter.advance(now) # Phase 2: Verify all quotas without modifying any counter (all-or-nothing check). # Exact equality (already_used + effort == limit) is allowed; only '>' fails. for counter, bucket_key, limit in buckets_to_check: already_used = counter.get_used(bucket_key) if already_used + effort > limit: return False # Phase 3: Every check passed, so charge effort to all three buckets atomically. for counter, bucket_key, limit in buckets_to_check: counter.add_effort(bucket_key, effort) return True- Phase 1 (Advance all windows): Advance all three counters to
Scale across servers with an atomic Redis Lua script
In production across many stateless app servers,
threading.Lockonly protects threads inside one process. Moving our 3-phase algorithm into Redis requires zero distributed locks: Redis executes a Lua script atomically on a single thread, so no other client command can run between Phase 2 (GET) and Phase 3 (INCRBY).Instead of explicitly wiping a dictionary when a window ends, we include the
window_indexinside each Redis key name (for examplerl:{quota}:hour:1). When hour2begins, servers naturally start reading and writingrl:{quota}:hour:2, andEXPIREATtells Redis to garbage-collect the old hour1key shortly after its window closes:-- KEYS[1..3] = [user_key, hour_key, day_key] for the current epoch windows -- ARGV[1] = effort (positive integer) -- ARGV[2..4] = [user_limit, hourly_limit, daily_limit] -- ARGV[5..7] = [user_exp, hour_exp, day_exp] (Unix timestamps for cleanup) local effort = tonumber(ARGV[1]) if not effort or effort < 1 then return redis.error_reply("effort must be >= 1") end -- Phase 2: Check all three buckets before modifying anything for i = 1, 3 do local already_used = tonumber(redis.call("GET", KEYS[i]) or "0") local limit = tonumber(ARGV[i + 1]) if already_used + effort > limit then return 0 end end -- Phase 3: Charge all three buckets and schedule key cleanup after window end for i = 1, 3 do redis.call("INCRBY", KEYS[i], effort) redis.call("EXPIREAT", KEYS[i], tonumber(ARGV[i + 4])) end return 1Each application server computes the three window-indexed keys and invokes the registered script in one network round trip:
GRACE_SECONDS = 60 def build_redis_bucket(prefix: str, now: float, window_seconds: int) -> Tuple[str, int]: """Return (redis_key, expire_at_unix_seconds) for the window containing `now`.""" window_index = int(now // window_seconds) # '{quota}' is a Redis Cluster hash tag forcing all three keys onto the same shard. redis_key = f"rl:{{quota}}:{prefix}:{window_index}" expires_at = (window_index + 1) * window_seconds + GRACE_SECONDS return redis_key, expires_at def allow_request_redis( lua_script, user_id: str, effort: int, now: float, limits: Tuple[int, int, int], user_window_seconds: int = 86400, ) -> bool: if effort < 1: raise ValueError("effort must be a positive integer") user_key, user_exp = build_redis_bucket(f"user:{user_id}", now, user_window_seconds) hour_key, hour_exp = build_redis_bucket("hour", now, 3600) day_key, day_exp = build_redis_bucket("day", now, 86400) allowed = lua_script( keys=[user_key, hour_key, day_key], args=[effort, limits[0], limits[1], limits[2], user_exp, hour_exp, day_exp], ) return allowed == 1Two production details make this rock-solid: - Hash tags in Redis Cluster (
{quota}). Redis Cluster refuses to run a multi-key script unless all keys hash to the same hash slot (partition). Wrapping{quota}in braces forces Redis to hash only the substringquota, placing the user, hour, and day keys on the same shard. -EXPIREATinstead ofEXPIRE. Setting an absolute Unix timestamp (window_end + 60s) means expiry is purely memory cleanup after the window has already ended. Using a relativeEXPIRE 3600on an un-indexed key (rl:hour) would push the deadline forward on every call so a busy system would never reset!Mitigate hot users and hot global keys
Because every request touches the shared global
houranddaykeys on one Redis shard, a single primary caps out around50,000–100,000Lua script executions per second. When a noisy user blasts thousands of requests per second (or overall fleet traffic grows huge), three layers take pressure off Redis:- Local deny caching (for exhausted quotas). Have the Lua script return which bucket failed and its remaining capacity
r. Because fixed-window usage never decreases within a window,ris a guaranteed upper bound until the window rolls over: the app server caches(bucket, window_index, r)in local RAM and immediately rejects any request witheffort > rfor the rest of that window with zero Redis calls. - Local quota leases (batch pre-allocation). Instead of calling Redis per job of
effort = 1, an app server requests a small lease of50effort units across(user, hour, day)in one Lua call, serves jobs locally from that balance, and flushes unused units on lease expiry. A hot user sending5,000jobs/s ofeffort = 1now triggers only5,000 / 50 = 100Redis calls/s (a50xreduction). The trade-off is bounded under-utilization:20servers holding50idle units each temporarily tie up at most1,000units (1%of a100,000hourly limit). - Sharded global sub-buckets. If legitimate accepted traffic exceeds one Redis shard, split the global hourly and daily limits across
Sshards (each shard enforceshourly_limit / Sanddaily_limit / S, routinguser_idconsistently by hash) with a background coordinator shifting unused budget from quiet shards to busy ones.
- Local deny caching (for exhausted quotas). Have the Lua script return which bucket failed and its remaining capacity
Trace a multi-user request sequence
Let's trace Example 1 (
RateLimiter(user_limit=12, hourly_limit=18, daily_limit=50)withuser_window_seconds = 86400):Time (s) Call User bucket Hour bucket (idx) Day bucket (idx) Result -------- ----------------- ----------------- ----------------- ---------------- ------ 0 ("dev_maya", 9) maya: 0 -> 9 0 -> 9 (idx 0) 0 -> 9 (idx 0) True 100 ("dev_maya", 5) 9 + 5 > 12! unchanged (9) unchanged (9) False 200 ("dev_noah", 9) noah: 0 -> 9 9 -> 18 (idx 0) 9 -> 18 (idx 0) True 500 ("dev_noah", 2) 9 + 2 <= 12 ok 18 + 2 > 18! unchanged (18) False 3600 ("dev_noah", 2) noah: 9 -> 11 reset! 0 -> 2 (1) 18 -> 20 (idx 0) TrueLook at the two key behaviors in action: - At
t = 100,("dev_maya", 5)fails Maya's per-user limit (14 > 12), leavinghouranddayuntouched at9so("dev_noah", 9)can still succeed att = 200. - Att = 3600,int(3600 // 3600) = 1rollshour_counterto a fresh window (0 -> 2), whileint(3600 // 86400) = 0keepsuser_counter(9 -> 11) andday_counter(18 -> 20) accumulating in day0.Complete solution
from typing import Callable, Dict, List, Optional, Tuple import threading import time HOUR_SECONDS = 3600 DAY_SECONDS = 86400 GLOBAL_KEY = "*" class FixedWindowCounter: """Tracks effort spent per key inside the current epoch-aligned fixed window.""" def __init__(self, window_seconds: int) -> None: self.window_seconds = window_seconds # window_index: integer index int(now // window_seconds), or None before the first call self.window_index: Optional[int] = None # used_by_key: maps bucket key -> effort spent in window_index (e.g., {"alice": 8} or {"*": 15}) self.used_by_key: Dict[str, int] = {} def advance(self, now: float) -> None: candidate_window = int(now // self.window_seconds) # Use strict '>' so a backward clock jump never resets or reverts to an older window. if self.window_index is None or candidate_window > self.window_index: self.window_index = candidate_window self.used_by_key = {} def get_used(self, key: str) -> int: return self.used_by_key.get(key, 0) def add_effort(self, key: str, effort: int) -> None: self.used_by_key[key] = self.used_by_key.get(key, 0) + effort class RateLimiter: """Accept a job only if it fits every quota; then charge all of them at once. Quotas are fixed windows aligned to the epoch (window index = int(now // length)): - per user: at most user_limit effort per user_window_seconds window, - global: at most hourly_limit effort per hour and daily_limit per day. A request is allowed when used + effort <= limit for all three buckets. A rejected request charges nothing. If the clock steps backwards, the newest window seen so far stays current. clock() returns seconds; tests pass a fake clock. Must be safe to call from many threads at once. """ def __init__(self, user_limit: int, hourly_limit: int, daily_limit: int, user_window_seconds: int = DAY_SECONDS, clock: Callable[[], float] = time.time) -> None: self.user_limit = user_limit self.hourly_limit = hourly_limit self.daily_limit = daily_limit self.clock = clock # Separate fixed-window counters for the three independent quota dimensions self.user_counter = FixedWindowCounter(user_window_seconds) self.hour_counter = FixedWindowCounter(HOUR_SECONDS) self.day_counter = FixedWindowCounter(DAY_SECONDS) # Mutex serializing clock read + check + charge across concurrent caller threads self.lock = threading.Lock() def allow_request(self, user_id: str, effort: int) -> bool: """Return True and charge every bucket if the job fits all quotas, else False.""" # Reject zero or negative effort up front so a bad input can never refund quota. if effort < 1: raise ValueError("effort must be a positive integer") # Read the clock inside the lock so threads are processed in monotonic lock order. with self.lock: now = self.clock() # buckets_to_check: list of (counter, bucket_key, max_limit) triples buckets_to_check: List[Tuple[FixedWindowCounter, str, int]] = [ (self.user_counter, user_id, self.user_limit), (self.hour_counter, GLOBAL_KEY, self.hourly_limit), (self.day_counter, GLOBAL_KEY, self.daily_limit), ] # Phase 1: Advance every counter first, even if an early quota check will fail, # so a rejected call at a new timestamp still moves all windows forward. for counter, bucket_key, limit in buckets_to_check: counter.advance(now) # Phase 2: Verify all quotas without modifying any counter (all-or-nothing check). # Exact equality (already_used + effort == limit) is allowed; only '>' fails. for counter, bucket_key, limit in buckets_to_check: already_used = counter.get_used(bucket_key) if already_used + effort > limit: return False # Phase 3: Every check passed, so charge effort to all three buckets atomically. for counter, bucket_key, limit in buckets_to_check: counter.add_effort(bucket_key, effort) return True✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a shipping dispatcher guarding a shared freight elevator with three rules posted on the wall: each department can ship at most 12 tons per day, the whole building can ship at most 18 tons per hour, and at most 50 tons per day. A shipment is allowed onto the elevator only if all three clipboards have enough room at the exact same moment, and the dispatcher writes the weight onto all three clipboards before talking to the next person in line. Our rate limiter works the same way using fixed-window counters — integer totals tied to non-overlapping time blocks such as int(now // 3600) for hours — wrapped inside a single atomic decision (an indivisible operation that either completes in full or changes nothing, implemented with a threading.Lock in memory and a single Lua script in Redis across servers).
Why does the obvious approach fail? If an application server reads the three counters with GET, checks the math in Python, and then sends INCRBY commands, two servers handling requests at the same millisecond will both see 14 / 18 used, both approve effort = 4, and push usage to 22 (a check-then-act race condition). Worse, if you charge buckets one by one and stop when the third bucket is full, earlier buckets stay charged for a rejected job unless you issue rollback decrements — which can themselves race with a window reset and corrupt the new window's count.
Let's trace 5 calls from Example 1 with user_limit = 12 (per day), hourly_limit = 18, and daily_limit = 50:
1. t = 0, ("dev_maya", 9): user[dev_maya] 0+9<=12, hour 0+9<=18, day 0+9<=50 -> True (all 3 become 9)
2. t = 100, ("dev_maya", 5): user[dev_maya] 9+5=14 > 12 -> False (hour and day stay 9; zero partial charge!)
3. t = 200, ("dev_noah", 9): user[dev_noah] 0+9<=12, hour 9+9<=18, day 9+9<=50 -> True (hour=18, day=18)
4. t = 500, ("dev_noah", 2): user[dev_noah] 9+2<=12, hour 18+2=20 > 18 -> False (noah stays 9, day stays 18)
5. t = 3600, ("dev_noah", 2): hour window index flips 0 -> 1 (hour resets to 0), day index stays 0:
user[dev_noah] 9+2<=12, hour 0+2<=18, day 18+2<=50 -> True (noah=11, hour=2, day=20)
Complexity
- Time:
O(1)perallow_requestcall. Every call advances 3 counters, performs at most 3 dictionary lookups, and performs at most 3 dictionary writes under a single mutex lock (and in the distributed Redis version, executes 1 network round trip running 3GETs and at most 3INCRBY+EXPIREAToperations inside one Lua script). - Space:
O(U)whereUis the number of distinct users active in the current user window. Wheneveruser_countermoves into a new window index, it replacesused_by_keywith a fresh empty dictionary, discarding inactive users from earlier windows;hour_counterandday_counterstore at most one global"*"entry each (and in Redis, old window keys are deleted automatically viaEXPIREAT).
Edge cases
- Exact capacity match (
already_used + effort == limit): Allowed (True), filling the bucket to100%; one additional unit (effort = 1) immediately returnsFalse. - Single job larger than a limit (
effort > limit): Fails Phase 2 immediately and charges zero buckets. In a production HTTP/gRPC service, return a permanent "payload exceeds max quota" status rather than "retry later" so clients do not retry forever. - Invalid non-positive cost (
effort <= 0): RaisesValueErrorbefore touching the lock so callers can never pass a negative number to refund quota. - Boundary bursts on fixed windows: Timestamp
3599.9falls in hour0(int(3599.9 // 3600) == 0) while3600.0starts hour1. A client can legally spendhourly_limitat3599sand anotherhourly_limitat3600s(2xthe hourly rate within 2 seconds) — the classic fixed-window boundary burst trade-off. - Clock stepping backwards: Because
FixedWindowCounter.advancecheckscandidate_window > self.window_index, a backward timestamp never reverts to an older window or wipes the current window's counts. Advancing all three counters in Phase 1 before any Phase 2 check can returnFalseguarantees that even a rejected request advances the high-water window on every bucket. - Staggered window rollovers: At
t = 3600, the hourly bucket resets to0while the 24-hour global and per-user buckets keep their accumulated totals untilt = 86400.
Common mistakes
- Splitting reads and writes across separate Redis calls: Calling
GETin application code andINCRBYafterward allows concurrent app servers to approve overlapping jobs and exceed global quotas. - Mutating counters while checking: Incrementing
user_counterbefore verifyinghour_counterandday_counterpenalizes users for rejected jobs. - Using Redis
MULTI/EXECwithout Lua: Commands queued inside a basic RedisMULTI/EXECtransaction cannot branch on the return value of an earlierGET, and pairing it withWATCH(optimistic locking) causes massive retry storms on the shared global hour/day keys under heavy concurrency. - Using relative
EXPIREon a static key name: CallingINCRBY rl:hour effortfollowed byEXPIRE rl:hour 3600resets the 1-hour timer on every request, meaning a busy cluster never expires the key and permanently locks out traffic. Always encodewindow_indexin the key name and useEXPIREAT. - Cross-slot errors in Redis Cluster: Omitting a shared hash tag like
{quota}inrl:{quota}:...causes Redis Cluster to place the user, hour, and day keys on different hash slots and reject the Lua script with aCROSSSLOTerror. - Blindly retrying timed-out Redis requests: If the Lua script succeeded on Redis but the network dropped the response, a retry will charge
efforttwice. Pass a unique idempotency key (a per-request unique ID stored briefly viaSET req_id 1 NX EX 3600inside the Lua script) so retries return the cached decision without double-charging.
Follow-up questions
- How would your architecture change if the 1-hour global cap had to enforce a true trailing 60-minute window instead of snapping to clock-hour boundaries? A sliding window enforces the cap over the exact trailing 3,600 seconds
[now - 3600, now]rather than snapping to:00clock boundaries, eliminating the2xboundary burst. An exact implementation stores each accepted job in a Redis sorted set (a collection ordered by numeric timestamp score), evicting entries older thannow - 3600viaZREMRANGEBYSCOREinside the Lua script, though that costsO(J)memory forJjobs in the hour. A much cheaper production choice is either sub-window bucketing (60 one-minute keys summed in Lua, bounding memory to 60 integers) or a sliding-window counter approximationcurrent_hour + previous_hour * (1 - elapsed_in_hour / 3600): for example,15minutes (25%) into the current hour with200used now and600used last hour estimates200 + 600 * 0.75 = 650effort. - How can you stop a handful of heavyweight batch jobs from exhausting the shared 24-hour budget and starving smaller interactive tasks? First, enforce a per-job maximum effort cap (for instance
max_job_effort = 1%ofdaily_limit) so no single submission can swallow a huge fraction of the day, while thehourly_limit(<= daily_limit / 10) naturally paces consumption across the day. Second, add tiered capacity reservations as a fourth bucket in the same atomic check — for example, capping "heavy jobs" (effort > 1,000) at60%ofdaily_limitso40%is always reserved for small interactive jobs. Third, if jobs can be queued asynchronously rather than synchronously rejected, schedule them with weighted fair queuing such as Deficit Round Robin (a scheduler that gives each user a turn-by-turn credit allowance proportional to their share so small-job users never wait behind one user's giant batch). - When the shared Redis store becomes unreachable, should admission fail open or fail closed, and what factors govern that choice? Choose based on the blast radius of over-admission versus downtime: fail-closed when protecting scarce or costly downstream resources (expensive GPU clusters, paid third-party APIs, or security/abuse boundaries), and fail-open when the limiter merely smooths multi-tenant fairness in front of a backend with headroom. In practice, a degraded local fallback gives the best middle ground: wrap Redis calls in a circuit breaker (a fast-fail switch that stops calling an unhealthy dependency after repeated timeouts) and fall back to an in-memory
RateLimiteron each of theNapp servers configured withlimit / N(e.g.,10servers each enforce10,000/hrfor a100,000/hrglobal cap). That keeps total outage admission bounded to at most one global limit per window while alerting operators and failing over to a Redis replica.
Follow-up questions
- How would your architecture change if the 1-hour global cap had to enforce a true trailing 60-minute window instead of snapping to clock-hour boundaries?
- How can you stop a handful of heavyweight batch jobs from exhausting the shared 24-hour budget and starving smaller interactive tasks?
- When the shared Redis store becomes unreachable, should admission fail open or fail closed, and what factors govern that choice?
Similar questions
- Zero Trust Access Models and Segmented Video Security
- Multi-Region Telemetry Monitoring and Alerting
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging