Build a Per-User Throttle and an In-Memory Event Broadcaster
Data Structure DesignModel answerLast 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_tokenstokens. - A user who has never been seen starts with a full bucket.
- Tokens accumulate at
refill_ratetokens per second, but never beyondmax_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.
RateLimitermust 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
- The data you store per user and how tokens are refilled (without a background thread, if possible).
- Where locks are taken, and which clock you read.
- How
publishavoids deadlocks and isolates bad subscribers. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
Throttle: use lazy token refill. Per user store (tokens, last_timestamp). On each request, add (now - last) * refill_rate tokens, cap at max_tokens, then consume one if at least one is available. No background thread is needed because the token count is only observable when a request arrives, so computing it lazily gives the same answer as continuous refilling.
Broadcaster: keep topic -> list[callback] behind a lock. On publish, snapshot the list under the lock, then call the callbacks outside the lock, each isolated by try/except, using a thread pool so publish returns quickly.
Why the throttle is correct
- Refill math. Tokens grow linearly with elapsed time and are clamped to capacity. That is the definition of a token bucket.
- First request. An unknown user gets a full bucket, so the example yields
TruethenFalse. After 2 seconds at rate 0.5, one token has returned and the next call succeeds. - Atomicity. If two threads both read
tokens = 1without a lock, both would be admitted and both would write0, over-admitting. Holding a lock around read, refill, decide and write makes it one indivisible step. - Timestamp inside the lock. If the time is read before acquiring the lock, a thread with an older timestamp can win the lock later and see negative elapsed time, losing tokens. Read the clock after acquiring.
- Monotonic clock.
time.time()can jump backwards (NTP, manual changes).time.monotonic()cannot. - Independence. Each user has their own entry, so one user's burst never drains another's tokens.
Why the broadcaster is correct
- Snapshot under lock. Copying the list gives each publish a consistent view. A subscription added mid-dispatch affects only later publishes, and no one iterates a list that is being mutated.
- Dispatch outside the lock. If callbacks ran while holding the lock, a callback that calls
subscribeorpublishcould deadlock (with a plainLock), and a slow callback would block every other publisher and subscriber. - Per-callback try/except. One crashing subscriber is logged and the rest still receive the message. Silent swallowing is a mistake; always log with the topic and callback.
- Thread pool.
publishreturns after submitting work, so publishers are not coupled to subscriber latency.
Complexity
allow_request: O(1) time, O(U) space for U users.subscribe: O(1) amortized.publish: O(k) to snapshot and submit k subscribers; callbacks run asynchronously. Space O(total subscriptions).
Code
import logging
import threading
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, Dict, List, Tuple
logger = logging.getLogger(__name__)
class RateLimiter:
def __init__(self, max_tokens: int, refill_rate: float):
if max_tokens <= 0:
raise ValueError("max_tokens must be positive")
if refill_rate < 0:
raise ValueError("refill_rate must be non-negative")
self.max_tokens = float(max_tokens)
self.refill_rate = float(refill_rate)
self._buckets: Dict[str, Tuple[float, float]] = {}
self._lock = threading.Lock()
def allow_request(self, user_id: str) -> bool:
with self._lock:
now = time.monotonic()
bucket = self._buckets.get(user_id)
if bucket is None:
tokens = self.max_tokens
else:
tokens, last = bucket
tokens = min(self.max_tokens,
tokens + (now - last) * self.refill_rate)
if tokens >= 1.0:
self._buckets[user_id] = (tokens - 1.0, now)
return True
self._buckets[user_id] = (tokens, now)
return False
class PubSub:
def __init__(self, max_workers: int = 8):
self._subs: Dict[str, List[Callable[[str], None]]] = defaultdict(list)
self._lock = threading.RLock()
self._pool = ThreadPoolExecutor(max_workers=max_workers,
thread_name_prefix="pubsub")
def subscribe(self, topic: str, callback: Callable[[str], None]):
if not callable(callback):
raise TypeError("callback must be callable")
with self._lock:
self._subs[topic].append(callback)
def unsubscribe(self, topic: str, callback) -> bool:
with self._lock:
cbs = self._subs.get(topic)
if cbs and callback in cbs:
cbs.remove(callback)
if not cbs:
del self._subs[topic]
return True
return False
def publish(self, topic: str, message: str):
with self._lock:
callbacks = list(self._subs.get(topic, ()))
for cb in callbacks:
self._pool.submit(self._deliver, topic, cb, message)
@staticmethod
def _deliver(topic, cb, message):
try:
cb(message)
except Exception:
logger.exception("Subscriber %r failed on topic %r", cb, topic)
def shutdown(self, wait: bool = True):
self._pool.shutdown(wait=wait)
Edge cases
refill_rate = 0:max_tokensbecomes a lifetime quota; valid.- Invalid config:
max_tokens <= 0or negative rate raisesValueError. - Long idle time: the cap prevents unbounded bursts.
- Memory growth: a bucket idle longer than
max_tokens / refill_rateequals a fresh one and can be evicted. - No subscribers: publishing is a no-op. Use
.getrather than indexing adefaultdicton the read path so empty topics are not created. - Non-callable subscriber: reject at subscribe time, not at publish time.
- Ordering: a shared pool does not guarantee per-subscriber order. State this trade-off.
Trade-offs and extensions
- Lock granularity. A single global lock is fine for a screen. Under contention, use lock striping (
hash(user_id) % Nlocks) or per-bucket locks. RLockvsLock. Since callbacks run outside the lock on worker threads, a plainLockwould also work.RLockis a safety net for reentrant calls from the calling thread.- Ordering per subscriber. Give each subscriber its own queue and a single consumer thread (or a per-subscriber serial executor). This preserves order and isolates slow consumers, at the cost of more threads and memory. Bound the queues and choose a policy (drop, block, or disconnect) for slow consumers.
- Distributed throttle. Keep the bucket in Redis and do refill-and-consume atomically in a Lua script, using the server clock to avoid skew between app servers. Set a TTL on keys so idle users expire.
- Delivery guarantees. This broadcaster is at-most-once and in-memory. Durability, retries and replay require a broker (Kafka, SQS) and are a different design.
Common mistakes
- Using a background thread to refill every bucket (wasteful, racy).
- Reading the clock before taking the lock, or using wall-clock time.
- Calling callbacks while holding the lock.
- Letting one exception abort delivery to remaining subscribers.
- Mutating the subscriber list while iterating it.
- Forgetting to cap tokens at
max_tokens.