Coalescing Single-Key Reads into Timed Batch Requests
Data Structure DesignModel answerLast updated
Build a callback-driven client that gathers individual key requests into one batched GET every 100 ms, using only a timer and an async HTTP primitive, while keeping overlapping batches isolated.
You are writing client code for a single-threaded, callback-driven runtime, comparable to a JavaScript event loop. A backend offers a bulk read endpoint:
GET /get?keys=key1,key2,...
Response: {"key1": 123, "key2": "abs"}
The runtime gives you exactly two primitives:
http_get_request(url, callback) # issues a GET; when the reply arrives, invokes callback(response: dict)
set_timeout(callback, ms) # invokes callback() once, ms milliseconds after this call
Implement start_fetch(key, callback). Application code calls it for one key at a time, but you must not issue one HTTP request per call. Instead, gather the requested keys and send them to the endpoint as a single batch request roughly every 100 ms. When a batch's response arrives, every callback that was waiting on a key from that batch must be invoked.
def start_fetch(key, callback):
# TODO: implement this
...
Example driver:
def main():
start_fetch("foo", cb1) # t = 0 ms
start_fetch("bar", cb2) # t = 30 ms
start_fetch("foo", cb3) # t = 70 ms
start_fetch("foo", cb4) # t = 120 ms
Here http_get_request must be called exactly twice. The first response triggers cb1, cb2 and cb3; the second response triggers cb4.
You may introduce global state and helper functions.
Rules
- The runtime is single-threaded:
start_fetch, timer callbacks and response callbacks each run to completion, one at a time. - A key may be requested multiple times before its batch goes out, and all waiting callbacks must fire (
cb1andcb3both wait on"foo"). - A key requested after its batch has been sent belongs to a later batch, even if the earlier request is still unanswered. This is why
cb4causes a second request. - A response can arrive at any later moment, including after further
start_fetchcalls or after the next batch has already been sent.
What to deliver
Write the implementation and explain (1) how you schedule the 100 ms flush, and (2) how you store pending keys together with the callbacks waiting on each. State your assumptions about the open design points: how the window is anchored, whether duplicate keys appear once in the URL, what the callback receives, and how failures or missing keys are handled.
Hints
Hint 1
Think about what has to happen the first time a key arrives while nothing is pending, and what should happen on every later arrival before the flush.
Hint 2
A dictionary from key to a list of callbacks handles duplicates naturally, and its keys give you the de-duplicated URL list.
Hint 3
At flush time, hand the current dictionary to the request's response handler and replace the global with a fresh one, so a late response can only touch its own batch.
Hint 4
Decide up front what a callback receives and what you do when the response lacks a key or the request fails; make sure each callback still runs exactly once.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep one piece of global state: a dictionary pending mapping each key to the list of callbacks waiting on it. Also keep a flag (or simply check whether pending is empty) telling us whether a flush timer is already armed.
Assumption on the window. I anchor the 100 ms window to the first key that enters an empty batch. This matches the example: foo at t=0 arms a timer for t=100, bar and foo join, the flush fires at 100, and foo at t=120 starts a new window ending at t=220. A fixed tick running forever would also work but wastes timers when idle and keeps the loop alive.
Flow
start_fetch(key, cb):- If
pendingis empty, callset_timeout(flush, 100). - Append
cbtopending[key](create the list if needed).
- If
flush():- Take a local reference
batch = pending, then setpending = {}immediately. This is the isolation step. - If
batchis empty, return (defensive; shouldn't happen). - Build the URL from the de-duplicated keys:
"/get?keys=" + ",".join(batch). - Call
http_get_request(url, on_response)whereon_responseis a closure overbatch.
- Take a local reference
on_response(resp):- For each
(key, cbs)inbatch, call every callback with the value for that key.
- For each
Code
pending = {} # key -> [callbacks] for the batch currently collecting
def start_fetch(key, callback):
global pending
if not pending:
set_timeout(flush, 100) # first key of a new window arms the timer
pending.setdefault(key, []).append(callback)
def flush():
global pending
batch, pending = pending, {} # detach: later calls build a new batch
if not batch:
return
url = "/get?keys=" + ",".join(batch.keys())
def on_response(resp):
for key, cbs in batch.items():
value = resp.get(key) # None if the server omitted the key
for cb in cbs:
cb(value)
http_get_request(url, on_response)
Trace of the example: t=0 foo arms the timer; t=30 bar and t=70 foo join the same dict; t=100 flush sends /get?keys=foo,bar and resets pending; t=120 foo sees an empty dict, arms a new timer, and ends up in the second request at t=220. Exactly two requests, with cb1, cb2, cb3 served by the first and cb4 by the second.
Design decisions and trade-offs
- Duplicates in the URL. Using dict keys sends each key once, shrinking the URL and the response. Every callback for that key still fires because the list holds them all.
- What the callback receives. I pass only that key's value, which keeps callers decoupled from batching. Passing the whole dict leaks the batching detail and invites bugs.
- Failures and missing keys. The runtime primitive shown only has a success callback, so I deliver
Nonefor keys absent from the response. If the real API exposes errors, I would call each callback with an error indicator (or a separate error callback) so that every callback runs exactly once instead of hanging forever. Retrying is a policy choice; a bounded retry of the whole batch is reasonable, but note it delays all callers in that batch. - Encoding. Keys containing commas,
&, or non-ASCII characters must be percent-encoded, and commas inside keys need escaping by the protocol (for example, encoding each key before joining). I would confirm the server's contract rather than guess. - Batch size cap. In production I would also flush early when the batch reaches a maximum key count or URL length (for example, ~2 KB URLs are a safe limit), since time-only batching can create oversized requests under bursty load.
Why it is correct on a single-threaded loop
Because each handler runs to completion, the check if not pending followed by set_timeout cannot interleave with another start_fetch, so we never arm two timers for one window. Swapping pending in flush is atomic for the same reason. The response closure captures its own batch, so a late or out-of-order response only touches callbacks from its own batch; a newer batch cannot be corrupted, and an older response cannot call callbacks twice.
On a multi-threaded runtime this breaks: the empty check, the append and the swap would need a mutex (or a lock-protected queue), and the timer would need to be armed under the same lock. Callbacks should also be invoked outside the lock to avoid deadlocks if they call start_fetch re-entrantly.
Re-entrancy note
A callback may itself call start_fetch. That is safe here: during on_response, pending is already a fresh dict, so the new request lands in the next window rather than mutating the batch being iterated.
Complexity
start_fetch: O(1) amortized.flush: O(k) for k distinct keys to build the URL.- Response handling: O(n) for n total callbacks.
- Memory: O(n) for pending callbacks, released once the batch's response is processed.
Common mistakes
- Arming a timer on every call, which produces multiple flushes per window.
- Clearing the shared dict after the response arrives instead of at send time, so keys requested in between get merged into the old batch or lost.
- Storing only one callback per key, silently dropping
cb1orcb3. - Using a single global "in-flight" structure so that overlapping responses overwrite each other.
- Forgetting to call callbacks when a key is missing from the response.