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:

  1. Per-user window cap (user_limit): A single user_id may spend at most user_limit total effort inside each fixed window of length user_window_seconds (default 86400 seconds).
  2. Global 1-hour cap (hourly_limit): Across all users combined, total accepted effort may not exceed hourly_limit inside each 3600-second fixed window.
  3. Global 24-hour cap (daily_limit): Across all users combined, total accepted effort may not exceed daily_limit inside each 86400-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 using clock() 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 returns True if admitted or False if rejected.

Your implementation must obey these exact rules:

  • Input validation: If effort < 1, raise ValueError immediately without charging any quota.
  • Epoch-aligned fixed windows: A timestamp now maps to window index int(now // window_length). When a newer window index is observed (candidate_index > current_index), that bucket's accumulated usage resets to 0.
  • 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 <= limit holds for all three buckets simultaneously. Accepted requests deduct effort from all three buckets atomically; rejected requests leave every bucket untouched.
  • Concurrency & distributed extension: allow_request must 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^9
  • 1 <= user_window_seconds <= 86400 * 30
  • user_id is a non-empty string.
  • effort is an integer; any effort < 1 must raise ValueError.
  • clock() returns a float or int timestamp in seconds (>= 0).
  • allow_request must run in O(1) time per call and be thread-safe across concurrent threads.

Step-by-step walkthrough

  1. 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 L seconds starting from Unix time 0. Any timestamp now belongs to window number int(now // L). For example, with L = 3600, now = 3599.9 is in hour window 0, and now = 3600.0 starts hour window 1. 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 <= limit holds for all three buckets. If even one bucket would exceed its limit, the call returns False and zero buckets are charged.
    • Strict positive effort. effort < 1 raises ValueError. Allowing negative effort would let a caller add quota back instead of spending it.
    • Injectable clock. Passing clock: Callable[[], float] = time.time lets unit tests jump cleanly to exact window boundaries without sleeping.
  2. 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 add effort. 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 effort to 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 subtract effort afterward 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.

  3. 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_key belonged 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 advance reset whenever candidate_window != self.window_index, a stray timestamp from 3599s arriving after 3600s would reset the counter back to hour 0, and the next 3600s call would wipe hour 1 all over again! Checking candidate_window > self.window_index ensures 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) + effort
    
  4. Implement atomic multi-bucket checking in RateLimiter

    Inside RateLimiter.allow_request, we validate effort >= 1, acquire self.lock, read self.clock(), and run three separate tiny loops over our 3 (counter, bucket_key, limit) triples:

    1. Phase 1 (Advance all windows): Advance all three counters to now before checking any quota. Why not combine Phase 1 and Phase 2 into one loop? Suppose dev_maya is out of daily user quota and submits a request at now = 3600 (the start of hour 1). If we returned False right after checking user_counter, hour_counter would never learn that 3600 happened — so if a slightly delayed clock read 3599 arrived next, hour_counter would still charge stale hour 0 instead of hour 1.
    2. Phase 2 (Read-only check): Check already_used + effort > limit for every bucket. Returning False here is completely safe because nothing has been mutated yet.
    3. Phase 3 (Charge all buckets): Add effort to all three counters and return True.

    Notice also why now = self.clock() sits inside with 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
    
  5. Scale across servers with an atomic Redis Lua script

    In production across many stateless app servers, threading.Lock only 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_index inside each Redis key name (for example rl:{quota}:hour:1). When hour 2 begins, servers naturally start reading and writing rl:{quota}:hour:2, and EXPIREAT tells Redis to garbage-collect the old hour 1 key 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 1
    

    Each 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 == 1
    

    Two 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 substring quota, placing the user, hour, and day keys on the same shard. - EXPIREAT instead of EXPIRE. Setting an absolute Unix timestamp (window_end + 60s) means expiry is purely memory cleanup after the window has already ended. Using a relative EXPIRE 3600 on an un-indexed key (rl:hour) would push the deadline forward on every call so a busy system would never reset!

  6. Mitigate hot users and hot global keys

    Because every request touches the shared global hour and day keys on one Redis shard, a single primary caps out around 50,000–100,000 Lua 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:

    1. 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, r is 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 with effort > r for the rest of that window with zero Redis calls.
    2. Local quota leases (batch pre-allocation). Instead of calling Redis per job of effort = 1, an app server requests a small lease of 50 effort 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 sending 5,000 jobs/s of effort = 1 now triggers only 5,000 / 50 = 100 Redis calls/s (a 50x reduction). The trade-off is bounded under-utilization: 20 servers holding 50 idle units each temporarily tie up at most 1,000 units (1% of a 100,000 hourly limit).
    3. Sharded global sub-buckets. If legitimate accepted traffic exceeds one Redis shard, split the global hourly and daily limits across S shards (each shard enforces hourly_limit / S and daily_limit / S, routing user_id consistently by hash) with a background coordinator shifting unused budget from quiet shards to busy ones.
  7. Trace a multi-user request sequence

    Let's trace Example 1 (RateLimiter(user_limit=12, hourly_limit=18, daily_limit=50) with user_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)  True
    

    Look at the two key behaviors in action: - At t = 100, ("dev_maya", 5) fails Maya's per-user limit (14 > 12), leaving hour and day untouched at 9 so ("dev_noah", 9) can still succeed at t = 200. - At t = 3600, int(3600 // 3600) = 1 rolls hour_counter to a fresh window (0 -> 2), while int(3600 // 86400) = 0 keeps user_counter (9 -> 11) and day_counter (18 -> 20) accumulating in day 0.

  8. 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) per allow_request call. 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 3 GETs and at most 3 INCRBY + EXPIREAT operations inside one Lua script).
  • Space: O(U) where U is the number of distinct users active in the current user window. Whenever user_counter moves into a new window index, it replaces used_by_key with a fresh empty dictionary, discarding inactive users from earlier windows; hour_counter and day_counter store at most one global "*" entry each (and in Redis, old window keys are deleted automatically via EXPIREAT).

