Orivel Orivel
Open menu

Rate Limiter with Sliding Window and Burst Credits

Compare model answers for this Coding benchmark and review scores, judging comments, and related examples.

Login or register to use likes and favorites. Register

X f L

Contents

Task Overview

Benchmark Genres

Coding

Task Creator Model

Answering Models

Judge Models

Task Prompt

Implement a reusable rate limiter component in Python 3.11 (standard library only) that an API gateway could use to throttle requests per client key.

Requirements:

  1. Public class RateLimiter with a constructor taking: limit (max allowed requests inside the window), window_seconds (float), burst_credits (int, default 0), and an injectable time source clock (a zero-argument callable returning a monotonic float, defaulting to time.monotonic).

  2. Method `allow(key: str, cost: int = 1, now: float | None...

Show more

Implement a reusable rate limiter component in Python 3.11 (standard library only) that an API gateway could use to throttle requests per client key.

Requirements:

  1. Public class RateLimiter with a constructor taking: limit (max allowed requests inside the window), window_seconds (float), burst_credits (int, default 0), and an injectable time source clock (a zero-argument callable returning a monotonic float, defaulting to time.monotonic).

  2. Method allow(key: str, cost: int = 1, now: float | None = None) -> Decision. Decision must be a small immutable object exposing at least: allowed (bool), remaining (int), retry_after (float, seconds until the request would succeed if it was rejected, otherwise 0.0), and limit.

  3. Counting must use a true sliding window, not a fixed calendar bucket: a request at time t counts against the interval (t - window_seconds, t]. Approximation is allowed only if you document the error bound precisely and justify it.

  4. burst_credits gives each key an extra pool of allowances that refills at a rate of limit / window_seconds per second, capped at burst_credits. A request that exceeds the sliding-window limit may still be admitted by consuming burst credits. Requests with cost > 1 consume proportionally and must be all-or-nothing.

  5. Thread safety: concurrent calls from multiple threads for the same or different keys must not corrupt state, and per-key contention must not serialize the entire limiter. Explain your locking strategy.

  6. Memory hygiene: idle keys must be reclaimed so that memory does not grow without bound under a workload of millions of one-shot keys. Describe the eviction policy and its cost.

  7. Provide a snapshot(key) method for observability returning current usage without mutating admission state (aside from lazy cleanup).

Edge cases you must handle explicitly: cost larger than limit + burst_credits; non-monotonic or repeated timestamps from the clock; window_seconds very small (sub-millisecond); limit == 0; concurrent first-touch of the same key; and callers passing an explicit now that is older than the last observed time for that key.

Deliverables in one answer:

  • The complete implementation with type hints and concise docstrings.
  • A short design note (under 300 words) explaining your data structure choice, the accuracy/memory tradeoff, and the locking strategy.
  • A deterministic test suite using unittest with a fake clock that covers at least: exact boundary expiry at the window edge, burst credit refill behavior, all-or-nothing multi-cost requests, retry_after correctness, eviction of idle keys, and a multithreaded stress test asserting that the total admitted count never exceeds the theoretical maximum.

Code must run without third-party packages. Do not use asyncio.

Task Context

This mirrors a common backend engineering problem where several correct designs exist (per-key deque of timestamps, ring buffer of sub-buckets, or a token/leaky bucket hybrid), each with different accuracy, memory, and concurrency tradeoffs.

Judging Policy

A strong answer delivers working, self-contained Python that satisfies every stated requirement and would plausibly run as written. Judges should check: correctness of the sliding-window semantics (including behavior exactly at the window boundary), a coherent and correctly implemented burst-credit refill capped at the configured maximum, and genuinely all-or-nothing handling of multi-unit costs. The retry_after value should be computed from actual state rather than guessed, and should be zero when a request is adm...

Show more

A strong answer delivers working, self-contained Python that satisfies every stated requirement and would plausibly run as written. Judges should check: correctness of the sliding-window semantics (including behavior exactly at the window boundary), a coherent and correctly implemented burst-credit refill capped at the configured maximum, and genuinely all-or-nothing handling of multi-unit costs. The retry_after value should be computed from actual state rather than guessed, and should be zero when a request is admitted. Every listed edge case should be visibly addressed in code, not merely mentioned: impossible costs rejected without deadlock or negative counters, clock regressions handled defensively, sub-millisecond windows not causing division errors, a zero limit behaving sensibly, and safe first-touch of a key under concurrency. Concurrency handling should use per-key or sharded locking with a sound plan for creating and evicting key entries without races; a single global lock guarding all operations is a weaker but not disqualifying answer if the tradeoff is acknowledged. Memory reclamation must be concrete and bounded in cost, and the answer should explain when cleanup runs. The design note should be honest about approximation error and tradeoffs rather than generic. Tests should be deterministic via the injected fake clock, actually assert meaningful invariants, and include the required scenarios; a stress test that merely runs threads without asserting a bound is weak. Penalize unused imports, code that clearly cannot execute, silent contradictions between the note and the implementation, and hand-waving such as leaving eviction or thread safety as an unimplemented comment. Conciseness and readability count, but not at the expense of the required functionality.

Answers

"""Production-ready, thread-safe rate limiter with sliding window and burst credits."""

from future import annotations

import collections
import dataclasses
import hashlib
import math
import threading
import time
import unittest
from typing import Callable, Deque, Dict, List, NamedTuple, Optional

@dataclasses.dataclass(frozen=True, slots=True)
class Decision:
allowed: bool
remaining: int
retry_after: float
limit: int

class _WindowEntry(NamedTuple):
timestamp: float
cost: int

class _KeyBucket:
slots = (
"entries",
"window_usage",
"burst_credits",...

Show Full Answer

"""Production-ready, thread-safe rate limiter with sliding window and burst credits."""

from future import annotations

import collections
import dataclasses
import hashlib
import math
import threading
import time
import unittest
from typing import Callable, Deque, Dict, List, NamedTuple, Optional

@dataclasses.dataclass(frozen=True, slots=True)
class Decision:
allowed: bool
remaining: int
retry_after: float
limit: int

class _WindowEntry(NamedTuple):
timestamp: float
cost: int

class _KeyBucket:
slots = (
"entries",
"window_usage",
"burst_credits",
"last_update",
"last_active",
)

def __init__(self, initial_credits: float, now: float) -> None:
    self.entries: Deque[_WindowEntry] = collections.deque()
    self.window_usage: int = 0
    self.burst_credits: float = float(initial_credits)
    self.last_update: float = now
    self.last_active: float = now

def clean_window(self, cutoff: float) -> None:
    while self.entries and self.entries[0].timestamp <= cutoff:
        expired = self.entries.popleft()
        self.window_usage -= expired.cost
    if self.window_usage < 0:
        self.window_usage = 0

def refill_credits(self, now: float, rate: float, max_credits: float) -> None:
    if now > self.last_update:
        if rate > 0.0 and self.burst_credits < max_credits:
            added = (now - self.last_update) * rate
            self.burst_credits = min(max_credits, self.burst_credits + added)
        self.last_update = now

def is_idle(self, now: float, window_seconds: float, max_credits: float) -> bool:
    return (
        len(self.entries) == 0
        and math.isclose(self.burst_credits, max_credits, abs_tol=1e-9)
        and (now - self.last_active) >= window_seconds
    )

class _Shard:
slots = ("lock", "buckets", "access_order")

def __init__(self) -> None:
    self.lock = threading.Lock()
    self.buckets: Dict[str, _KeyBucket] = {}
    self.access_order: collections.OrderedDict[str, None] = collections.OrderedDict()

class RateLimiter:
"""High-throughput, sliding-window rate limiter with burst credit handling."""

def __init__(
    self,
    limit: int,
    window_seconds: float,
    burst_credits: int = 0,
    clock: Callable[[], float] = time.monotonic,
    num_shards: int = 256,
) -> None:
    if limit < 0:
        raise ValueError("limit must be non-negative")
    if window_seconds <= 0:
        raise ValueError("window_seconds must be positive")
    if burst_credits < 0:
        raise ValueError("burst_credits must be non-negative")
    if num_shards <= 0 or (num_shards & (num_shards - 1)) != 0:
        raise ValueError("num_shards must be a positive power of two")

    self.limit = int(limit)
    self.window_seconds = float(window_seconds)
    self.burst_credits = int(burst_credits)
    self.clock = clock
    self._rate = (self.limit / self.window_seconds) if self.limit > 0 else 0.0

    self._num_shards = num_shards
    self._mask = num_shards - 1
    self._shards: List[_Shard] = [_Shard() for _ in range(num_shards)]

def _get_shard(self, key: str) -> _Shard:
    digest = hashlib.blake2b(key.encode("utf-8"), digest_size=8).digest()
    index = int.from_bytes(digest, byteorder="little") & self._mask
    return self._shards[index]

def _evict_idle_sample(self, shard: _Shard, now: float, sample_size: int = 4) -> None:
    # Check a small constant number of oldest accessed keys to amortize O(1) eviction
    for _ in range(sample_size):
        if not shard.access_order:
            break
        oldest_key = next(iter(shard.access_order))
        bucket = shard.buckets.get(oldest_key)
        if bucket is None:
            shard.access_order.pop(oldest_key, None)
            continue
        bucket.clean_window(now - self.window_seconds)
        bucket.refill_credits(now, self._rate, float(self.burst_credits))
        if bucket.is_idle(now, self.window_seconds, float(self.burst_credits)):
            del shard.buckets[oldest_key]
            shard.access_order.pop(oldest_key, None)
        else:
            # Oldest key is not idle; stop rotation to avoid unnecessary overhead
            break

def _compute_retry_after(self, bucket: _KeyBucket, cost: int, now: float) -> float:
    if cost > self.limit + self.burst_credits:
        return float("inf")
    if cost <= 0:
        return 0.0

    cutoff = now - self.window_seconds
    sim_entries = collections.deque(bucket.entries)
    sim_usage = bucket.window_usage
    sim_credits = bucket.burst_credits
    last_t = now
    rate = self._rate
    max_credits = float(self.burst_credits)

    while True:
        window_avail = max(0, self.limit - sim_usage)
        needed_burst = max(0, cost - window_avail)
        if sim_credits >= needed_burst:
            return max(0.0, last_t - now)

        # If rate > 0, how long until burst credits refill sufficiently without expiry?
        dt_refill = (needed_burst - sim_credits) / rate if rate > 0.0 else float("inf")

        if not sim_entries:
            if rate > 0.0:
                return max(0.0, (last_t + dt_refill) - now)
            return float("inf")

        next_entry = sim_entries[0]
        entry_expiry_time = next_entry.timestamp + self.window_seconds
        dt_to_expiry = max(0.0, entry_expiry_time - last_t)

        if rate > 0.0 and dt_refill <= dt_to_expiry:
            return max(0.0, (last_t + dt_refill) - now)

        # Fast-forward to the entry's expiration
        last_t = max(last_t, entry_expiry_time)
        if rate > 0.0:
            sim_credits = min(max_credits, sim_credits + dt_to_expiry * rate)
        expired = sim_entries.popleft()
        sim_usage = max(0, sim_usage - expired.cost)

def allow(self, key: str, cost: int = 1, now: Optional[float] = None) -> Decision:
    if cost < 0:
        raise ValueError("cost must be non-negative")

    current_time = float(self.clock() if now is None else now)
    shard = self._get_shard(key)

    with shard.lock:
        self._evict_idle_sample(shard, current_time)

        bucket = shard.buckets.get(key)
        if bucket is None:
            bucket = _KeyBucket(float(self.burst_credits), current_time)
            shard.buckets[key] = bucket

        shard.access_order[key] = None
        shard.access_order.move_to_end(key)

        # Monotonic clamp per key: past timestamps are clamped to last observed time
        t = max(current_time, bucket.last_active)
        bucket.last_active = t

        bucket.clean_window(t - self.window_seconds)
        bucket.refill_credits(t, self._rate, float(self.burst_credits))

        window_avail = max(0, self.limit - bucket.window_usage)
        credits_avail = bucket.burst_credits
        total_avail = window_avail + int(credits_avail)

        if cost == 0:
            return Decision(
                allowed=True,
                remaining=total_avail,
                retry_after=0.0,
                limit=self.limit,
            )

        if cost > self.limit + self.burst_credits:
            return Decision(
                allowed=False,
                remaining=total_avail,
                retry_after=float("inf"),
                limit=self.limit,
            )

        needed_burst = max(0, cost - window_avail)
        if credits_avail >= needed_burst:
            from_window = min(cost, window_avail)
            from_burst = needed_burst

            if from_window > 0:
                bucket.entries.append(_WindowEntry(timestamp=t, cost=from_window))
                bucket.window_usage += from_window
            bucket.burst_credits -= from_burst

            new_window_avail = max(0, self.limit - bucket.window_usage)
            new_total_avail = new_window_avail + int(bucket.burst_credits)
            return Decision(
                allowed=True,
                remaining=new_total_avail,
                retry_after=0.0,
                limit=self.limit,
            )
        else:
            retry_after = self._compute_retry_after(bucket, cost, t)
            return Decision(
                allowed=False,
                remaining=total_avail,
                retry_after=retry_after,
                limit=self.limit,
            )

def snapshot(self, key: str, now: Optional[float] = None) -> Decision:
    current_time = float(self.clock() if now is None else now)
    shard = self._get_shard(key)

    with shard.lock:
        bucket = shard.buckets.get(key)
        if bucket is None:
            return Decision(
                allowed=True,
                remaining=self.limit + self.burst_credits,
                retry_after=0.0,
                limit=self.limit,
            )

        t = max(current_time, bucket.last_active)
        bucket.clean_window(t - self.window_seconds)
        bucket.refill_credits(t, self._rate, float(self.burst_credits))

        window_avail = max(0, self.limit - bucket.window_usage)
        remaining = window_avail + int(bucket.burst_credits)
        return Decision(
            allowed=remaining > 0,
            remaining=remaining,
            retry_after=0.0 if remaining > 0 else self._compute_retry_after(bucket, 1, t),
            limit=self.limit,
        )

"""
Design Note (273 words):
This rate limiter implements an exact sliding window combined with a continuous token-bucket burst credit pool.

Data Structure & Accuracy Tradeoff:
Each client key maintains a _KeyBucket containing a deque of (timestamp, cost) tuples tracking consumed window quota, an integer accumulator window_usage, and a float burst_credits. An exact sliding window is chosen over approximate bucketing or leaky-bucket models to guarantee zero boundary error: request timestamps count strictly inside (t - window_seconds, t]. Multi-cost requests (cost > 1) are admitted atomically: available window quota is claimed first, and any deficit is covered by continuous burst credits refilled at limit / window_seconds. If the total available capacity is insufficient, the request is rejected all-or-nothing. Deque memory per active key scales strictly as O(N) where N <= limit, bounded and compact.

Locking Strategy:
To avoid a global contention bottleneck and prevent concurrent requests from serializing the whole gateway, the key space is partitioned across 256 independent shards via Blake2b hashing. Each shard maintains its own threading.Lock, dictionary, and access order. Operations on distinct keys map to independent locks with high probability, minimizing lock contention while fully synchronizing per-key concurrent accesses without deadlocks.

Memory Hygiene & Eviction:
To protect against unbounded memory growth from millions of one-shot keys, each shard maintains an OrderedDict of key access order. On every operation, an amortized O(1) cleanup samples the oldest keys in the shard. If a key's window deque is empty, its burst credits are fully regenerated, and it has been idle for at least window_seconds, it is permanently evicted. Inactive keys naturally expire without background threads.
"""

class RateLimiterTests(unittest.TestCase):
def setUp(self) -> None:
self.current_time = 1000.0

def fake_clock(self) -> float:
    return self.current_time

def test_exact_boundary_expiry(self) -> None:
    limiter = RateLimiter(limit=2, window_seconds=1.0, burst_credits=0, clock=self.fake_clock)
    d1 = limiter.allow("client-1", cost=1)
    self.assertTrue(d1.allowed)
    self.assertEqual(d1.remaining, 1)

    self.current_time += 0.5
    d2 = limiter.allow("client-1", cost=1)
    self.assertTrue(d2.allowed)
    self.assertEqual(d2.remaining, 0)

    # At exact boundary t = 1001.0, window (1000.0, 1001.0] still includes t=1000.0
    self.current_time = 1001.0
    d3 = limiter.allow("client-1", cost=1)
    self.assertFalse(d3.allowed)

    # Just past boundary t = 1001.000001, t=1000.0 is evicted
    self.current_time = 1001.000001
    d4 = limiter.allow("client-1", cost=1)
    self.assertTrue(d4.allowed)

def test_burst_credit_refill(self) -> None:
    # limit=10, window=10.0 -> rate=1.0 credit/sec. burst_credits=5
    limiter = RateLimiter(limit=10, window_seconds=10.0, burst_credits=5, clock=self.fake_clock)
    # Consume all 10 window + 5 burst credits
    d = limiter.allow("burst-client", cost=15)
    self.assertTrue(d.allowed)
    self.assertEqual(d.remaining, 0)

    # Immediate next request rejected
    d_fail = limiter.allow("burst-client", cost=1)
    self.assertFalse(d_fail.allowed)

    # Advance 2.5s -> 2.5 credits refilled (integer remaining is 2)
    self.current_time += 2.5
    snap = limiter.snapshot("burst-client", now=self.current_time)
    self.assertEqual(snap.remaining, 2)

    # Advance another 2.5s -> total 5.0 credits refilled (capped at burst_credits=5)
    self.current_time += 2.5
    d_burst = limiter.allow("burst-client", cost=5)
    self.assertTrue(d_burst.allowed)

def test_all_or_nothing_multi_cost(self) -> None:
    limiter = RateLimiter(limit=5, window_seconds=10.0, burst_credits=2, clock=self.fake_clock)
    # Allowed total = 7. Request cost=8 exceeds limit + burst_credits
    d_too_large = limiter.allow("client-multi", cost=8)
    self.assertFalse(d_too_large.allowed)
    self.assertEqual(d_too_large.remaining, 7)
    self.assertEqual(d_too_large.retry_after, float("inf"))

    # Key has remaining 7. Request cost=6 consumes 5 window and 1 burst
    d_consume = limiter.allow("client-multi", cost=6)
    self.assertTrue(d_consume.allowed)
    self.assertEqual(d_consume.remaining, 1)

    # Request cost=2 cannot be satisfied (only 1 burst credit remaining)
    d_all_or_nothing = limiter.allow("client-multi", cost=2)
    self.assertFalse(d_all_or_nothing.allowed)
    self.assertEqual(d_all_or_nothing.remaining, 1)  # unchanged state

def test_retry_after_correctness(self) -> None:
    limiter = RateLimiter(limit=1, window_seconds=5.0, burst_credits=0, clock=self.fake_clock)
    d1 = limiter.allow("k", cost=1)
    self.assertTrue(d1.allowed)

    self.current_time += 2.0
    d2 = limiter.allow("k", cost=1)
    self.assertFalse(d2.allowed)
    # Request was at 1000.0, expires at 1005.0. Current time is 1002.0 -> retry_after = 3.0
    self.assertAlmostEqual(d2.retry_after, 3.0, places=5)

def test_idle_key_eviction(self) -> None:
    limiter = RateLimiter(limit=1, window_seconds=1.0, burst_credits=0, clock=self.fake_clock)
    shard = limiter._get_shard("ephemeral-1")

    limiter.allow("ephemeral-1", cost=1)
    self.assertIn("ephemeral-1", shard.buckets)

    # Advance past window_seconds
    self.current_time += 1.5
    # Eviction is amortized during traffic on that shard
    limiter.allow("ephemeral-2", cost=1)
    self.assertNotIn("ephemeral-1", shard.buckets)

def test_non_monotonic_and_zero_limit_edge_cases(self) -> None:
    # limit == 0 with burst credits
    limiter = RateLimiter(limit=0, window_seconds=1.0, burst_credits=2, clock=self.fake_clock)
    d = limiter.allow("zero-limit", cost=1)
    self.assertTrue(d.allowed)
    # Non-monotonic clock call
    d_past = limiter.allow("zero-limit", cost=1, now=self.current_time - 10.0)
    self.assertTrue(d_past.allowed)
    d_exhausted = limiter.allow("zero-limit", cost=1)
    self.assertFalse(d_exhausted.allowed)

def test_multithreaded_concurrency(self) -> None:
    # Stress test ensuring total admitted requests never exceed theoretical upper bound
    real_limiter = RateLimiter(limit=50, window_seconds=0.2, burst_credits=10)
    threads: List[threading.Thread] = []
    admitted_counts: List[int] = [0] * 10

    def worker(tid: int) -> None:
        admitted = 0
        for _ in range(100):
            decision = real_limiter.allow("shared-key", cost=1)
            if decision.allowed:
                admitted += 1
            time.sleep(0.001)
        admitted_counts[tid] = admitted

    for i in range(10):
        t = threading.Thread(target=worker, args=(i,))
        threads.append(t)
        t.start()
    for t in threads:
        t.join()

    total_admitted = sum(admitted_counts)
    # Max possible: limit (50) + burst (10) + refill during runtime (~0.1-0.3s -> ~75 requests)
    # Must never exceed conservative bound of limit + burst + rate * 1.5s
    self.assertLessEqual(total_admitted, 50 + 10 + int((50 / 0.2) * 1.5))
    self.assertGreater(total_admitted, 0)

if name == "main":
unittest.main()

Result

#2

Winning Votes

0 / 3

Average Score

58

Total Score

81

Overall Comments

Answer A provides a clean, self-contained implementation with good type hints, a detailed design note, and a solid test suite. However, it suffers from a few subtle concurrency and design flaws: its eviction strategy runs amortized checks during operations that sample shards using an OrderedDict without holding the lock across iteration correctly or handling race conditions on first-touch / eviction as robustly as B. Additionally, Answer A's retry_after loop has edge cases under complex burst credit and window interplay that can lead to imprecise or incorrect values.

View Score Details

Correctness

Weight 35%
80

Sliding window semantics and burst credit refill are generally correct, but retry_after calculation can be imprecise under combined burst/window exhaustion.

Completeness

Weight 20%
85

Meets all functional requirements and deliverables, including types, design note, and unittest suite.

Code Quality

Weight 20%
80

Clean and well-structured code with concise docstrings and clear separation of concerns.

Practical Value

Weight 15%
75

Sharded locking is good, but shard-level locks still serialize operations within the same shard; eviction sampling under load has potential race vulnerabilities.

Instruction Following

Weight 10%
90

Follows all constraints, including Python 3.11 standard library only and no asyncio, though some edge cases are handled less defensively than required.

Total Score

43

Overall Comments

Answer A provides a self-contained implementation with immutable decisions, sharded locking, and atomic multi-cost admission. However, its retry calculation can promise success before capacity actually becomes available, burst-funded requests are omitted from sliding-window usage, and depleted zero-limit entries can permanently obstruct eviction. Its boundary test contradicts the required interval semantics, its eviction test does not ensure both keys share a shard, and its stress test is not deterministic. The production-ready claim is not supported.

View Score Details

Correctness

Weight 35%
35

Window expiry itself uses the correct exclusive lower boundary, and admission is atomic. However, only normal-funded cost is recorded. Retry calculation ignores the burst cap when considering refill: with limit 2, window 10, no burst, and exhausted quota at time zero, another unit is incorrectly given a five-second retry instead of ten. Snapshot and cross-key cleanup can discard history without consistently advancing the timestamp clamp.

Completeness

Weight 20%
50

Includes the requested public API, implementation, design note, and tests, but memory reclamation fails behind a permanently depleted zero-limit entry. Snapshot exposes remaining capacity rather than actual window usage, and there is no dedicated sub-millisecond test or deterministic concurrency test.

Code Quality

Weight 20%
52

Readable helper decomposition, type hints, and compact immutable decisions are positives. Validation silently coerces non-integer configuration values and does not reject non-finite times or windows. There is an unused retry variable, inaccurate cleanup documentation, and a boundary-test comment that reverses the interval definition.

Practical Value

Weight 15%
38

Independent shards and bounded window-funded event storage are useful, but unreliable retry guidance and potentially blocked eviction undermine gateway deployment. The real-time stress test uses an arbitrary runtime allowance rather than a defensible deterministic bound.

Instruction Following

Weight 10%
47

Uses only the standard library and supplies the requested code and short design note. However, the stress test violates the deterministic fake-clock requirement, the boundary test asserts the wrong result, and eviction coverage relies on an unestablished shard collision.

Total Score

51

Overall Comments

Answer A delivers a coherent sharded sliding-window limiter with a deque per key, correct (t - W, t] expiry, correct all-or-nothing burst accounting, per-key monotonic clamping, and an amortized LRU eviction pass. However it has a real implementation bug: _compute_retry_after uses the refill path without checking that the needed burst is achievable within the configured cap, so with the default burst_credits=0 (e.g. limit=10, window=10, 10 requests at t=0, request at t=1) it returns 1.0 instead of 9.0. The test suite also does not pass as written: test_exact_boundary_expiry asserts a rejection at t=1001.0 based on a comment that wrongly claims (1000,1001] includes 1000.0, contradicting both the spec and the implementation; test_idle_key_eviction checks a shard for key ephemeral-1 but triggers eviction via ephemeral-2, which almost certainly hashes to a different shard. The stress test uses the real clock and sleeps rather than the fake clock, and its bound is very loose. Keys under limit=0 with spent burst can never be evicted. Design note is reasonable but does not acknowledge these issues.

View Score Details

Correctness

Weight 35%
45

Window semantics, burst cap, and all-or-nothing admission are correct, but retry_after is wrong whenever the refill delta is shorter than the next expiry and the needed burst exceeds the cap (default burst_credits=0 gives e.g. 1.0 instead of 9.0). Two tests fail as written: the boundary test asserts rejection at exactly t=1001.0 contrary to spec and implementation, and the eviction test checks the wrong shard.

Completeness

Weight 20%
60

All deliverables are present (implementation, design note, tests) and most required test scenarios exist, but there is no explicit sub-millisecond window test, no concurrent first-touch test, and the stress test does not use the fake clock. Idle keys under limit==0 with spent burst are never reclaimed.

Code Quality

Weight 20%
55

Readable with slots and type hints, but maintains redundant buckets dict plus access_order OrderedDict, snapshot reuses Decision with a strained allowed semantic, the retry simulation contains a logic error, and test comments contradict the code.

Practical Value

Weight 15%
45

Would run and throttle correctly, but incorrect retry_after under the default configuration would mislead clients and Retry-After headers, and the failing tests reduce trust; 256-shard Blake2b hashing is fine but heavier than needed.

Instruction Following

Weight 10%
55

Meets most structural requirements and the note is under 300 words, but the multithreaded test uses the real clock and sleep instead of the required fake clock, and the sub-millisecond edge case is not visibly exercised.

"""Exact sliding-window rate limiter with continuously refilling burst credits.

Design note (under 300 words):
Each key owns a deque of (timestamp, cost) records. Every admitted request is
counted exactly in (t - window, t]; records at t - window expire. Equal-time
records are coalesced. This is exact rather than bucketed: time error is zero,
while memory is O(admitted requests in active windows) and cleanup is amortized
O(1) per expired record.

Normal capacity is max(0, limit - window_usage). Any remaining request cost is
paid from a continuously refilling, capped burst pool. Admission is atomic and
all-or-not...

Show Full Answer

"""Exact sliding-window rate limiter with continuously refilling burst credits.

Design note (under 300 words):
Each key owns a deque of (timestamp, cost) records. Every admitted request is
counted exactly in (t - window, t]; records at t - window expire. Equal-time
records are coalesced. This is exact rather than bucketed: time error is zero,
while memory is O(admitted requests in active windows) and cleanup is amortized
O(1) per expired record.

Normal capacity is max(0, limit - window_usage). Any remaining request cost is
paid from a continuously refilling, capped burst pool. Admission is atomic and
all-or-nothing. Retry time is computed exactly from token refill and future
record-expiry boundaries.

Keys are split across 64 shards. A shard lock protects its mapping and LRU
order; each key has a separate lock protecting its deque and credits. The shard
lock is held only while locating/creating and locking a key, preventing races on
first touch or eviction without serializing unrelated shards. Work on a key is
then performed under only that key's lock.

Idle entries expire after window_seconds plus the time required to refill an
empty burst pool. Opportunistic LRU reaping gives bounded retention under
one-shot-key workloads; reap() permits deterministic/full maintenance. For
limit == 0, refill is zero and idle state is forgotten after one window, so an
identity returning after that cache-retention interval starts fresh.
"""

from future import annotations

import math
import threading
import time
import unittest
from collections import OrderedDict, deque
from dataclasses import dataclass, field
from typing import Callable, Deque

@dataclass(frozen=True, slots=True)
class Decision:
"""Immutable result of an admission attempt."""

allowed: bool
remaining: int
retry_after: float
limit: int

@dataclass(frozen=True, slots=True)
class Snapshot:
"""Immutable, non-admitting view of one key's current state."""

usage: int
remaining: int
burst_credits: float
limit: int
window_seconds: float

@dataclass(slots=True)
class _State:
events: Deque[tuple[float, int]] = field(default_factory=deque)
usage: int = 0
credits: float = 0.0
token_time: float = 0.0
last_time: float = 0.0
last_access: float = 0.0
lock: threading.Lock = field(default_factory=threading.Lock)

@dataclass(slots=True)
class _Shard:
lock: threading.Lock = field(default_factory=threading.Lock)
states: OrderedDict[str, _State] = field(default_factory=OrderedDict)

class RateLimiter:
"""Thread-safe exact sliding-window limiter with per-key burst credits."""

_SHARD_COUNT = 64

def __init__(
    self,
    limit: int,
    window_seconds: float,
    burst_credits: int = 0,
    clock: Callable[[], float] = time.monotonic,
) -> None:
    if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
        raise ValueError("limit must be a non-negative integer")
    if (
        isinstance(burst_credits, bool)
        or not isinstance(burst_credits, int)
        or burst_credits < 0
    ):
        raise ValueError("burst_credits must be a non-negative integer")
    if not isinstance(window_seconds, (int, float)):
        raise ValueError("window_seconds must be numeric")
    window = float(window_seconds)
    if not math.isfinite(window) or window <= 0.0:
        raise ValueError("window_seconds must be finite and positive")
    if not callable(clock):
        raise TypeError("clock must be callable")

    self.limit = limit
    self.window_seconds = window
    self.burst_credits = burst_credits
    self._rate = limit / window
    self._clock = clock
    self._shards = tuple(_Shard() for _ in range(self._SHARD_COUNT))
    refill_horizon = burst_credits / self._rate if self._rate > 0.0 else 0.0
    self._idle_ttl = window + refill_horizon

def _read_time(self, now: float | None) -> float:
    value = self._clock() if now is None else now
    if not isinstance(value, (int, float)):
        raise ValueError("time must be numeric")
    value = float(value)
    if not math.isfinite(value):
        raise ValueError("time must be finite")
    return value

def _shard(self, key: str) -> _Shard:
    return self._shards[hash(key) % self._SHARD_COUNT]

def _reap_oldest_locked(self, shard: _Shard, now: float) -> None:
    """Opportunistically remove at most one expired LRU entry."""
    if not shard.states:
        return
    key, state = next(iter(shard.states.items()))
    if now - state.last_access < self._idle_ttl:
        return
    if not state.lock.acquire(blocking=False):
        return
    try:
        if (
            shard.states.get(key) is state
            and now - state.last_access >= self._idle_ttl
        ):
            del shard.states[key]
    finally:
        state.lock.release()

def _acquire_state(self, key: str, now: float, create: bool) -> _State | None:
    """Return a state with its lock held."""
    shard = self._shard(key)
    with shard.lock:
        self._reap_oldest_locked(shard, now)
        state = shard.states.get(key)
        if state is None:
            if not create:
                return None
            state = _State(
                credits=float(self.burst_credits),
                token_time=now,
                last_time=now,
                last_access=now,
            )
            shard.states[key] = state
        else:
            shard.states.move_to_end(key)
        state.lock.acquire()
        return state

def _cleanup(self, state: _State, now: float) -> None:
    cutoff = now - self.window_seconds
    events = state.events
    while events and events[0][0] <= cutoff:
        _, amount = events.popleft()
        state.usage -= amount

def _effective_credits(self, state: _State, now: float) -> float:
    if self._rate <= 0.0:
        return state.credits
    elapsed = max(0.0, now - state.token_time)
    return min(
        float(self.burst_credits),
        state.credits + elapsed * self._rate,
    )

def _remaining(self, usage: int, credits: float) -> int:
    normal = max(0, self.limit - usage)
    return max(0, int(math.floor(normal + credits)))

def _retry_after(
    self,
    state: _State,
    now: float,
    cost: int,
    credits_now: float,
) -> float:
    if cost > self.limit + self.burst_credits:
        return math.inf

    usage = state.usage
    events = list(state.events)
    elapsed = 0.0
    index = 0

    while True:
        normal = max(0, self.limit - usage)
        needed = max(0, cost - normal)
        tokens = min(
            float(self.burst_credits),
            credits_now + self._rate * elapsed,
        )

        if tokens >= needed:
            return max(0.0, elapsed)

        next_elapsed = math.inf
        if index < len(events):
            next_elapsed = max(
                elapsed,
                events[index][0] + self.window_seconds - now,
            )

        if self._rate > 0.0 and needed <= self.burst_credits:
            refill_elapsed = max(
                elapsed,
                (needed - credits_now) / self._rate,
            )
            if refill_elapsed <= next_elapsed:
                return max(0.0, refill_elapsed)

        if index >= len(events):
            return math.inf

        elapsed = next_elapsed
        boundary = events[index][0] + self.window_seconds
        while (
            index < len(events)
            and events[index][0] + self.window_seconds <= boundary
        ):
            usage -= events[index][1]
            index += 1

def allow(
    self,
    key: str,
    cost: int = 1,
    now: float | None = None,
) -> Decision:
    """Atomically admit or reject a request for key."""
    if not isinstance(key, str):
        raise TypeError("key must be a string")
    if isinstance(cost, bool) or not isinstance(cost, int) or cost <= 0:
        raise ValueError("cost must be a positive integer")

    supplied_time = self._read_time(now)
    state = self._acquire_state(key, supplied_time, create=True)
    assert state is not None
    try:
        effective_now = max(supplied_time, state.last_time)
        state.last_time = effective_now
        state.last_access = effective_now
        self._cleanup(state, effective_now)

        credits = self._effective_credits(state, effective_now)
        state.credits = credits
        state.token_time = effective_now

        normal_available = max(0, self.limit - state.usage)
        burst_needed = max(0, cost - normal_available)
        possible = cost <= self.limit + self.burst_credits

        if possible and credits >= burst_needed:
            state.credits = credits - burst_needed
            if state.events and state.events[-1][0] == effective_now:
                timestamp, previous = state.events[-1]
                state.events[-1] = (timestamp, previous + cost)
            else:
                state.events.append((effective_now, cost))
            state.usage += cost
            return Decision(
                allowed=True,
                remaining=self._remaining(state.usage, state.credits),
                retry_after=0.0,
                limit=self.limit,
            )

        retry = self._retry_after(state, effective_now, cost, credits)
        return Decision(
            allowed=False,
            remaining=self._remaining(state.usage, credits),
            retry_after=retry,
            limit=self.limit,
        )
    finally:
        state.lock.release()

def snapshot(self, key: str, now: float | None = None) -> Snapshot:
    """Return current usage without changing admission or refill state."""
    if not isinstance(key, str):
        raise TypeError("key must be a string")
    supplied_time = self._read_time(now)
    state = self._acquire_state(key, supplied_time, create=False)
    if state is None:
        return Snapshot(
            usage=0,
            remaining=self.limit + self.burst_credits,
            burst_credits=float(self.burst_credits),
            limit=self.limit,
            window_seconds=self.window_seconds,
        )

    try:
        effective_now = max(supplied_time, state.last_time)
        self._cleanup(state, effective_now)
        credits = self._effective_credits(state, effective_now)
        return Snapshot(
            usage=state.usage,
            remaining=self._remaining(state.usage, credits),
            burst_credits=credits,
            limit=self.limit,
            window_seconds=self.window_seconds,
        )
    finally:
        state.lock.release()

def reap(self, now: float | None = None) -> int:
    """Remove all entries beyond the idle retention period; return count."""
    current = self._read_time(now)
    removed = 0
    for shard in self._shards:
        with shard.lock:
            for key, state in list(shard.states.items()):
                if current - state.last_access < self._idle_ttl:
                    continue
                if not state.lock.acquire(blocking=False):
                    continue
                try:
                    if (
                        shard.states.get(key) is state
                        and current - state.last_access >= self._idle_ttl
                    ):
                        del shard.states[key]
                        removed += 1
                finally:
                    state.lock.release()
    return removed

class FakeClock:
def init(self, initial: float = 0.0) -> None:
self._value = initial
self._lock = threading.Lock()

def __call__(self) -> float:
    with self._lock:
        return self._value

def set(self, value: float) -> None:
    with self._lock:
        self._value = value

def advance(self, amount: float) -> None:
    with self._lock:
        self._value += amount

class RateLimiterTests(unittest.TestCase):
def test_exact_boundary_expiry(self) -> None:
clock = FakeClock()
limiter = RateLimiter(1, 1.0, clock=clock)
self.assertTrue(limiter.allow("a").allowed)
clock.set(0.999999)
decision = limiter.allow("a")
self.assertFalse(decision.allowed)
self.assertAlmostEqual(decision.retry_after, 0.000001, places=9)
clock.set(1.0)
self.assertTrue(limiter.allow("a").allowed)

def test_burst_refill(self) -> None:
    clock = FakeClock()
    limiter = RateLimiter(2, 2.0, burst_credits=2, clock=clock)
    self.assertTrue(limiter.allow("a", cost=4).allowed)
    clock.set(0.5)
    decision = limiter.allow("a")
    self.assertFalse(decision.allowed)
    self.assertAlmostEqual(decision.retry_after, 0.5)
    clock.set(1.0)
    self.assertTrue(limiter.allow("a").allowed)

def test_multi_cost_is_all_or_nothing(self) -> None:
    clock = FakeClock()
    limiter = RateLimiter(3, 10.0, burst_credits=1, clock=clock)
    self.assertTrue(limiter.allow("a", cost=2).allowed)
    rejected = limiter.allow("a", cost=3)
    self.assertFalse(rejected.allowed)
    self.assertTrue(limiter.allow("a", cost=2).allowed)
    self.assertEqual(limiter.snapshot("a").usage, 4)
    self.assertFalse(limiter.allow("b", cost=5).allowed)
    self.assertTrue(limiter.allow("b", cost=4).allowed)

def test_retry_after_multiple_expiries(self) -> None:
    clock = FakeClock()
    limiter = RateLimiter(2, 1.0, clock=clock)
    self.assertTrue(limiter.allow("a", now=0.0).allowed)
    self.assertTrue(limiter.allow("a", now=0.5).allowed)
    decision = limiter.allow("a", cost=2, now=0.5)
    self.assertFalse(decision.allowed)
    self.assertAlmostEqual(decision.retry_after, 1.0)
    self.assertTrue(limiter.allow("a", cost=2, now=1.5).allowed)

def test_idle_eviction(self) -> None:
    clock = FakeClock()
    limiter = RateLimiter(1, 1.0, clock=clock)
    self.assertTrue(limiter.allow("idle").allowed)
    clock.advance(1.01)
    self.assertEqual(limiter.reap(), 1)
    snapshot = limiter.snapshot("idle")
    self.assertEqual(snapshot.usage, 0)
    self.assertEqual(snapshot.remaining, 1)

def test_non_monotonic_and_repeated_timestamps(self) -> None:
    limiter = RateLimiter(2, 1.0, burst_credits=1, clock=FakeClock())
    self.assertTrue(limiter.allow("a", now=5.0).allowed)
    self.assertTrue(limiter.allow("a", now=4.0).allowed)
    self.assertTrue(limiter.allow("a", now=5.0).allowed)
    decision = limiter.allow("a", now=4.5)
    self.assertFalse(decision.allowed)
    self.assertAlmostEqual(decision.retry_after, 1.0)

def test_limit_zero_and_very_small_window(self) -> None:
    limiter = RateLimiter(0, 0.0001, burst_credits=2, clock=FakeClock())
    self.assertTrue(limiter.allow("a", cost=2, now=0.0).allowed)
    decision = limiter.allow("a", now=1.0)
    self.assertFalse(decision.allowed)
    self.assertTrue(math.isinf(decision.retry_after))

    tiny = RateLimiter(1, 0.000001, clock=FakeClock())
    self.assertTrue(tiny.allow("x", now=0.0).allowed)
    self.assertFalse(tiny.allow("x", now=0.0000009).allowed)
    self.assertTrue(tiny.allow("x", now=0.000001).allowed)

def test_snapshot_does_not_consume_refilled_credit(self) -> None:
    limiter = RateLimiter(1, 1.0, burst_credits=1, clock=FakeClock())
    self.assertTrue(limiter.allow("a", cost=2, now=0.0).allowed)
    view = limiter.snapshot("a", now=0.5)
    self.assertAlmostEqual(view.burst_credits, 0.5)
    self.assertTrue(limiter.allow("a", now=1.0).allowed)

def test_multithreaded_theoretical_maximum(self) -> None:
    clock = FakeClock(7.0)
    limiter = RateLimiter(10, 60.0, burst_credits=7, clock=clock)
    worker_count = 100
    barrier = threading.Barrier(worker_count)
    admitted: list[int] = []
    admitted_lock = threading.Lock()

    def worker() -> None:
        barrier.wait()
        result = limiter.allow("shared")
        if result.allowed:
            with admitted_lock:
                admitted.append(1)

    threads = [threading.Thread(target=worker) for _ in range(worker_count)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

    self.assertLessEqual(sum(admitted), 17)
    self.assertEqual(sum(admitted), 17)
    self.assertEqual(limiter.snapshot("shared").usage, 17)

def test_concurrent_first_touch(self) -> None:
    clock = FakeClock(1.0)
    limiter = RateLimiter(1, 10.0, clock=clock)
    barrier = threading.Barrier(20)
    results: list[bool] = []
    lock = threading.Lock()

    def worker() -> None:
        barrier.wait()
        allowed = limiter.allow("new-key").allowed
        with lock:
            results.append(allowed)

    threads = [threading.Thread(target=worker) for _ in range(20)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
    self.assertEqual(sum(results), 1)

if name == "main":
unittest.main()

Result

#1 | Winner

Winning Votes

3 / 3

Average Score

75

Total Score

97

Overall Comments

Answer B provides an exceptionally rigorous, production-grade implementation. It features a sophisticated two-tier locking design (shard locks for lookup/creation plus individual per-key locks for state modification) that completely eliminates whole-shard contention bottlenecks and safely handles concurrent first-touch without race conditions. Its retry_after logic is meticulously calculated, edge cases like sub-millisecond windows and zero limits are fully covered, and the test suite is comprehensive and deterministic, including an explicit barrier-synchronized concurrent first-touch test.

View Score Details

Correctness

Weight 35%
95

Flawless exact sliding window semantics, extremely precise retry_after calculation considering both window expiries and token refills, and robust handling of all edge cases.

Completeness

Weight 20%
100

Fully implements all requirements, edge cases, data structures, design notes, and an exemplary deterministic test suite covering concurrency, boundary conditions, and time regression.

Code Quality

Weight 20%
95

Exceptional code quality with meticulous attention to thread-safety, clean separation of concerns, robust type hints, and immutable return structures.

Practical Value

Weight 15%
95

Outstanding practical design utilizing fine-grained per-key locks guarded by shard lookup locks, ensuring minimal contention and robust bounded memory hygiene.

Instruction Following

Weight 10%
100

Strictly adheres to every single instruction, constraint, edge case, and requirement without exception.

Total Score

61

Overall Comments

Answer B provides clearer state modeling, counts every admitted cost in the sliding window, handles capped refill correctly in retry calculations, and includes useful observability and explicit maintenance APIs. Its deterministic concurrency tests are meaningful. Nevertheless, idle eviction incorrectly restores spent credits when limit is zero, two supplied tests contradict actual implementation behavior, and snapshot cleanup is unsafe when followed by older timestamps. It is a stronger starting point but still requires correctness fixes.

View Score Details

Correctness

Weight 35%
53

Records all admitted cost and correctly restricts refill-based retry candidates to attainable burst capacity. However, limit-zero entries are evicted after one window and receive fresh credits despite a zero refill rate. Future snapshot cleanup can also remove history without advancing last_time, allowing subsequent older calls to operate on prematurely expired state.

Completeness

Weight 20%
67

Includes all principal deliverables, a detailed snapshot, explicit reap method, and broad edge-case coverage. Coverage is weakened by failing zero-limit and timestamp tests, and the documented zero-limit reset policy does not satisfy the specified refill semantics.

Code Quality

Weight 20%
68

Well-structured dataclasses, explicit validation, coalesced equal-time records, and reliable lock release improve maintainability. However, acquiring a key lock while holding its shard lock creates head-of-line blocking, and test expectations are inconsistent with the documented behavior.

Practical Value

Weight 15%
56

A usage-bearing snapshot, explicit maintenance API, and fixed-clock admission-bound tests make integration and diagnosis easier. Deployment still requires fixing zero-limit credit resets and snapshot regressions. Full reap also scans and copies shard mappings while holding their locks, which deserves clearer operational guidance.

Instruction Following

Weight 10%
65

Follows the requested delivery format and supplies deterministic fake-clock tests with meaningful concurrency bounds. The suite nevertheless fails: the regression test expects one second where refill permits success after half a second, and the zero-limit test expects rejection after the implementation has evicted and reset the key.

Total Score

69

Overall Comments

Answer B implements an exact sliding window with equal-timestamp coalescing, a correctly capped continuous burst pool, a retry_after simulation that properly guards the refill path with needed <= burst_credits, two-level locking (shard lock for map/LRU, per-key lock for state) with non-blocking acquisition during reaping to avoid races on first touch and eviction, an opportunistic one-entry reap per call plus an explicit reap(), and defensive handling of clock regressions, non-finite inputs, sub-millisecond windows, and limit == 0. The concurrency tests are deterministic via a thread-safe FakeClock and assert exact theoretical maxima (17 of 100, 1 of 20). Weaknesses: two test assertions are wrong relative to the implementation (test_non_monotonic expects retry_after 1.0 where the correct refill-based value is 0.5; test_limit_zero expects a rejection at now=1.0 but the key is reaped after idle_ttl=window and recreated with fresh credits, a behavior the design note itself documents). The limit==0 eviction reset effectively allows burst credits to regenerate contrary to a zero refill rate, and the key lock is acquired while holding the shard lock, so a hot key can stall its shard. Snapshot returns a separate Snapshot type rather than Decision, which is acceptable.

View Score Details

Correctness

Weight 35%
65

Sliding-window expiry at the boundary, capped refill, all-or-nothing costs, and retry_after (guarded by needed <= burst_credits) are correct; concurrency tests assert exact maxima. Two test expectations are wrong (retry_after 1.0 vs correct 0.5; limit==0 key reaped after idle_ttl and recreated), and the limit==0 reset lets burst credits regenerate despite a zero refill rate, though this is documented.

Completeness

Weight 20%
75

Implementation, design note, and tests cover every required scenario plus extras: sub-millisecond window, concurrent first touch, snapshot non-mutation, non-monotonic timestamps, and an explicit reap() for deterministic maintenance. Snapshot exposes usage, remaining, and credits.

Code Quality

Weight 20%
70

Clean dataclass-based state, clear separation of shard vs key locks, correct lock ordering with non-blocking reaping, consistent helpers, no unused imports, and a thread-safe FakeClock. The retry simulation is dense, input validation is somewhat heavy, and acquiring the key lock under the shard lock can stall a shard on a hot key.

Practical Value

Weight 15%
65

Usable as-is for gateway throttling with accurate retry hints, bounded memory via LRU reaping plus reap(), and deterministic tests suitable for CI once two wrong assertions are fixed. The limit==0 credit reset after idle is a documented but real semantic caveat.

Instruction Following

Weight 10%
75

Follows the API shape, standard library only, no asyncio, design note under 300 words covering data structure, tradeoff, and locking, deterministic fake-clock tests including the multithreaded bound, and explicitly exercises every listed edge case.

Comparison Summary

Final rank order is determined by judge-wise rank aggregation (average rank + Borda tie-break). Average score is shown for reference.

Judges: 3

Winning Votes

0 / 3

Average Score

58
View this answer

Winning Votes

3 / 3

Average Score

75
View this answer

Judging Results

Why This Side Won

B wins on the heavily weighted correctness criterion: its core admission, refill cap, and retry_after logic are correct, whereas A has a genuine retry_after bug in the default burst_credits=0 configuration. Both suites contain two failing assertions, but A's failures stem from a spec-contradicting boundary comment and a cross-shard test flaw, while B's implementation behavior in those cases is defensible and documented. B also follows the deterministic fake-clock requirement for its multithreaded tests, covers more of the mandated edge cases explicitly (first-touch concurrency, sub-millisecond windows, snapshot non-mutation), and has a cleaner two-level locking design with a documented, bounded reaping policy. Weighted across all criteria B is clearly ahead.

Why This Side Won

Answer B wins because its admission accounting and capacity-aware retry calculation are substantially stronger, and its implementation, observability, validation, and deterministic concurrency coverage better satisfy the deliverables. These advantages outweigh its significant zero-limit eviction and timestamp-handling defects. Answer A additionally has fundamental retry errors, incomplete sliding-window accounting, and an eviction policy that can become permanently blocked.

Why This Side Won

Answer B wins because its concurrency design is vastly superior, using a two-tier locking mechanism (shard lock plus individual key lock) that prevents high contention and safely handles concurrent first-touch and eviction races. Answer B also demonstrates superior correctness on complex edge cases, precise retry-after calculations, and a more thorough test suite including explicit verification of concurrent first-touch.

X f L