Batched Event-Loop Key-Value Client

Hard · System Design · Software Engineer · Technical Screen

Prompt

A remote storage service exposes a bulk lookup route GET /read?keys=k1,k2,... whose response body is a JSON map from string keys to numeric values (for example, {"sku_7": 250, "sku_9": 40}). Your runtime runs on a single-threaded event loop and supplies two helper primitives:

  • httpGetAsync(urlPath, callback) -> void to issue non-blocking HTTP requests.
  • parseKvs(json) to decode a JSON payload into a key-to-value map.

Design an in-process client exposing getKeyAsync(key, callback) that coalesces individual lookups into bulk network reads while supporting concurrent non-blocking I/O. Your design must enforce four core invariants:

  1. 100 ms batching window: Coalesce lookups arriving within a 100 ms window into one outbound GET /read?keys=... request.
  2. Intra-batch deduplication: Include each unique key only once per outbound query string, while still firing every caller's callback exactly once.
  3. Dispatch-time consistency: An HTTP reply from a batch may only resolve getKeyAsync calls that were registered prior to that batch being sent; any lookup arriving after dispatch—even for an identical key—must wait for a later batch.
  4. Concurrent in-flight isolation: Allow several dispatched batches to remain on the wire simultaneously and return out of order without cross-wiring callbacks or results.

Scope & Expectations

  • Specify the in-memory data structures, batch state transitions, timer scheduling, and mechanism for binding each HTTP reply back to its waiting callers.
  • Define clear contracts and recovery behavior for omitted keys, malformed or failed responses, request timeouts and retries, caller cancellation, and memory/concurrency backpressure.
  • Analyze time and space complexity per operation and call out subtle execution-ordering traps specific to single-threaded event loops.
  • Outline a fast, deterministic test strategy that validates batching, deduplication, failure paths, and the dispatch-time consistency rule.

