KatInterview

Shared Token Bucket with Optimistic Concurrency

Data Structure DesignAuto-graded · 23 test cases
MediumAuto-gradedData Structure Designdesignconcurrencysimulation

Last 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^6
  • 0.001 ≤ refill_rate_per_sec ≤ 10^6
  • 1 ≤ tokens ≤ capacity
  • 0 ≤ max_cas_retries ≤ 10
  • timestamp_ms is 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.