KatInterview

Build a Per-User Throttle and an In-Memory Event Broadcaster

Data Structure DesignModel answer
MediumModel answerData Structure Designrate-limitingtoken-bucketpub-sub

Last updated

Write a thread-safe per-user token-bucket throttle and a small topic-based event broadcaster that stays correct under concurrency and survives failing listeners.

Implement two small, thread-safe components in Python. Explain your design and write the code.

Part 1: Per-user throttle

Create a class RateLimiter that caps how often each user may call a service, using the token bucket model.

  • Every user owns an independent bucket holding at most max_tokens tokens.
  • A user who has never been seen starts with a full bucket.
  • Tokens accumulate at refill_rate tokens per second, but never beyond max_tokens.
  • Each accepted request consumes exactly one token. If less than one token is available, the request is refused.
class RateLimiter:
    def __init__(self, max_tokens: int, refill_rate: float):
        ...

    def allow_request(self, user_id: str) -> bool:
        """True if the request is admitted, False if it is throttled."""
        ...

Example:

limiter = RateLimiter(max_tokens=1, refill_rate=0.5)  # one token, regained every 2 seconds
limiter.allow_request("user_1")  # True
limiter.allow_request("user_1")  # False

Part 2: Topic-based event broadcaster

Create a class PubSub where listeners register interest in a topic and publishers send messages to that topic.

class PubSub:
    def subscribe(self, topic: str, callback: callable):
        """Register callback to be invoked for every message published on topic."""
        ...

    def publish(self, topic: str, message: str):
        """Deliver message to every callback registered for topic."""
        ...

Requirements

  • Both classes must be safe to use from many threads at once.
  • RateLimiter must treat different users completely independently.
  • Decide and justify what happens when a subscriber's callback raises an exception, or is slow, or itself calls subscribe/publish.

What to cover in your answer

  1. The data you store per user and how tokens are refilled (without a background thread, if possible).
  2. Where locks are taken, and which clock you read.
  3. How publish avoids deadlocks and isolates bad subscribers.
  4. Complexity, edge cases, and how you would scale or extend each component.

Hints

Hint 1

You do not need a timer thread to refill buckets. Store (tokens, last_update_time) per user and compute the refill from elapsed time whenever a request arrives, capping at max_tokens.

Hint 2

The check-refill-consume sequence must be one atomic step, and the timestamp should be read after the lock is acquired using a clock that cannot go backwards (a monotonic clock).

Hint 3

In publish, copy the subscriber list while holding the lock, release it, and only then call the callbacks, each wrapped in its own try/except, so slow, failing or re-entrant callbacks cannot block or corrupt anything.