Edge cases

  • Exact capacity match (already_used + effort == limit): Allowed (True), filling the bucket to 100%; one additional unit (effort = 1) immediately returns False.
  • 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): Raises ValueError before touching the lock so callers can never pass a negative number to refund quota.
  • Boundary bursts on fixed windows: Timestamp 3599.9 falls in hour 0 (int(3599.9 // 3600) == 0) while 3600.0 starts hour 1. A client can legally spend hourly_limit at 3599s and another hourly_limit at 3600s (2x the hourly rate within 2 seconds) — the classic fixed-window boundary burst trade-off.
  • Clock stepping backwards: Because FixedWindowCounter.advance checks candidate_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 return False guarantees that even a rejected request advances the high-water window on every bucket.
  • Staggered window rollovers: At t = 3600, the hourly bucket resets to 0 while the 24-hour global and per-user buckets keep their accumulated totals until t = 86400.

Common mistakes

  • Splitting reads and writes across separate Redis calls: Calling GET in application code and INCRBY afterward allows concurrent app servers to approve overlapping jobs and exceed global quotas.
  • Mutating counters while checking: Incrementing user_counter before verifying hour_counter and day_counter penalizes users for rejected jobs.
  • Using Redis MULTI/EXEC without Lua: Commands queued inside a basic Redis MULTI/EXEC transaction cannot branch on the return value of an earlier GET, and pairing it with WATCH (optimistic locking) causes massive retry storms on the shared global hour/day keys under heavy concurrency.
  • Using relative EXPIRE on a static key name: Calling INCRBY rl:hour effort followed by EXPIRE rl:hour 3600 resets the 1-hour timer on every request, meaning a busy cluster never expires the key and permanently locks out traffic. Always encode window_index in the key name and use EXPIREAT.
  • Cross-slot errors in Redis Cluster: Omitting a shared hash tag like {quota} in rl:{quota}:... causes Redis Cluster to place the user, hour, and day keys on different hash slots and reject the Lua script with a CROSSSLOT error.
  • Blindly retrying timed-out Redis requests: If the Lua script succeeded on Redis but the network dropped the response, a retry will charge effort twice. Pass a unique idempotency key (a per-request unique ID stored briefly via SET req_id 1 NX EX 3600 inside 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 :00 clock boundaries, eliminating the 2x boundary burst. An exact implementation stores each accepted job in a Redis sorted set (a collection ordered by numeric timestamp score), evicting entries older than now - 3600 via ZREMRANGEBYSCORE inside the Lua script, though that costs O(J) memory for J jobs 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 approximation current_hour + previous_hour * (1 - elapsed_in_hour / 3600): for example, 15 minutes (25%) into the current hour with 200 used now and 600 used last hour estimates 200 + 600 * 0.75 = 650 effort.
  • 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% of daily_limit) so no single submission can swallow a huge fraction of the day, while the hourly_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) at 60% of daily_limit so 40% 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 RateLimiter on each of the N app servers configured with limit / N (e.g., 10 servers each enforce 10,000/hr for a 100,000/hr global 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

Similar questions

More Zscaler interview questions

All 3 Zscaler questions →