Shared Token Bucket with Optimistic Concurrency
Data Structure DesignAuto-graded · 23 test casesLast updated
Tests implementation of a token bucket rate limiter over a versioned key-value store, including lazy replenishment, clock skew tolerance, and CAS-based retry logic.
Problem
You are building a quota enforcement layer for a multi-node service. Every node shares access to a single key-value store that supports atomic versioned writes. Your job is to implement a token bucket rate limiter on top of that store.
Each tracked entity (identified by a string key) has a bucket that holds up to capacity tokens and refills at refill_rate_per_sec tokens per second. When a node wants to serve a request, it checks the bucket for that key, adds any tokens that have accrued since the last recorded timestamp, and tries to consume the required number of tokens — all using a read-modify-write cycle protected by optimistic concurrency.
Key-Value Store Interface
The store is provided for you. It supports two operations:
class KeyValueStore:
def get(self, key: str) -> tuple[dict | None, int]:
"""
Returns (value, version) for the given key.
If the key has never been written, returns (None, 0).
"""
def cas(self, key: str, expected_version: int, new_value: dict, ttl_seconds: int) -> bool:
"""
Writes new_value for key only if the stored version equals expected_version.
Returns True on success, False on version mismatch.
"""
Each successful cas call increments the stored version by 1.
What to Implement
Implement a simulation function that processes a sequence of operations on a single rate limiter backed by one shared in-memory store.
Operations arrive as two parallel lists:
operations: a list of strings, each either"DistributedRateLimiter"(or"init") or"allow_request".arguments: the corresponding argument list for each operation.
"DistributedRateLimiter" / "init" — constructs the limiter. Arguments: [capacity, refill_rate_per_sec], optionally followed by max_cas_retries (default 3) and ttl_seconds (default 3600). Records null in the output.
"allow_request" — attempts to consume tokens from a key's bucket. Arguments: [key, timestamp_ms], optionally followed by tokens (default 1). Records true if the tokens were successfully consumed, false otherwise.
Bucket Rules
Replenishment is computed lazily at request time, never in the background:
available = min(capacity, stored_tokens + elapsed_seconds × refill_rate_per_sec)
where elapsed_seconds = (timestamp_ms − last_updated_ms) / 1000.0.
Rejection without write: if available < tokens_requested, return false immediately — do not attempt a CAS write.
Uninitialised key: treat the bucket as completely full, stamped at the current request's timestamp.
Clock skew: if timestamp_ms < last_updated_ms, treat elapsed time as 0 (no refill, no rollback of the stored timestamp).
Concurrency retries: if cas returns False, re-read the latest state and retry. The loop runs at most max_cas_retries + 1 total attempts. If every attempt loses the CAS race, return false.
Constraints
1 ≤ capacity ≤ 10^60.001 ≤ refill_rate_per_sec ≤ 10^61 ≤ tokens ≤ capacity0 ≤ max_cas_retries ≤ 10timestamp_msis a non-negative 64-bit integer- The first operation is always an initialisation call
1 ≤ len(operations) ≤ 500
Examples
Example 1
Input: token_bucket_sim(['DistributedRateLimiter', 'allow_request', 'allow_request', 'allow_request'], [[5, 1], ['user_1', 0, 3], ['user_1', 1000, 4], ['user_1', 1000, 2]])
Output: [None, True, False, True]
Example 2
Input: token_bucket_sim(['DistributedRateLimiter', 'allow_request', 'allow_request', 'allow_request'], [[5, 1], ['user_1', 0, 3], ['user_1', 1000, 2], ['user_1', 800, 1]])
Output: [None, True, True, True]
Example 3
Input: token_bucket_sim(['DistributedRateLimiter', 'allow_request', 'allow_request', 'allow_request', 'allow_request'], [[2, 0.5, 0], ['a', 0, 1], ['a', 0, 1], ['a', 1000, 1], ['a', 3000, 1]])
Output: [None, True, True, False, True]
Hints
Hint 1
For an uninitialised key, the bucket starts full and last_updated_ms is set to the incoming timestamp — this also makes the first CAS act as an atomic 'create if absent'.
Hint 2
When timestamp_ms is earlier than the stored last_updated_ms, clamp elapsed time to zero and leave last_updated_ms unchanged in the new record; rolling it backward would cause a future request to over-count refill.
Hint 3
Track total attempts as max_cas_retries + 1: a rejected request (not enough tokens) exits the loop immediately without a CAS, while a failed CAS re-reads fresh state before the next attempt.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea: lazy read-modify-write with optimistic locking
No background thread refills any bucket. Instead, each allow_request call does a short read-modify-write cycle:
- Read the stored record
{tokens, last_updated_ms}and its version number viaget. - Replenish by computing how many tokens have accrued since the stored timestamp and clamping to
capacity. - Reject early — if the available balance is still below what was requested, return
falseimmediately without touching the store. - Write the new balance and timestamp via
cas. If the version has changed since the read (another node wrote first), restart from step 1.
Why this is correct
No double-spend. A write only succeeds when the version matches the one read in step 1. If two nodes race, exactly one wins; the other re-reads the winner's committed record before trying again. There is no window where both nodes spend from the same tokens.
Retries use fresh data. On a CAS failure the entire record is re-read. Reusing the stale available value from the previous iteration would be a classic bug — the new record may have fewer tokens and a later timestamp that shifts the replenishment calculation.
Retry budget. The loop runs max_cas_retries + 1 times total (a value of 0 means exactly one attempt). Exhausting the budget returns false, failing closed under heavy contention rather than spinning forever.
Clock skew tolerance. When timestamp_ms < last_updated_ms, elapsed time is clamped to zero: no negative refill is applied and the stored timestamp is left unchanged. Rolling the timestamp backward would cause the next in-order request to see an inflated elapsed time and over-count refill.
Monotonic store timestamps. Because last_updated_ms never decreases, total refill over any real-time interval is bounded by rate × actual elapsed time.
Fractional tokens. Balances are stored as floats so sub-second replenishment accumulates correctly across many calls.
First request for a key. get returns (None, 0); the bucket is treated as full, anchored at the current timestamp. cas with expected_version=0 acts as an atomic "create if absent". If two nodes race to create the same key, exactly one succeeds and the other retries against the real record.
Complexity
- Time per operation: O(R) where R =
max_cas_retries + 1≤ 11. Each attempt is onegetand at most onecas, both O(1) on the in-memory store. Over n operations the total is O(n · R) = O(n). - Space: O(K) in the store for K distinct keys, with a constant-size record per key. The TTL parameter allows idle entries to expire in a real deployment.
Edge cases
| Scenario | Behaviour |
|---|---|
| First-ever request for a key | Full bucket; CAS version 0 acts as creation |
| Request exactly equal to available tokens | Succeeds (available < requested is strict) |
| Rejected request | No write; last_updated_ms is not advanced (harmless: refill is re-computed from the same anchor next time) |
| Out-of-order timestamp | Stored tokens consumed as-is; stored timestamp unchanged |
| Long idle period | Refill clamped to capacity; no overflow |
max_cas_retries = 0 | Exactly one attempt; CAS failure → false |
Reference solution
from typing import List, Optional
class _InMemoryStore:
"""Versioned in-memory key-value store with CAS semantics."""
def __init__(self):
self._data = {}
def get(self, key: str):
entry = self._data.get(key)
if entry is None:
return None, 0
return entry["value"], entry["version"]
def cas(self, key: str, expected_version: int, new_value: dict, ttl_seconds: int) -> bool:
entry = self._data.get(key)
actual_version = 0 if entry is None else entry["version"]
if actual_version != expected_version:
return False
self._data[key] = {"value": new_value, "version": expected_version + 1}
return True
def token_bucket_sim(operations: List[str], arguments: List[List]) -> List[Optional[bool]]:
store = _InMemoryStore()
limiter = None
results: List[Optional[bool]] = []
for operation, args in zip(operations, arguments):
# ── Initialisation ────────────────────────────────────────────────
if operation in ("DistributedRateLimiter", "init"):
limiter = {
"capacity": args[0],
"rate": args[1],
"max_retries": args[2] if len(args) > 2 else 3,
"ttl": args[3] if len(args) > 3 else 3600,
}
results.append(None)
continue
if operation != "allow_request":
raise ValueError(f"Unknown operation: {operation!r}")
if limiter is None:
raise ValueError("Limiter must be initialised before allow_request")
# ── allow_request ─────────────────────────────────────────────────
key = args[0]
timestamp_ms = args[1]
requested = args[2] if len(args) > 2 else 1
capacity = limiter["capacity"]
rate = limiter["rate"]
allowed = False
for _ in range(limiter["max_retries"] + 1):
# Step 1: read current state and version
current, version = store.get(key)
if current is None:
# Uninitialised key: full bucket, timestamp anchored to now
current_tokens = float(capacity)
last_updated_ms = timestamp_ms
else:
current_tokens = current["tokens"]
last_updated_ms = current["last_updated_ms"]
# Step 2: replenish (or handle clock skew)
if timestamp_ms >= last_updated_ms:
elapsed_sec = (timestamp_ms - last_updated_ms) / 1000.0
available = min(capacity, current_tokens + elapsed_sec * rate)
new_last_updated = timestamp_ms
else:
# Out-of-order timestamp: no refill, keep stored timestamp
available = current_tokens
new_last_updated = last_updated_ms
# Step 3: reject without writing if tokens are insufficient
if available < requested:
break
# Step 4: attempt atomic write
new_value = {
"tokens": available - requested,
"last_updated_ms": new_last_updated,
}
if store.cas(key, version, new_value, limiter["ttl"]):
allowed = True
break
# CAS failed: another writer updated the key; re-read and retry
results.append(allowed)
return results