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 HTTPGETforurland later invokescallback(response_dict)once the response dictionary arrives.set_timeout(callback, ms): schedulescallback()to run oncemsmilliseconds afterset_timeoutis 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:
- Lazy window timer: Schedule zero timers while idle. When
start_fetcharrives and no batch window is currently open, open a window and schedule one flushwindow_msmilliseconds later. Any furtherstart_fetchcalls before that flush fires join the same open window without creating additional timers. - 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. - 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, orNoneif the server omitted that key. If the same key was requested multiple times in the window, every registered callback runs once. - In-flight batch isolation: Flushing a window closes it immediately. Any
start_fetchcall 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 ifhttp_get_requestresponds 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_fetchshould run inO(1)expected time per call, and flushing/delivering a batch withkdistinct keys andcwaiting callbacks should run inO(k + c)time (plus URL string length).
Step-by-step walkthrough
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 combinedGET /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_fetchcall that arrives while no batch is waiting. That sends the example's first batch att = 100 msand 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%2Cand spaces into%20) so a key containing a comma cannot be misread by the server as two separate keys.
Because
http_get_requestandset_timeoutcome from the host runtime,KeyBatcheraccepts them as constructor arguments (making it easy to test with a fake clock), andmake_start_fetchbinds them into a standalonestart_fetch(key, callback)function.- When does the 100 ms window open? On the first
Trace the timeline: how many timers do we need?
A naive implementation that calls
http_get_requestimmediately on everystart_fetchsends 4 HTTP requests for 4 calls. A second naive attempt—callingset_timeout(..., 100)on everystart_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.
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.pendingis non-empty if and only if a 100 ms flush timer is currently scheduled. - Whenstart_fetchseesnot self.pending, it knows no timer is running, so it schedulesself._flush. - Whenself._flushruns, it resetsself.pendingback to{}. - Because we checknot self.pendingdirectly, we do not need a separate boolean flag likeself.timer_scheduledthat 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)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 att = 115 ms,cb4asks 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 att = 150 ms, it would wrongly hand Batch 1's older value tocb4!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
_flushare essential:- Assign a brand-new
{}instead of calling.clear(). Writingbatch = self.pending; self.pending.clear()would wipe the exact dictionarybatchpoints to, leaving zero callbacks to call when the response arrives! Rebindingself.pending = {}pointsself.pendingat a new empty dict while leavingbatchuntouched. - 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 ownbatchdict and its ownon_responseclosure, in-flight requests cannot interfere with one another even if responses arrive out of order. - Detach before calling
http_get_request. Ifhttp_get_requestever answers immediately (for example from a local cache) and one of the user callbacks callsstart_fetchright away,self.pendingis already{}—so that chained call safely opens a fresh batch instead of modifyingbatchmid-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)- Assign a brand-new
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},deliverwalks each(key, callbacks)pair in that detachedbatch, looks upresponse.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_fetchBecause each callback sits in exactly one detached
batchand the runtime invokeson_responseonce when its HTTP request completes, every callback runs once with the value from the batch it joined.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,cb1andcb3got725whilecb4got750.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_fetchtime — O(1) average per call: We check whetherself.pendingis empty, do one hash-table lookup forkey, appendcallbackto a Python list in amortized constant time, and callset_timeoutat most once per batch._flushtime — O(k + U): Forkdistinct keys whose percent-encoded characters total lengthU, we iterate through thekkeys once and join the encoded strings into one URL of lengthO(U).delivertime — O(k + c): Forkdistinct keys andcwaiting callbacks in that batch, we do oneO(1)dictionary lookup inresponseper key and invoke each of theccallbacks once (excluding whatever work the caller's callback does itself).- Space — O(C): Across the open
pendingdictionary and any closures for HTTP requests still in flight, we store one list entry per waiting callback (Ccallbacks 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
cb4gets the newer value andcb1–cb3still 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
listrather than aset,start_fetch("tax_ca", cb)called twice in one window invokescbtwice, matching two caller requests. - Server omits a requested key:
response.get(key)evaluates toNone, so omitted keys receiveNonewithout crashing delivery for the other keys in the batch. - Synchronous HTTP response (cache hit): If
http_get_requestinvokeson_responseimmediately before returning, and a user callback callsstart_fetchright insidedeliver, detachingself.pending = {}before callinghttp_get_requestguarantees the re-entrant call opens a new batch instead of mutatingbatchduring iteration. - Keys containing commas, spaces, or
&: Percent-encoding (replacing reserved URL characters with%plus two hex digits, such as,->%2Cviaurllib.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_fetchcall: Creates redundant timers that either send four separate requests or fire later on emptypendingdictionaries (GET /get?keys=) and flush future keys earlier than 100 ms. - Keeping a single global
key -> callbacksmap across batches: Causes Batch 1's response arriving att = 150 msto prematurely firecb4(queued att = 115 ms) with stale data, leaving nobody waiting when Batch 2's response arrives. - Mutating
self.pending.clear()instead of rebindingself.pending = {}: Bothbatchandself.pendingreference the same dictionary object before rebinding, so.clear()erases every waiting callback right before the response arrives. - Resetting a
timer_runningflag insideon_responseinstead of_flush: If Request 1 is still in flight att = 115 ms,cb4seestimer_running == Trueand schedules no timer, strandingcb4inself.pendingindefinitely. - Detaching
self.pendingafter callinghttp_get_request: Breaks wheneverhttp_get_requestcompletes synchronously and triggers a chainedstart_fetch, either raisingRuntimeError: dictionary changed size during iterationor wiping the newly queued callback right afterward.
Alternative approaches
- Fixed-interval 100 ms ticker: Schedule
set_timeout(tick, 100)once and havetickreschedule itself forever, flushing wheneverself.pendingis 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 countM, or when the 100 ms timer fires, whichever comes first. Becauseset_timeoutreturns 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, slicelist(batch.keys())into chunks of at mostMkeys (for example, 250 keys withM = 100become three chunks of 100, 100, and 50), build a smaller sub-dictionary{k: batch[k] for k in chunk}for each chunk, and callhttp_get_requestonce 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 asMkeys accumulate before 100 ms, increment aself.generationcounter 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
cb4onto an already in-flight request (by keeping anin_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 answeringcb4up to 100 ms plus a round-trip faster. However, it violates read-after-write freshness (a guarantee that a lookup started att = 115 mssees writes committed att = 108 ms), because the server may have read"tax_ca"att = 103 msbeforecb4even asked. Our contract requires a second HTTP request here socb4observes a read started aftert = 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
attemptcounter and a booleansettled = Falseguard, and scheduleset_timeout(on_timeout, timeout_ms)alongside eachhttp_get_request. Because the event loop is single-threaded, checkingif settled: returnis free of race conditions: if a valid response arrives before all retries fail, setsettled = Trueand deliver once so future timeout timers become no-ops; ifon_timeoutfires whilesettledis stillFalse, incrementattempt(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) becauseGETlookups are idempotent (safe to repeat without changing server state). After the final retry times out, setsettled = Trueand invoke every callback once withNoneor 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_fetchconcurrently? Wrapself.pendingwith a mutex lock (a synchronization primitive allowing only one thread at a time inside a critical section) so checkingnot self.pending, scheduling the timer, and appendingcallbackhappen atomically—otherwise two threads could both see an empty dictionary and schedule duplicate timers, or one thread could append to a dictionary right after_flushdetached it. Inside_flush, acquire the lock only long enough to swapbatch = self.pending; self.pending = {}, then release the lock before callinghttp_get_requestor invoking user callbacks so a callback that callsstart_fetchagain cannot deadlock waiting for the same lock. Even simpler in practice is keepingKeyBatchersingle-threaded and posting cross-threadstart_fetchcalls onto the event loop's thread-safe queue (such asloop.call_soon_threadsafein Python'sasyncio).
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?
- 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?
- If HTTP requests can hang indefinitely, how would you layer per-request timeouts and retries while guaranteeing each callback runs at most once?
- What synchronization changes are required if multiple OS threads invoke `start_fetch` concurrently?
Similar questions
- Batched Event-Loop Key-Value Client
- Multithreading vs. Event-Loop Concurrency
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging