Coalesce Callback Key Fetches Into 100 ms HTTP Batches

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement a client-side request batcher for a single-threaded, event-driven runtime where asynchronous work uses callbacks rather than async/await.

A backend service exposes a multi-key lookup endpoint:

GET /get?keys=k1,k2,...

which responds with a dictionary mapping resolved keys to their values (for instance, {"tax_ca": 725, "tax_ny": 888}).

The host environment supplies two non-blocking primitives:

  • http_get_request(url, callback): dispatches an HTTP GET for url and later invokes callback(response_dict) once the response dictionary arrives.
  • set_timeout(callback, ms): schedules callback() to run once ms milliseconds after set_timeout is invoked.

Implement KeyBatcher and the factory make_start_fetch so callers can request individual keys through start_fetch(key, callback) while outgoing lookups are coalesced into one HTTP request per window_ms (100 ms by default):

from typing import Any, Callable

BATCH_WINDOW_MS = 100


class KeyBatcher:
    def __init__(
        self,
        http_get_request: Callable,
        set_timeout: Callable,
        window_ms: int = BATCH_WINDOW_MS,
    ):
        ...

    def start_fetch(self, key: str, callback: Callable[[Any], None]) -> None:
        ...


def make_start_fetch(
    http_get_request: Callable,
    set_timeout: Callable,
) -> Callable[[str, Callable], None]:
    ...

Your implementation must satisfy these exact rules:

  1. Lazy window timer: Schedule zero timers while idle. When start_fetch arrives and no batch window is currently open, open a window and schedule one flush window_ms milliseconds later. Any further start_fetch calls before that flush fires join the same open window without creating additional timers.
  2. Per-window deduplication and encoding: Within one window, include each distinct key only once in /get?keys=..., ordered by its first arrival in that window. Percent-encode every key (safe="", so , becomes %2C, spaces become %20, & becomes %26, etc.) before joining with commas.
  3. Callback fan-out and missing keys: When a batch's response dictionary arrives, invoke every callback that joined that batch with response.get(key)—passing only its own key's value, or None if the server omitted that key. If the same key was requested multiple times in the window, every registered callback runs once.
  4. In-flight batch isolation: Flushing a window closes it immediately. Any start_fetch call made after a batch flushes—including calls for a key whose earlier batch is still awaiting a response, or calls triggered inside a response callback (even if http_get_request responds synchronously)—must join or open a subsequent batch, and out-of-order HTTP responses must only notify callbacks from their own batch.

Examples

Example 1

Timeline:
  t =   0 ms: start_fetch("tax_ca", cb1)
  t =  25 ms: start_fetch("tax_ny", cb2)
  t =  65 ms: start_fetch("tax_ca", cb3)
  t = 115 ms: start_fetch("tax_ca", cb4)

Outgoing HTTP calls:
  t = 100 ms: GET /get?keys=tax_ca,tax_ny
  t = 215 ms: GET /get?keys=tax_ca

The t = 0 ms call opens a 100 ms window ending at t = 100 ms; the calls at 25 ms and 65 ms join that window, deduplicating "tax_ca". At t = 115 ms, Batch 1 has already flushed, so cb4 opens Batch 2 (flushing at 215 ms). When Batch 1 answers {"tax_ca": 725, "tax_ny": 888}, cb1(725), cb3(725), and cb2(888) run; when Batch 2 answers {"tax_ca": 750}, cb4(750) runs.

Example 2

Timeline:
  t =  10 ms: start_fetch("plan,pro", cb1)
  t =  10 ms: start_fetch("legacy", cb2)
  t = 130 ms: start_fetch("seat count", cb3)

Outgoing HTTP calls:
  t = 110 ms: GET /get?keys=plan%2Cpro,legacy
  t = 230 ms: GET /get?keys=seat%20count

Suppose Request 2 returns first at t = 240 ms with {"seat count": 15}, and Request 1 returns later at t = 280 ms with {"plan,pro": "active"}. At t = 240 ms, only cb3(15) runs. At t = 280 ms, cb1("active") and cb2(None) run ("legacy" was absent from Request 1's response).

Constraints

  • Execution is single-threaded and cooperative: start_fetch, timer callbacks, and HTTP response callbacks each run to completion without preemption.
  • Network responses may arrive arbitrarily late, out of order across batches, or synchronously inside http_get_request.
  • Keys are arbitrary Python strings and may contain commas, spaces, slashes, or query delimiters.
  • start_fetch should run in O(1) expected time per call, and flushing/delivering a batch with k distinct keys and c waiting callbacks should run in O(k + c) time (plus URL string length).

Step-by-step walkthrough

  1. Understand the goal and settle edge-case rules

    We are running on a single-threaded event loop (a runtime that executes functions one at a time from a queue, never interrupting one function halfway through to run another). Callers ask for single keys via start_fetch(key, callback)—where a callback is simply a function the caller passes in so we can invoke it later once the network answer arrives. Instead of firing one HTTP request per call, we want to group calls into 100 ms windows and send one combined GET /get?keys=... request per window.

    Before writing code, state the exact contract for the open design details:

    • When does the 100 ms window open? On the first start_fetch call that arrives while no batch is waiting. That sends the example's first batch at t = 100 ms and schedules zero timers when the app is idle (unlike a repeating 100 ms heartbeat, which wakes up ten times a second forever).
    • Duplicate keys inside one window: Include each distinct key only once in the URL (in the order it was first requested), while remembering every waiting callback so all of them receive the result.
    • What argument does each callback receive? Only its own key's value, callback(value)—not the entire response dictionary, which would expose other callers' keys.
    • Missing keys in the response: Pass None (response.get(key)) so one omitted key does not prevent the other callbacks in the batch from running.
    • Special characters inside keys: Percent-encode each key (turning characters like , into %2C and spaces into %20) so a key containing a comma cannot be misread by the server as two separate keys.

    Because http_get_request and set_timeout come from the host runtime, KeyBatcher accepts them as constructor arguments (making it easy to test with a fake clock), and make_start_fetch binds them into a standalone start_fetch(key, callback) function.

  2. Trace the timeline: how many timers do we need?

    A naive implementation that calls http_get_request immediately on every start_fetch sends 4 HTTP requests for 4 calls. A second naive attempt—calling set_timeout(..., 100) on every start_fetch—creates 4 separate timers and flushes at the wrong times.

    Let's trace Example 1's 4 calls on a timeline to see which calls actually start a timer:

    Time (ms)   Event                         Action                                  Waiting batch
    ---------   ---------------------------   -------------------------------------   ------------------------------------
    t =   0     start_fetch("tax_ca", cb1)    No batch open -> schedule Timer A       {"tax_ca": [cb1]}
                                              (due at 0 + 100 = 100 ms)
    t =  25     start_fetch("tax_ny", cb2)    Timer A already active -> join batch    {"tax_ca": [cb1], "tax_ny": [cb2]}
    t =  65     start_fetch("tax_ca", cb3)    Timer A already active -> join batch    {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}
    t = 100     Timer A fires!                Send GET /get?keys=tax_ca,tax_ny        {}  (no batch open now)
    t = 115     start_fetch("tax_ca", cb4)    No batch open -> schedule Timer B       {"tax_ca": [cb4]}
                                              (due at 115 + 100 = 215 ms)
    t = 215     Timer B fires!                Send GET /get?keys=tax_ca               {}
    

    Notice the pattern: we need exactly one timer per batch, scheduled by the very first call that sees no batch waiting. Every call that arrives before that timer fires simply adds itself to the open batch.

  3. Store the open batch in one dictionary

    To answer two questions at once—"is a batch window already open?" and "which callbacks are waiting on each key?"—we store the unsent batch in a single dictionary self.pending:

    self.pending = {
        "tax_ca": [cb1, cb3],   # key -> list of callbacks waiting on "tax_ca" in this window
        "tax_ny": [cb2],        # Python dicts preserve first-insertion order: tax_ca, then tax_ny
    }
    

    This single dictionary gives us a clean invariant (a rule that stays true before and after every operation): self.pending is non-empty if and only if a 100 ms flush timer is currently scheduled. - When start_fetch sees not self.pending, it knows no timer is running, so it schedules self._flush. - When self._flush runs, it resets self.pending back to {}. - Because we check not self.pending directly, we do not need a separate boolean flag like self.timer_scheduled that could accidentally get out of sync.

    from typing import Any, Callable, Dict, List
    from urllib.parse import quote
    
    BATCH_WINDOW_MS = 100
    
    
    class KeyBatcher:
        def __init__(self, http_get_request: Callable, set_timeout: Callable, window_ms: int = BATCH_WINDOW_MS):
            self.http_get_request = http_get_request
            self.set_timeout = set_timeout
            self.window_ms = window_ms
            # pending: maps each distinct key in the open window to all callbacks waiting on it.
            # Mini-shape: {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}
            # Invariant: self.pending is non-empty if and only if a _flush timer is scheduled.
            self.pending: Dict[str, List[Callable[[Any], None]]] = {}
    
        def start_fetch(self, key: str, callback: Callable[[Any], None]) -> None:
            """Queue key for the next batch; callback(value) runs when that batch is answered."""
            # Phase 1: if no batch is currently open, this first arrival opens a new 100 ms window.
            # Later calls within the window see a non-empty dict and share this single timer.
            if not self.pending:
                self.set_timeout(self._flush, self.window_ms)
    
            # Phase 2: record the callback in a list (not a set) so duplicate keys are sent
            # once in first-seen order while every caller's callback still runs once.
            if key not in self.pending:
                self.pending[key] = []
            self.pending[key].append(callback)
    
  4. Detach the batch before sending the HTTP request

    Here is the subtlest bug in callback batching: HTTP responses take time! At t = 100 ms, Batch 1 is sent over the network, and at t = 115 ms, cb4 asks for "tax_ca" again. If our HTTP response handler looked up "tax_ca" in a single shared dictionary, then when Batch 1's response finally came back at t = 150 ms, it would wrongly hand Batch 1's older value to cb4!

    Instead, when the 100 ms timer fires in _flush, we detach the dictionary:

    Before _flush() at t = 100 ms:
      self.pending ──► {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}
    
    After detaching inside _flush() at t = 100 ms:
      self.pending ──► {}                                         (ready for Batch 2 at t = 115 ms)
      on_response1 ──► batch = {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}   (private to Request 1)
    

    Three details in _flush are essential:

    1. Assign a brand-new {} instead of calling .clear(). Writing batch = self.pending; self.pending.clear() would wipe the exact dictionary batch points to, leaving zero callbacks to call when the response arrives! Rebinding self.pending = {} points self.pending at a new empty dict while leaving batch untouched.
    2. Use a closure for on_response. A closure is an inner function (on_response) that remembers local variables (batch) from the outer function call (_flush) where it was created. Because each flush creates its own batch dict and its own on_response closure, in-flight requests cannot interfere with one another even if responses arrive out of order.
    3. Detach before calling http_get_request. If http_get_request ever answers immediately (for example from a local cache) and one of the user callbacks calls start_fetch right away, self.pending is already {}—so that chained call safely opens a fresh batch instead of modifying batch mid-loop.
    def build_url(keys: List[str]) -> str:
        """Build '/get?keys=k1,k2,...' with each key percent-encoded."""
        encoded_keys = []
        for key in keys:
            # safe="" encodes commas (%2C), slashes (%2F), spaces (%20), and '&' (%26)
            # so characters inside a key cannot split the comma-separated query parameter.
            encoded_keys.append(quote(key, safe=""))
        return "/get?keys=" + ",".join(encoded_keys)
    
    
    class KeyBatcher:
        # __init__ and start_fetch as shown above
    
        def _flush(self) -> None:
            """Timer callback: detach and send the waiting batch, leaving a fresh empty state."""
            batch = self.pending
            self.pending = {}
    
            def on_response(response: Dict[str, Any]) -> None:
                deliver(batch, response)
    
            keys_to_fetch = list(batch.keys())
            url = build_url(keys_to_fetch)
            self.http_get_request(url, on_response)
    
  5. Deliver each key's value to its waiting callbacks

    When the server responds to a batch with a dictionary such as {"tax_ca": 725, "tax_ny": 888}, deliver walks each (key, callbacks) pair in that detached batch, looks up response.get(key) once, and invokes every callback waiting on that key:

    def deliver(batch: Dict[str, List[Callable[[Any], None]]], response: Dict[str, Any]) -> None:
        """Call every callback in one detached batch with its own key's value (or None if omitted)."""
        for key, callbacks in batch.items():
            # .get(key) returns None when the server omits a key, preventing KeyError
            # from blocking delivery to the remaining keys in the same batch.
            value = response.get(key)
            for callback in callbacks:
                callback(value)
    
    
    def make_start_fetch(http_get_request: Callable, set_timeout: Callable) -> Callable[[str, Callable], None]:
        """Return a start_fetch(key, callback) function bound to the runtime's primitives."""
        return KeyBatcher(http_get_request, set_timeout).start_fetch
    

    Because each callback sits in exactly one detached batch and the runtime invokes on_response once when its HTTP request completes, every callback runs once with the value from the batch it joined.

  6. Trace out-of-order HTTP responses step by step

    Let's verify the hardest case: Batch 2's HTTP response comes back before Batch 1's HTTP response!

    t = 100 ms  _flush() runs for Timer A:
                  Closure 1 holds batch = {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}
                  self.pending = {}
                  HTTP #1 sent: GET /get?keys=tax_ca,tax_ny
    
    t = 115 ms  start_fetch("tax_ca", cb4):
                  self.pending is {} -> schedules Timer B (due at 215 ms)
                  self.pending = {"tax_ca": [cb4]}
    
    t = 215 ms  _flush() runs for Timer B:
                  Closure 2 holds batch = {"tax_ca": [cb4]}
                  self.pending = {}
                  HTTP #2 sent: GET /get?keys=tax_ca
    
    t = 250 ms  HTTP #2 responds FIRST with {"tax_ca": 750}:
                  Closure 2 runs -> calls cb4(750) ONLY!
    
    t = 300 ms  HTTP #1 responds LATER with {"tax_ca": 725, "tax_ny": 888}:
                  Closure 1 runs -> calls cb1(725), cb3(725), cb2(888)!
    

    Even though both batches asked for "tax_ca" and arrived out of order, cb1 and cb3 got 725 while cb4 got 750.

  7. Complete solution

    from typing import Any, Callable, Dict, List
    from urllib.parse import quote
    
    BATCH_WINDOW_MS = 100
    
    
    def build_url(keys: List[str]) -> str:
        """Build '/get?keys=k1,k2,...' with each key percent-encoded."""
        encoded_keys = []
        for key in keys:
            # safe="" encodes commas (%2C), slashes (%2F), spaces (%20), and '&' (%26)
            # so characters inside a key cannot split the comma-separated query parameter.
            encoded_keys.append(quote(key, safe=""))
        return "/get?keys=" + ",".join(encoded_keys)
    
    
    def deliver(batch: Dict[str, List[Callable[[Any], None]]], response: Dict[str, Any]) -> None:
        """Call every callback in one detached batch with its own key's value (or None if omitted)."""
        for key, callbacks in batch.items():
            # .get(key) returns None when the server omits a key, preventing KeyError
            # from blocking delivery to the remaining keys in the same batch.
            value = response.get(key)
            for callback in callbacks:
                callback(value)
    
    
    class KeyBatcher:
        """Batches single-key lookups into one GET /get?keys=k1,k2,... request per window.
    
        http_get_request(url, callback) and set_timeout(callback, ms) are the runtime's two
        primitives. They are passed in (instead of being globals) so a test can drive the
        batcher with a fake event loop.
        """
    
        def __init__(self, http_get_request: Callable, set_timeout: Callable, window_ms: int = BATCH_WINDOW_MS):
            self.http_get_request = http_get_request
            self.set_timeout = set_timeout
            self.window_ms = window_ms
            # pending: maps each distinct key in the open window to all callbacks waiting on it.
            # Mini-shape: {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}
            # Invariant: self.pending is non-empty if and only if a _flush timer is scheduled.
            self.pending: Dict[str, List[Callable[[Any], None]]] = {}
    
        def start_fetch(self, key: str, callback: Callable[[Any], None]) -> None:
            """Queue key for the next batch; callback(value) runs when that batch is answered."""
            # Phase 1: if no batch is currently open, this first arrival opens a new 100 ms window.
            # Later calls within the window see a non-empty dict and share this single timer.
            if not self.pending:
                self.set_timeout(self._flush, self.window_ms)
    
            # Phase 2: record the callback in a list (not a set) so duplicate keys are sent
            # once in first-seen order while every caller's callback still runs once.
            if key not in self.pending:
                self.pending[key] = []
            self.pending[key].append(callback)
    
        def _flush(self) -> None:
            """Timer callback: detach and send the waiting batch, leaving a fresh empty state."""
            # Phase 1: detach the dictionary by assigning a brand-new {} (never .clear(), which
            # would empty batch too). Doing this BEFORE http_get_request ensures that even if
            # http_get_request answers synchronously and a callback calls start_fetch again,
            # that new call opens a fresh batch instead of mutating batch mid-delivery.
            batch = self.pending
            self.pending = {}
    
            def on_response(response: Dict[str, Any]) -> None:
                # Closure captures only local `batch`, isolating this request's callbacks from
                # any later batches that opened while this HTTP request was still in flight.
                deliver(batch, response)
    
            # Phase 2: build the batch URL from distinct keys in first-request order and send it.
            keys_to_fetch = list(batch.keys())
            url = build_url(keys_to_fetch)
            self.http_get_request(url, on_response)
    
    
    def make_start_fetch(http_get_request: Callable, set_timeout: Callable) -> Callable[[str, Callable], None]:
        """Return a start_fetch(key, callback) function bound to the runtime's primitives."""
        return KeyBatcher(http_get_request, set_timeout).start_fetch
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of KeyBatcher like an airport shuttle bus with a 100-millisecond departure rule. When the curb is empty, no countdown clock is running. The moment the first passenger steps onto the bus, the driver starts a 100 ms timer. Anyone else who walks up during those 100 ms climbs onto the same bus; if two passengers ask for the same hotel stop, the driver writes that hotel down only once on the route sheet while noting both passengers' names. When the 100 ms timer rings, that bus pulls away with its own private passenger manifest, and a fresh empty bus immediately pulls up to the curb for future arrivals—even before the first bus returns.

A naive approach that calls http_get_request inside start_fetch sends one HTTP request per lookup, flooding the server and breaking the 100 ms batching rule. A slightly less naive approach that keeps a single global key -> callbacks dictionary across the entire program also breaks whenever an HTTP request takes longer than 100 ms: an older response returning late would trigger callbacks registered for a newer batch, or wipe callbacks that have not been answered yet. Giving each outgoing HTTP request its own detached dictionary inside a closure (an inner callback function that remembers the local variables of the flush call that created it) keeps overlapping in-flight batches completely separate.

Walk through the four calls from Example 1: 1. At t = 0 ms, start_fetch("tax_ca", cb1) sees an empty pending dict, schedules a flush timer for t = 100 ms, and sets pending = {"tax_ca": [cb1]}. 2. At t = 25 ms ("tax_ny", cb2) and t = 65 ms ("tax_ca", cb3), pending is already non-empty, so neither call schedules a timer; pending grows to {"tax_ca": [cb1, cb3], "tax_ny": [cb2]}. 3. At t = 100 ms, the timer fires, saves that dictionary into a local variable batch, resets self.pending = {}, and sends GET /get?keys=tax_ca,tax_ny with a response closure bound to batch. 4. At t = 115 ms, start_fetch("tax_ca", cb4) sees self.pending == {}, schedules a second timer for t = 215 ms, and starts a separate batch {"tax_ca": [cb4]} that fires GET /get?keys=tax_ca at t = 215 ms.

Complexity

  • start_fetch time — O(1) average per call: We check whether self.pending is empty, do one hash-table lookup for key, append callback to a Python list in amortized constant time, and call set_timeout at most once per batch.
  • _flush time — O(k + U): For k distinct keys whose percent-encoded characters total length U, we iterate through the k keys once and join the encoded strings into one URL of length O(U).
  • deliver time — O(k + c): For k distinct keys and c waiting callbacks in that batch, we do one O(1) dictionary lookup in response per key and invoke each of the c callbacks once (excluding whatever work the caller's callback does itself).
  • Space — O(C): Across the open pending dictionary and any closures for HTTP requests still in flight, we store one list entry per waiting callback (C callbacks total) plus each distinct key string once per batch; once a response arrives and its closure finishes, that batch's dictionary can be garbage-collected.

Edge cases

  • Out-of-order HTTP responses: If Request 2 returns before Request 1, Request 2's closure holds only Batch 2's dictionary, so cb4 gets the newer value and cb1–cb3 still wait for Request 1.
  • Duplicate keys within one window: Stored under a single dictionary key mapped to a list of callbacks, so the key appears once in the URL (in first-seen order) while every callback is invoked.
  • Identical callback function passed twice: Because callbacks are stored in a list rather than a set, start_fetch("tax_ca", cb) called twice in one window invokes cb twice, matching two caller requests.
  • Server omits a requested key: response.get(key) evaluates to None, so omitted keys receive None without crashing delivery for the other keys in the batch.
  • Synchronous HTTP response (cache hit): If http_get_request invokes on_response immediately before returning, and a user callback calls start_fetch right inside deliver, detaching self.pending = {} before calling http_get_request guarantees the re-entrant call opens a new batch instead of mutating batch during iteration.
  • Keys containing commas, spaces, or &: Percent-encoding (replacing reserved URL characters with % plus two hex digits, such as , -> %2C via urllib.parse.quote(key, safe="")) prevents a key like "a,b" from splitting into two keys "a" and "b" on the wire.

Common mistakes

  • Scheduling a timer on every start_fetch call: Creates redundant timers that either send four separate requests or fire later on empty pending dictionaries (GET /get?keys=) and flush future keys earlier than 100 ms.
  • Keeping a single global key -> callbacks map across batches: Causes Batch 1's response arriving at t = 150 ms to prematurely fire cb4 (queued at t = 115 ms) with stale data, leaving nobody waiting when Batch 2's response arrives.
  • Mutating self.pending.clear() instead of rebinding self.pending = {}: Both batch and self.pending reference the same dictionary object before rebinding, so .clear() erases every waiting callback right before the response arrives.
  • Resetting a timer_running flag inside on_response instead of _flush: If Request 1 is still in flight at t = 115 ms, cb4 sees timer_running == True and schedules no timer, stranding cb4 in self.pending indefinitely.
  • Detaching self.pending after calling http_get_request: Breaks whenever http_get_request completes synchronously and triggers a chained start_fetch, either raising RuntimeError: dictionary changed size during iteration or wiping the newly queued callback right afterward.

Alternative approaches

  • Fixed-interval 100 ms ticker: Schedule set_timeout(tick, 100) once and have tick reschedule itself forever, flushing whenever self.pending is non-empty. Under continuous traffic it sends the same rate of requests, but when the client is idle it keeps waking the event loop ten times per second, and the first key of a batch waits anywhere from 0 to 100 ms instead of a predictable 100 ms.
  • Flush on size or time (hybrid cap): Flush immediately as soon as len(self.pending) reaches a maximum key count M, or when the 100 ms timer fires, whichever comes first. Because set_timeout returns no cancel handle in this runtime, give each batch an integer generation counter (a number incremented every time a batch flushes) so an old timer whose batch already flushed early sees a mismatched generation and exits as a no-op.

Follow-up questions

  • Suppose the endpoint enforces a maximum key count per HTTP call. How would you split flushes and route each response back to its waiting callbacks? Inside _flush, slice list(batch.keys()) into chunks of at most M keys (for example, 250 keys with M = 100 become three chunks of 100, 100, and 50), build a smaller sub-dictionary {k: batch[k] for k in chunk} for each chunk, and call http_get_request once per chunk with a closure bound to that chunk's sub-dictionary. Each response maps straight back to its own chunk's callbacks with no shared lookup state. If you also want to flush early as soon as M keys accumulate before 100 ms, increment a self.generation counter on every flush and capture the current generation inside the timer closure so stale timers do nothing when they later fire.
  • When a caller requests a key that already has an unanswered batch in flight, under what circumstances could you piggyback onto that in-flight request, and what guarantee would you give up? Coalescing cb4 onto an already in-flight request (by keeping an in_flight: Dict[str, List[Callable]] map of sent-but-unanswered keys) is ideal when values are immutable or read from a cache where slightly older reads are acceptable, saving a duplicate HTTP call and answering cb4 up to 100 ms plus a round-trip faster. However, it violates read-after-write freshness (a guarantee that a lookup started at t = 115 ms sees writes committed at t = 108 ms), because the server may have read "tax_ca" at t = 103 ms before cb4 even asked. Our contract requires a second HTTP request here so cb4 observes a read started after t = 115 ms.
  • If HTTP requests can hang indefinitely, how would you layer per-request timeouts and retries while guaranteeing each callback runs at most once? Give each detached batch an attempt counter and a boolean settled = False guard, and schedule set_timeout(on_timeout, timeout_ms) alongside each http_get_request. Because the event loop is single-threaded, checking if settled: return is free of race conditions: if a valid response arrives before all retries fail, set settled = True and deliver once so future timeout timers become no-ops; if on_timeout fires while settled is still False, increment attempt (giving each attempt its own per-attempt timeout guard) and retry with exponential backoff (doubling the wait between retries, plus a small random jitter offset so many clients do not retry at the exact same millisecond) because GET lookups are idempotent (safe to repeat without changing server state). After the final retry times out, set settled = True and invoke every callback once with None or an error value, causing any very late network response from an earlier attempt to be ignored.
  • What synchronization changes are required if multiple OS threads invoke start_fetch concurrently? Wrap self.pending with a mutex lock (a synchronization primitive allowing only one thread at a time inside a critical section) so checking not self.pending, scheduling the timer, and appending callback happen atomically—otherwise two threads could both see an empty dictionary and schedule duplicate timers, or one thread could append to a dictionary right after _flush detached it. Inside _flush, acquire the lock only long enough to swap batch = self.pending; self.pending = {}, then release the lock before calling http_get_request or invoking user callbacks so a callback that calls start_fetch again cannot deadlock waiting for the same lock. Even simpler in practice is keeping KeyBatcher single-threaded and posting cross-thread start_fetch calls onto the event loop's thread-safe queue (such as loop.call_soon_threadsafe in Python's asyncio).

Follow-up questions

Similar questions

More Anrok interview questions

All 3 Anrok questions →