Step-by-step walkthrough

  1. Clarify requirements and interface contracts

    Unlike a multi-server architecture question, this is an in-process component design running on a single-threaded event loop—a concurrency model (like Node.js or Python asyncio) where one thread runs one small callback at a time from an event queue while the operating system performs network I/O in the background. Because only one thread touches our data structures, we never need mutex locks, yet we must be very careful about interleaving (timers, HTTP responses, cancellations, and user callbacks firing in arbitrary order).

    What getKeyAsync(key, callback) must guarantee

    • 100 ms request coalescing: combine getKeyAsync lookups submitted inside a 100 ms collection window into a single outbound GET /read?keys=k1,k2,... call.
    • Per-batch key deduplication: if five callers request "sku_7" inside the same open batch, "sku_7" appears once in the query string, and all five callbacks each fire exactly once.
    • Read-after-arrival consistency: a batch's HTTP reply can resolve only lookups registered prior to that batch leaving the process. Why does this rule matter so much? Trace what goes wrong if a late caller piggybacks on an already-dispatched batch:
    t = 100 ms : Batch 1 dispatches GET /read?keys=sku_7
    t = 104 ms : Backend reads sku_7 = 250 from storage and starts sending the HTTP response
    t = 107 ms : Another service updates sku_7 = 310 on the backend, then calls getKeyAsync("sku_7", cb_late)
    t = 120 ms : Batch 1's response {"sku_7": 250} arrives!
    

    If cb_late joined Batch 1 while it was in flight, cb_late would receive 250—a stale value read before cb_late was even called! Sealing Batch 1 at t = 100 ms forces cb_late into Batch 2 (dispatched at t = 207 ms), which reads the fresh value 310.

    • Concurrent in-flight batches without cross-talk: if Batch 1 takes 180 ms and Batch 2 takes 30 ms, both can be on the network simultaneously and finish out of order without ever mixing responses.

    Explicit assumptions about the primitives

    • httpGetAsync(url_path, callback) invokes callback(error, raw_json) once on the event loop (error is None on HTTP 2xx; otherwise an error object carrying optional .status for HTTP status codes, or None on socket failures). It provides no socket-abort handle.
    • parseKvs(raw_json) returns dict[str, float | int] and raises an exception on malformed JSON.
    • A key omitted from a valid 200 OK JSON dictionary means the key does not exist on the server.
    • The event loop provides call_soon(fn, *args) (run on a future turn of the loop) and call_later(delay_seconds, fn, *args) returning a timer handle with .cancel().
    • When the 100 ms timer starts: when the first request opens a new batch. A fixed 100 ms repeating tick wakes an idle CPU 10 times a second for nothing, while a debounce timer (resetting the 100 ms clock on every arrival) can starve requests forever under continuous traffic. Starting on the first arrival bounds batching delay to at most 100 ms.
    • URL encoding: each key is percent-encoded (urllib.parse.quote(key, safe="")) so a key containing ,, &, or # becomes %2C, %26, or %23 and cannot corrupt /read?keys=....
  2. Back-of-the-envelope numbers and safety caps

    Even inside a single process, back-of-the-envelope math exposes two hidden failure modes—oversized URLs and unbounded memory when the backend slows down:

    1. Traffic & URL length per 100 ms window
       Incoming call rate:         5,000 calls/s -> 500 requests per 100 ms window
       Key repetition (~50%):      ~250 distinct keys per 100 ms window
       Encoded key size (~20 B):   250 * 21 B (key + comma) = ~5.25 KB URL
       HTTP URL limit:             Nginx, Envoy, and load balancers reject request lines > ~8 KB!
       -> Safety cap 1:            max_keys = 200 and max_url_len = 8000 bytes (seal batch early when full!)
    
    2. In-flight concurrency via Little's Law (Concurrency = Throughput * Latency)
       Batch dispatch rate:        ~15-25 batches/s (down from 5,000 HTTP calls/s -> ~250x reduction!)
       Healthy p50 (30 ms):        20/s * 0.03 s = ~0.6 batches in flight on average
       Healthy p99 (200 ms):       20/s * 0.20 s = ~4 batches in flight
       Backend brownout (2 s):     20/s * 2.00 s = ~40 batches piling up simultaneously!
       -> Safety cap 2:            max_in_flight = 4 concurrent HTTP calls (protects struggling backend)
       -> Safety cap 3:            max_pending = 10,000 waiting requests (~4 MB RAM cap; protects our process)
    

    Without max_url_len, a traffic spike produces a 30 KB query string that fails every batch with 414 URI Too Long. Without max_in_flight and max_pending, a slow backend causes hundreds of concurrent sockets and out-of-memory crashes.

  3. API, error types, and callback invariants

    Let's define a crisp error-first contract for getKeyAsync(key, callback) and cancel(ticket):

    ticket = fetcher.getKeyAsync(key, callback)
      - Returns a Request handle (`ticket`) that the caller can pass to fetcher.cancel(ticket).
      - Invokes callback(error, value) EXACTLY ONCE, ALWAYS asynchronously on a later event-loop turn:
          (None, 42)               -> key found with numeric value 42
          (KeyNotFound(key), None) -> server responded 2xx, key absent (not retried)
          (FetchFailed(msg), None) -> non-retryable HTTP error, invalid key, or retries exhausted
          (Cancelled(key), None)   -> caller cancelled via fetcher.cancel(ticket)
          (Overloaded(msg), None)  -> pending requests >= max_pending (fail-fast backpressure)
    
    fetcher.cancel(ticket) -> bool
      - Returns True if this call cancelled a still-pending request (scheduling Cancelled callback),
        or False if the request had already completed or been cancelled.
    

    Why enforce always-asynchronous callbacks (loop.call_soon) even when rejecting an empty key or an Overloaded call immediately? If callback sometimes runs inside getKeyAsync before getKeyAsync returns and sometimes runs 100 ms later, caller code suffers from unpredictable execution order (often called "releasing Zalgo" in event-loop systems)—for example, trying to read the ticket variable inside callback before ticket = fetcher.getKeyAsync(...) has even assigned ticket!

    # Distinct error classes so callers can distinguish missing keys from transport failures
    class KeyNotFound(Exception):
        """Server returned 2xx, but the requested key was absent from the JSON map."""
    
    
    class FetchFailed(Exception):
        """Batch failed permanently (4xx validation error or all retry attempts exhausted)."""
    
    
    class BatchTimeout(Exception):
        """Single HTTP attempt exceeded timeout_ms without receiving a response."""
    
    
    class Cancelled(Exception):
        """Caller cancelled the request via fetcher.cancel(ticket)."""
    
    
    class Overloaded(Exception):
        """Fetcher reached max_pending waiting requests and shed load fast."""
    
  4. Data structures and batch state machine

    The single most important structural rule is never use a global key -> [callbacks] dictionary. If Batch 1 (currently IN_FLIGHT over the network) and Batch 2 (currently OPEN collecting new arrivals) both ask for "sku_7", a global dictionary would let Batch 1's response wake up Batch 2's callbacks—violating consistency! Instead, every Batch owns its own isolated waiters map.

    Batch lifecycle state machine:
    
      [OPEN] ---(100 ms timer fires OR next key hits max_keys / max_url_len)---> [READY]
        |                                                                           |
        | (all waiters cancelled while OPEN -> cancel timer -> [DONE])              | (in_flight < max_in_flight)
        v                                                                           v
      [DONE] <------------------(2xx response parsed)------------------------- [IN_FLIGHT]
        ^                                                                           |
        +---(4xx error, or retries exhausted)---+---(5xx / 429 / timeout)---> [BACKOFF]
                                                                                    |
                                                (jittered delay timer fires) -------+-> back to [READY]
    

    Inside each Batch, how should waiters store callbacks so that key deduplication, arrival-order delivery, and single-request cancellation are all O(1)? Use a two-level dictionary waiters: dict[str, dict[int, Request]] mapping each distinct key to an insertion-ordered dictionary of {request_id: Request}:

    from collections import deque
    
    
    class Request:
        """Represents one caller's getKeyAsync(key, callback) invocation."""
    
        def __init__(self, request_id: int, key: str, callback):
            self.id = request_id
            self.key = key
            self.callback = callback
            self.batch = None       # Batch instance that owns this request
            self.done = False       # Guards the "invoke callback at most once" invariant
    
    
    class Batch:
        """A sealed-together group of requests sharing one consistency boundary."""
    
        def __init__(self, batch_id: int, prefix_len: int):
            self.id = batch_id
            # waiters maps distinct_key -> {request_id: Request} in arrival order
            self.waiters: dict[str, dict[int, Request]] = {}
            self.url_len = prefix_len
            self.state = "OPEN"     # OPEN -> READY -> IN_FLIGHT -> (BACKOFF -> READY) -> DONE
            self.attempt = 0        # Increments on every HTTP dispatch to ignore stale timeouts/replies
            self.window_timer = None
            self.timeout_timer = None
    
    
    class BatchingFetcher:
        """Single-threaded event-loop key-value batcher with strict consistency."""
    
        PATH_PREFIX = "/read?keys="
    
        def __init__(
            self,
            loop,
            httpGetAsync,
            parseKvs,
            window_ms: int = 100,
            max_keys: int = 200,
            max_url_len: int = 8000,
            max_in_flight: int = 4,
            max_pending: int = 10000,
            timeout_ms: int = 2000,
            max_retries: int = 2,
            backoff_ms: int = 100,
        ):
            self.loop = loop
            self.httpGetAsync = httpGetAsync
            self.parseKvs = parseKvs
            self.window_ms = window_ms
            self.max_keys = max_keys
            self.max_url_len = max_url_len
            self.max_in_flight = max_in_flight
            self.max_pending = max_pending
            self.timeout_ms = timeout_ms
            self.max_retries = max_retries
            self.backoff_ms = backoff_ms
    
            # _open is the ONLY batch that newly arriving requests are allowed to join
            self._open: Batch | None = None
            # _ready holds sealed batches waiting for a free in-flight concurrency slot (FIFO)
            self._ready: deque[Batch] = deque()
            # _in_flight tracks batches currently awaiting an HTTP response: {batch_id: Batch}
            self._in_flight: dict[int, Batch] = {}
            self._pending_count = 0
            self._next_req_id = 0
            self._next_batch_id = 0
    
  5. Control flow and the 100 ms batching window

    Let's trace the end-to-end control flow across the caller, the single-threaded fetcher, and the backend before writing the windowing code:

      Caller                        BatchingFetcher (Event Loop)                     Backend
        |                                        |                                      |
        |-- getKeyAsync("sku_7", cb1) ---------->| Opens Batch 1, starts 100 ms timer   |
        |-- getKeyAsync("sku_7", cb2) ---------->| Dedups "sku_7" in Batch 1 (2 waiters)|
        |                                        |                                      |
        |                     [t = 100 ms: window timer seals Batch 1]                  |
        |                     [self._open = None; Batch 1 -> IN_FLIGHT]                 |
        |                                        |-- GET /read?keys=sku_7 (attempt 1) ->|
        |                                        |                                      |
        |-- getKeyAsync("sku_7", cb3) ---------->| self._open is None! Opens Batch 2    |
        |                                        | (starts new 100 ms timer at t=210ms) |
        |                                        |                                      |
        |                                        |<-- 200 OK {"sku_7": 250} (Batch 1) --|
        |<-- call_soon: cb1(None, 250) ----------| Batch 1 resolves ONLY cb1 & cb2;     |
        |<-- call_soon: cb2(None, 250) ----------| cb3 stays safely inside Batch 2!     |
    

    When getKeyAsync runs, it validates capacity and key size, checks whether adding a new distinct key would overflow the currently open batch's max_keys or max_url_len (sealing early if so), and attaches the request to self._open:

    from urllib.parse import quote
    
    
    def encode_key(key: str) -> str:
        # Percent-encode every reserved character (including ',' and '&')
        return quote(key, safe="")
    
    
    # Methods on BatchingFetcher (Step 1 of implementation: windowing & sealing)
    class BatchingFetcherWindowMixin:
        def getKeyAsync(self, key: str, callback):
            req = Request(self._next_req_id, key, callback)
            self._next_req_id += 1
    
            # 1. Fail fast if memory backpressure cap is reached
            if self._pending_count >= self.max_pending:
                self._reject_request(req, Overloaded("max_pending limit reached"))
                return req
    
            # 2. Reject empty keys or single keys too large to ever fit in one URL
            encoded = encode_key(key)
            if not key or len(self.PATH_PREFIX) + len(encoded) > self.max_url_len:
                self._reject_request(req, FetchFailed("invalid or oversized key"))
                return req
    
            # 3. Join the currently open batch (or open a fresh one if sealed/full)
            self._pending_count += 1
            batch = self._open_batch_for(key, encoded)
            key_waiters = batch.waiters.get(key)
            if key_waiters is None:
                # First waiter for this key in this batch: account for ',' separator if not first key
                comma_bytes = 1 if batch.waiters else 0
                batch.url_len += comma_bytes + len(encoded)
                key_waiters = {}
                batch.waiters[key] = key_waiters
    
            key_waiters[req.id] = req
            req.batch = batch
            return req
    
        def _open_batch_for(self, key: str, encoded: str) -> Batch:
            batch = self._open
            # Repeated keys add 0 bytes to the URL, so only brand-new keys can overflow caps
            if batch is not None and key not in batch.waiters:
                comma_bytes = 1 if batch.waiters else 0
                would_exceed_keys = len(batch.waiters) >= self.max_keys
                would_exceed_url = batch.url_len + comma_bytes + len(encoded) > self.max_url_len
                if would_exceed_keys or would_exceed_url:
                    self._seal_batch(batch)
                    batch = None
    
            if batch is None:
                batch = Batch(self._next_batch_id, len(self.PATH_PREFIX))
                self._next_batch_id += 1
                batch.window_timer = self.loop.call_later(
                    self.window_ms / 1000.0,
                    self._on_window_expired,
                    batch,
                )
                self._open = batch
            return batch
    
        def _on_window_expired(self, batch: Batch) -> None:
            # Guard state in case the batch was already sealed early by max_keys/max_url_len
            if batch.state == "OPEN":
                self._seal_batch(batch)
    
        def _seal_batch(self, batch: Batch) -> None:
            batch.window_timer.cancel()
            batch.state = "READY"
            # Detaching self._open BEFORE dispatch guarantees no future request can ever join this batch
            if self._open is batch:
                self._open = None
            self._ready.append(batch)
            self._pump_ready_queue()
    

    Notice why the consistency invariant holds unconditionally: a Request only ever enters self._open, and _seal_batch sets self._open = None before _pump_ready_queue() dispatches the HTTP call. Even if _ready waits behind max_in_flight or retries later, every waiter inside that batch arrived strictly prior to dispatch.

  6. Deep dive 1: Dispatching batches and correlating responses

    How do we correlate an incoming HTTP response to the exact waiting callbacks when four batches are in flight at once and two of them both contain "sku_7"? Correlate via lexical closure over (batch, attempt), never by looking up keys globally. When _dispatch_batch calls httpGetAsync(url_path, on_http_done), the inner function on_http_done captures that specific Batch object and integer attempt number.

    # Methods on BatchingFetcher (Step 2 of implementation: dispatch & response correlation)
    class BatchingFetcherDispatchMixin:
        def _pump_ready_queue(self) -> None:
            # Dispatch sealed batches in FIFO order while concurrency slots are free
            while self._ready and len(self._in_flight) < self.max_in_flight:
                batch = self._ready.popleft()
                if not batch.waiters:
                    # Every request in this batch was cancelled while waiting in _ready
                    batch.state = "DONE"
                    continue
                self._dispatch_batch(batch)
    
        def _dispatch_batch(self, batch: Batch) -> None:
            batch.state = "IN_FLIGHT"
            batch.attempt += 1
            current_attempt = batch.attempt
            self._in_flight[batch.id] = batch
    
            encoded_keys = [encode_key(k) for k in batch.waiters]
            url_path = self.PATH_PREFIX + ",".join(encoded_keys)
    
            # Start per-attempt timeout timer
            batch.timeout_timer = self.loop.call_later(
                self.timeout_ms / 1000.0,
                self._on_attempt_timeout,
                batch,
                current_attempt,
            )
    
            # Closure binds this exact (batch, current_attempt) pair—batches can never mix!
            def on_http_done(error, raw_json):
                self._on_http_response(batch, current_attempt, error, raw_json)
    
            self.httpGetAsync(url_path, on_http_done)
    
        def _on_http_response(self, batch: Batch, attempt: int, error, raw_json) -> None:
            # Ignore late responses from an earlier timed-out attempt
            if batch.state != "IN_FLIGHT" or batch.attempt != attempt:
                return
            batch.timeout_timer.cancel()
    
            parsed_kvs = None
            if error is None:
                try:
                    parsed_kvs = self.parseKvs(raw_json)
                except Exception as parse_err:
                    error = parse_err
    
            if error is not None:
                self._retry_or_fail_batch(batch, error)
                return
    
            # Success: mark batch DONE and detach waiters BEFORE scheduling user callbacks
            del self._in_flight[batch.id]
            batch.state = "DONE"
            waiters_snapshot = batch.waiters
            batch.waiters = {}
    
            for key, key_waiters in waiters_snapshot.items():
                key_present = key in parsed_kvs
                val = parsed_kvs[key] if key_present else None
                for req in key_waiters.values():
                    if key_present:
                        self._complete_request(req, None, val)
                    else:
                        self._complete_request(req, KeyNotFound(key), None)
    
            # Freeing an in-flight slot lets the next READY batch launch immediately
            self._pump_ready_queue()
    
        def _complete_request(self, req: Request, error, value) -> None:
            if req.done:
                return
            req.done = True
            self._pending_count -= 1
            self.loop.call_soon(self._invoke_safe, req.callback, error, value)
    
        def _reject_request(self, req: Request, error) -> None:
            req.done = True
            self.loop.call_soon(self._invoke_safe, req.callback, error, None)
    
        @staticmethod
        def _invoke_safe(callback, error, value) -> None:
            try:
                callback(error, value)
            except Exception:
                # Log uncaught user callback error; never crash the event loop or sibling callbacks
                pass
    

    Three cooperating guards enforce exactly-once callback execution: 1. batch.attempt != attempt silently drops any late HTTP response arriving after its timeout already triggered a retry. 2. req.done ensures cancellation and completion can never both schedule req.callback. 3. loop.call_soon runs each user callback in its own isolated turn after batch.waiters has been emptied, so a callback that calls cancel() or getKeyAsync() cannot mutate a dictionary mid-iteration.

  7. Deep dive 2: Missing keys, partial failures, timeouts, and retries

    Because GET /read?keys=... is a read-only idempotent operation (executing it multiple times has no side effects on server state), transient transport failures are safe to retry:

    Outcome from backend Action taken by BatchingFetcher
    HTTP 2xx, key in JSON Deliver (None, value) to all waiters for that key in arrival order.
    HTTP 2xx, key omitted Deliver (KeyNotFound(key), None) immediately; do not retry (server answered authoritatively).
    HTTP 2xx, extra unrequested key Ignore extra keys; iterate batch.waiters, never parsed_kvs.
    Timeout, socket error, malformed JSON, 429, or 5xx Retry whole batch up to max_retries using exponential backoff with jitter.
    Client HTTP error (400, 401, 403) Permanent bug/auth error; fail all remaining waiters immediately with FetchFailed.
    414 URI Too Long (proxy limit tighter than max_url_len) Optional hardening: split batch.waiters into two smaller READY batches (still preserves consistency because all waiters predate both sub-dispatches!).
    import random
    
    
    def is_transient_error(error) -> bool:
        status = getattr(error, "status", None)
        if status is None:
            # Network disconnect, BatchTimeout, or truncated/corrupt JSON body
            return True
        return status == 429 or status >= 500
    
    
    # Methods on BatchingFetcher (Step 3 of implementation: timeouts & backoff retries)
    class BatchingFetcherRetryMixin:
        def _on_attempt_timeout(self, batch: Batch, attempt: int) -> None:
            if batch.state != "IN_FLIGHT" or batch.attempt != attempt:
                return
            self._retry_or_fail_batch(
                batch,
                BatchTimeout(f"HTTP attempt {attempt} timed out after {self.timeout_ms} ms"),
            )
    
        def _retry_or_fail_batch(self, batch: Batch, error) -> None:
            # Release the in-flight slot immediately so healthy batches are not blocked during sleep
            del self._in_flight[batch.id]
    
            can_retry = (
                batch.attempt <= self.max_retries
                and is_transient_error(error)
                and bool(batch.waiters)
            )
            if can_retry:
                batch.state = "BACKOFF"
                # Exponential backoff (100 ms, 200 ms, ...) * uniform jitter [0.5, 1.0] avoids thundering herds
                base_delay = self.backoff_ms * (2 ** (batch.attempt - 1))
                jittered_ms = base_delay * random.uniform(0.5, 1.0)
                self.loop.call_later(jittered_ms / 1000.0, self._requeue_after_backoff, batch)
            else:
                batch.state = "DONE"
                waiters_snapshot = batch.waiters
                batch.waiters = {}
                failure = FetchFailed(str(error))
                for key_waiters in waiters_snapshot.values():
                    for req in key_waiters.values():
                        self._complete_request(req, failure, None)
    
            self._pump_ready_queue()
    
        def _requeue_after_backoff(self, batch: Batch) -> None:
            if not batch.waiters:
                batch.state = "DONE"
                return
            batch.state = "READY"
            # Push to the LEFT (front) of _ready so older retried batches go ahead of newer ones
            self._ready.appendleft(batch)
            self._pump_ready_queue()
    
  8. Deep dive 3: Cancellation and backpressure

    Cancellation across every batch state. What happens when a caller runs fetcher.cancel(ticket)? - If ticket.done is already True, return False. - Otherwise remove ticket from batch.waiters[ticket.key] in O(1). If it was the last waiter for that key, delete ticket.key from batch.waiters—so if the batch is still OPEN, READY, or in BACKOFF, we save bandwidth by not even asking the server for ticket.key! - If the OPEN batch now has zero keys left, cancel window_timer and set self._open = None so zero HTTP requests are sent. - If the batch is already IN_FLIGHT, we cannot recall bytes on the wire, so we schedule Cancelled(key) for this caller immediately while sibling waiters for the same key still receive their value when the HTTP response arrives.

    # Method on BatchingFetcher (Step 4 of implementation: O(1) cancellation)
    class BatchingFetcherCancelMixin:
        def cancel(self, req: Request) -> bool:
            if req.done:
                return False
    
            batch = req.batch
            if batch is not None:
                key_waiters = batch.waiters.get(req.key)
                if key_waiters is not None:
                    key_waiters.pop(req.id, None)
                    if not key_waiters:
                        # Nobody else in this batch wants req.key anymore
                        del batch.waiters[req.key]
    
                # If cancelling emptied the OPEN batch completely, abort its 100 ms timer
                if batch.state == "OPEN" and not batch.waiters:
                    batch.window_timer.cancel()
                    batch.state = "DONE"
                    if self._open is batch:
                        self._open = None
    
            self._complete_request(req, Cancelled(req.key), None)
            return True
    

    (Note: we intentionally leave batch.url_len un-decremented on cancel; keeping url_len as a conservative upper bound avoids edge-case bookkeeping and at worst seals a heavily-cancelled batch slightly early.)

    Two-level backpressure. 1. max_in_flight (default 4) throttles outbound concurrency so a degraded backend isn't hammered by dozens of overlapping batch reads. Sealed batches wait in self._ready (and if desired, _pump_ready_queue can even coalesce adjacent READY batches up to max_keys/max_url_len before dispatch without violating consistency, since neither batch has been dispatched yet!). 2. max_pending (default 10,000) caps memory inside our process by failing excess arrivals fast with Overloaded.

  9. Complexity and single-threaded event-loop pitfalls

    Time and space complexity (let L be len(key), U be distinct keys in a batch, and R be total Request waiters in that batch):

    getKeyAsync(key, cb) : O(L) to URL-encode key + O(1) average dict insert into batch.waiters
    cancel(ticket)       : O(1) average (two dict key removals + call_soon)
    _dispatch_batch      : O(U * avg_key_len) to join URL query string
    _on_http_response    : O(response_bytes) in parseKvs + O(R) to schedule callbacks
    Memory footprint     : O(pending_requests) <= O(max_pending), bounded strictly by configuration
    Active timers        : <= 1 open window timer + max_in_flight timeout timers + retrying backoff timers
    

    Six classic single-threaded ordering pitfalls (and how our design prevents them)

    1. Synchronous vs. asynchronous callback mixing ("Zalgo"): Running callback synchronously on Overloaded or cancel() surprises callers whose local state isn't initialized yet. Fix: every completion goes through loop.call_soon.
    2. One throwing callback breaking the rest of the batch: If cb1 raises ValueError inside a plain for loop, cb2..cb500 never get called! Fix: schedule each callback individually via _invoke_safe wrapped in try / except.
    3. Re-entrant state mutation: A callback that immediately calls getKeyAsync or cancel while _on_http_response is looping over batch.waiters can raise RuntimeError: dictionary changed size during iteration. Fix: swap batch.waiters = {} and set batch.state = "DONE" before scheduling callbacks.
    4. Stale window timer sealing the next batch: If Batch 1 seals early at t = 65 ms due to max_keys and forgets to cancel its t = 100 ms timer, or uses a single shared self._timer without checking which batch owns it, t = 100 ms prematurely seals Batch 2 after only 35 ms! Fix: cancel batch.window_timer in _seal_batch and pass batch to _on_window_expired checking batch.state == "OPEN".
    5. Zombie timeout / late HTTP reply double-firing callbacks: Attempt 1 times out at t = 2,000 ms, Attempt 2 starts, and Attempt 1's delayed packet arrives at t = 2,050 ms. Fix: compare batch.attempt == attempt and guard req.done.
    6. Event-loop starvation: Heavy CPU work inside parseKvs or user callbacks delays timers past 100 ms ("100 ms" on an event loop always means at least 100 ms). max_keys bounds JSON payload sizes so parseKvs stays sub-millisecond.
  10. Deterministic test plan with a fake clock

    Never test event-loop timers with real time.sleep(0.1)—tests become slow and race-prone on busy CI machines. Instead, inject a deterministic FakeLoop driven by a min-heap manual clock and a fake_http stub whose responses the test triggers in any chosen order:

    import heapq
    import json
    
    
    class FakeTimer:
        def __init__(self):
            self.cancelled = False
    
        def cancel(self):
            self.cancelled = True
    
    
    class FakeLoop:
        """Deterministic single-threaded clock + task queue for instant, flake-free unit tests."""
    
        def __init__(self):
            self.now = 0.0
            self._heap = []
            self._seq = 0
    
        def call_soon(self, fn, *args):
            return self.call_later(0.0, fn, *args)
    
        def call_later(self, delay: float, fn, *args) -> FakeTimer:
            timer = FakeTimer()
            heapq.heappush(self._heap, (self.now + delay, self._seq, timer, fn, args))
            self._seq += 1
            return timer
    
        def advance_to(self, target_time: float) -> None:
            while self._heap and self._heap[0][0] <= target_time:
                when, _, timer, fn, args = heapq.heappop(self._heap)
                self.now = when
                if not timer.cancelled:
                    fn(*args)
            self.now = target_time
    
    
    class CompleteFetcher(
        BatchingFetcher,
        BatchingFetcherWindowMixin,
        BatchingFetcherDispatchMixin,
        BatchingFetcherRetryMixin,
        BatchingFetcherCancelMixin,
    ):
        """Combines all four mixins into the complete runnable BatchingFetcher."""
    
    
    def test_consistency_rule_and_dedup():
        loop = FakeLoop()
        http_calls = []
        events = []
    
        def fake_http(url_path, cb):
            http_calls.append((url_path, cb))
    
        fetcher = CompleteFetcher(loop, fake_http, json.loads)
    
        # t = 0 ms: two callers ask for "sku_7" in the same 100 ms window -> deduplicated!
        fetcher.getKeyAsync("sku_7", lambda err, val: events.append(("r1", err, val)))
        fetcher.getKeyAsync("sku_7", lambda err, val: events.append(("r2", err, val)))
    
        # t = 100 ms: Batch 1 seals and dispatches a single GET /read?keys=sku_7
        loop.advance_to(0.100)
        assert len(http_calls) == 1 and http_calls[0][0] == "/read?keys=sku_7"
    
        # t = 110 ms: r3 asks for "sku_7" AFTER Batch 1 was dispatched -> must wait for Batch 2!
        fetcher.getKeyAsync("sku_7", lambda err, val: events.append(("r3", err, val)))
    
        # t = 120 ms: Batch 1 returns {"sku_7": 250} -> satisfies r1 and r2 ONLY, NOT r3
        http_calls[0][1](None, '{"sku_7": 250}')
        loop.advance_to(0.120)
        assert events == [("r1", None, 250), ("r2", None, 250)]
    
        # t = 210 ms: Batch 2 dispatches and returns updated value {"sku_7": 310} to r3
        loop.advance_to(0.210)
        assert len(http_calls) == 2 and http_calls[1][0] == "/read?keys=sku_7"
        http_calls[1][1](None, '{"sku_7": 310}')
        loop.advance_to(0.220)
        assert events == [("r1", None, 250), ("r2", None, 250), ("r3", None, 310)]
    

    Core test suite to cover in an interview 1. Single & duplicate keys in window: 3 requests for "sku_7" + 1 for "sku_9" -> one /read?keys=sku_7,sku_9 at t = 100 ms, all 4 callbacks fire once in arrival order. 2. Post-dispatch consistency boundary: request arriving 1 ms after dispatch is never answered by the in-flight batch (verified above). 3. Out-of-order concurrent batches: Batch 1 (t = 100 ms) answers after Batch 2 (t = 200 ms); each caller receives its own batch's snapshot. 4. Missing key vs. 400 vs. 503 retry: absent key yields KeyNotFound with 0 retries; 400 yields FetchFailed with 0 retries; 503 retries with backoff and succeeds on attempt 2. 5. Timeout + late first reply: attempt 1 times out at 2.0 s, attempt 2 dispatches, attempt 1's late reply arrives at 2.1 s (ignored!), attempt 2 succeeds -> callbacks fire once. 6. Cancellation in OPEN vs. IN_FLIGHT: cancelling sole "sku_9" waiter before 100 ms omits "sku_9" from URL; cancelling all waiters sends 0 HTTP calls; cancelling in-flight "sku_7" delivers Cancelled once without breaking sibling "sku_7" waiters. 7. Early seal & backpressure: max_keys = 2 seals immediately on the 3rd distinct key (not on duplicate keys); max_in_flight = 1 queues sealed batches; max_pending = 2 rejects the 3rd request asynchronously with Overloaded. 8. Randomized linearizability fuzz test: simulate 500 seeded timelines mixing writes to a fake key-value store, getKeyAsync, cancel, timeouts, and out-of-order HTTP completions, asserting that every non-error callback ran at most and at least once and observed a value present on the server at some instant inside [arrival_time, completion_time].

Intuition & how it works

Think of getKeyAsync like an office mailroom shuttle bus that starts a 100 ms countdown as soon as the first envelope is dropped off. Instead of sending 5,000 separate couriers across town every second, everyone who drops off a lookup request while the current shuttle's door is open shares a single trip (GET /read?keys=k1,k2,...). If ten callers ask for the exact same key "sku_7", the driver writes "sku_7" on the manifest only once (deduplication) while clipping all ten claim tickets onto that specific bus's clipboard. The instant the 100 ms timer fires (or the manifest fills up), the shuttle locks its doors and pulls out (dispatched): anyone arriving even 1 millisecond later starts loading the next shuttle, even if they also ask for "sku_7". Locking the manifest at dispatch guarantees read-after-arrival consistency—no caller ever receives a stale value read by a shuttle that left before the caller even asked!

Why do naive implementations fail? Calling httpGetAsync directly per lookup floods the backend with thousands of tiny HTTP requests per second and exhausts connection pools. Keeping a single global key -> [callbacks] dictionary mixes batches together: an already-in-flight request for "sku_7" will prematurely answer a brand-new caller with an outdated snapshot, and two overlapping batches will steal each other's callbacks. Finally, invoking error or cancellation callbacks synchronously on the caller's stack causes unpredictable execution order and crashes if a callback calls getKeyAsync or cancel mid-loop (re-entrancy, when a function is entered again via a callback before its previous call finished updating internal state).

Let's trace four concrete requests (r1, r2, r3, r4) on the event loop (a single thread running one small callback at a time from a task queue) to see how batches stay isolated:

t =   0 ms : r1 = getKeyAsync("sku_7", cb1) -> opens Batch #0, starts 100 ms window timer
t =  40 ms : r2 = getKeyAsync("sku_7", cb2) -> joins Batch #0 under key "sku_7" (still 1 URL key!)
t =  70 ms : r3 = getKeyAsync("sku_9", cb3) -> joins Batch #0 under key "sku_9"
t = 100 ms : Window timer fires! Batch #0 seals (self._open = None) and dispatches:
             GET /read?keys=sku_7,sku_9   (Batch #0 is now IN_FLIGHT, attempt = 1)
t = 110 ms : Backend updates "sku_7" from 250 to 310; caller runs r4 = getKeyAsync("sku_7", cb4)
             -> self._open is None, so r4 opens fresh Batch #1 (timer set for t = 210 ms)
t = 135 ms : Batch #0 HTTP response arrives: {"sku_7": 250, "sku_9": 40}
             -> Closure resolves ONLY Batch #0's waiters via call_soon:
                cb1(None, 250), cb2(None, 250), cb3(None, 40). r4 is untouched!
t = 210 ms : Batch #1 dispatches GET /read?keys=sku_7 -> returns {"sku_7": 310} -> cb4(None, 310).

Key trade-offs

  • First-arrival tumbling window vs. fixed tick or debounce window. Starting the 100 ms timer when the first request enters an empty batch caps batching latency at 100 ms and lets an idle process sleep completely. A fixed repeating 100 ms timer wakes the CPU 10 times per second when idle, while a debounce window (restarting the 100 ms timer on every incoming call) can starve early callers indefinitely during steady traffic.
  • Strict seal-at-dispatch vs. piggybacking on in-flight keys. Letting r4("sku_7") attach to an already-in-flight batch fetching "sku_7" would save one backend lookup for hot keys, but violates the consistency requirement because the backend may have read "sku_7" before r4 arrived. Sealing self._open before dispatch guarantees linearizable read-after-arrival semantics, trading cross-batch deduplication for strict freshness.
  • Per-batch waiter maps + closure correlation vs. a global key map. Storing waiters: dict[str, dict[int, Request]] inside each Batch object and capturing (batch, attempt) in the HTTP callback closure (a nested function that remembers variables from its enclosing scope) uses a few extra bytes per batch object, in exchange for making cross-batch response mixing structurally impossible even when responses return out of order.
  • Early sealing on max_keys / max_url_len vs. pure time-based flushing. Sealing a batch immediately when the next distinct key would exceed 200 keys or 8,000 URL bytes sends slightly more HTTP calls during bursts, but prevents 414 URI Too Long rejections from proxies and keeps JSON parse times short on the single-threaded loop.
  • Always-asynchronous callbacks (call_soon) vs. immediate synchronous invocation. Deferring every callback—including fast-fail Overloaded and cancel() completions—by one event-loop tick adds microseconds of scheduling overhead, but guarantees uniform execution ordering and prevents user callbacks from mutating batch.waiters while the fetcher is mid-update.
  • Whole-batch retry with released concurrency slots vs. holding slots during backoff. Because GET /read is idempotent (safe to repeat without changing server state), retrying the whole batch on 5xx, 429, or timeout with exponential backoff and jitter (doubling wait times multiplied by a random factor so retries do not collide in lockstep) is simple and reliable; releasing the in_flight slot during the backoff sleep lets healthy newer batches proceed, while appendleft puts the older retried batch at the front of the queue once its delay finishes.
  • Fail-fast Overloaded cap vs. unbounded queuing. Rejecting requests beyond max_pending = 10,000 forces callers to handle errors under extreme brownouts, whereas an unbounded queue silently consumes gigabytes of RAM until the process crashes.

Common mistakes

  • Using a single global pending_by_key: dict[str, list[Callback]] table. Any request for "sku_7" arriving while "sku_7" is already on the wire gets answered by the old batch's response (violating consistency), and two overlapping in-flight batches for "sku_7" corrupt each other's waiter lists.
  • Clearing self._open on HTTP response instead of HTTP dispatch. Leaving the batch open while the network call is in flight lets post-dispatch arrivals sneak into the batch.
  • Forgetting to URL-encode keys before joining with ,. A key like "a,b" or "x&y=1" splits into bogus keys or corrupts the query string unless percent-encoded (quote(key, safe="")).
  • Missing per-attempt guards on timeouts and retries. When Attempt 1 times out at 2,000 ms, triggers Attempt 2, and then Attempt 1's delayed packet finally arrives at 2,050 ms, failing to check batch.attempt == attempt and request.done invokes every user callback twice!
  • Forgetting to cancel or guard the 100 ms window timer on early size-cap flushes. If a shared timer fires after Batch #0 already sealed early at 65 ms, an unguarded timer handler prematurely flushes Batch #1 after only 35 ms.
  • Iterating directly over batch.waiters while invoking user callbacks synchronously. If one callback throws an uncaught exception, every remaining waiter in the batch hangs forever; if one callback calls cancel() or getKeyAsync(), mutating the dictionary mid-loop raises RuntimeError.
  • Writing unit tests with real sleep(0.1) calls. Real wall-clock timers make 12 edge-case tests take seconds and flake randomly under CPU load; injecting a heap-based FakeLoop tests multi-second retry/timeout interleavings deterministically in under 5 milliseconds.

Follow-up questions

  • How would you layer an async/await coroutine API on top of callback-based getKeyAsync while preserving cancellation? Keep the core batching state machine callback-based and wrap it in a thin async adapter using an event-loop Future (a placeholder object representing a result that will arrive later). Create future = loop.create_future(), pass a small completion callback to getKeyAsync that calls future.set_result(val) or future.set_exception(err), and catch asyncio.CancelledError around await future so cancelling a coroutine automatically calls fetcher.cancel(ticket) and removes unneeded keys before dispatch:

```python import asyncio

async def get_key(fetcher, key: str): loop = asyncio.get_running_loop() future = loop.create_future()

  def on_done(error, value):
      if future.done():
          return
      if error is not None:
          future.set_exception(error)
      else:
          future.set_result(value)

  ticket = fetcher.getKeyAsync(key, on_done)
  try:
      return await future
  except asyncio.CancelledError:
      fetcher.cancel(ticket)
      raise

```

  • Can you add a client-side cache for frequently requested keys without violating the pre-dispatch consistency guarantee? Not under strict read-after-arrival consistency, because any cached entry was fetched before the new request arrived—the exact same staleness risk as piggybacking on an in-flight batch! If the product explicitly relaxes consistency to bounded staleness (for instance, "values read within the last 500 ms are acceptable"), each cached entry can store (value, batch_dispatch_timestamp): a request arriving at t_req may be served from cache (or piggyback on an in-flight batch!) if and only if t_dispatch >= t_req - 0.500.
  • How would you avoid the 100 ms batching wait during low-traffic periods while still coalescing bursts? Apply Nagle's algorithm (the same adaptive batching trick TCP uses for small packets): when len(self._in_flight) == 0, dispatch the very first request immediately with zero timer wait; while at least one batch is IN_FLIGHT, buffer newly arriving requests in self._open until either the in-flight batch returns or the 100 ms window / size cap hits. You should ask the interviewer before switching to this mode, because it intentionally changes strict 100 ms window coalescing into "dispatch immediately when idle, batch while busy", trading higher HTTP request counts at low QPS for near-zero added tail latency.

Follow-up questions

Similar questions

More Anrok interview questions

All 3 Anrok questions →