Build an Event-Loop Request Batcher with Deduplication
System DesignModel answerLast updated
Design and implement an asynchronous request coalescer that collects individual key lookups into windowed batches, handles deduplication, and correlates responses.
You need to build a request coalescer for a key-value lookup service. The service exposes an HTTP endpoint:
GET /read?keys=k1,k2,k3
Returns: {"k1": 42, "k2": 7, "k3": 105}
You have two primitives available:
httpGetAsync(path, callback)— makes an async HTTP request; callback receives(err, responseBody)parseKvs(json)— parses the JSON body into a dictionary
Your task is to implement:
fetchKey(key, callback)
This function should allow many callers to request individual keys concurrently, but intelligently batch their requests to minimize HTTP calls.
Core requirements:
- Windowed batching: Collect all requests arriving within a 100 ms window and issue a single HTTP call for that window
- Deduplication: If five callers request the same key in one window, include it only once in the HTTP request but notify all five callers
- Consistency boundary: A batch response may only satisfy callbacks for requests received before that batch was sent; requests arriving afterward belong to the next batch
- Concurrent batches: Support multiple in-flight HTTP requests without mixing up which response satisfies which callbacks
- Error handling: Define behavior for missing keys, partial failures, HTTP errors, timeouts, and request cancellation
- Backpressure: Prevent unbounded memory growth under load
Deliverables:
- Data structures (what state do you track? how do you correlate responses to callbacks?)
- Control flow (when do you start/flush a batch? how do timers work?)
- Edge case policies (missing keys, retries, cancellation, overload)
- Complexity analysis (time/space per operation)
- Key concurrency pitfalls in a single-threaded event loop
- Brief test strategy
Assume you have setTimeout(ms, fn) and clearTimeout(handle) available. The environment is single-threaded with an event loop (like Node.js or Python asyncio).
Hints
Hint 1
The consistency boundary is enforced by atomically swapping the pending batch with an empty one when you flush—any request after that line goes into the next batch
Hint 2
Correlation is simple if each HTTP callback captures its own frozen batch in a closure; you don't need request IDs or a global map
Hint 3
Each individual request needs its own timeout so a slow backend can't hold callers indefinitely, but the batch also needs retry logic for transient failures
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifications and Assumptions
Before designing, confirm these points:
- Timer primitives:
setTimeout(ms, fn) -> handleandclearTimeout(handle)are available - Callback signature: User callbacks are
callback(err, value), invoked exactly once - Window start: The 100 ms timer starts when the first request arrives into an empty batch, not at fixed wall-clock intervals
- Batch size cap: A maximum key count (e.g., 500) or URL length limit forces early flush
- Concurrency cap: Limit in-flight HTTP requests (e.g., 4) to protect the backend
- Scale estimate: ~10k requests/sec, 100-200 ms backend latency → roughly 10 batches/sec with 1-3 in flight
High-Level Design
The batcher maintains three logical states:
- Pending: The currently open batch accepting new requests
- In-flight: Batches dispatched to the backend, awaiting responses
- Queued: Closed batches waiting for an available in-flight slot (backpressure queue)
Each request gets a unique waiter object that holds its callback and a done flag for exactly-once semantics.
Data Structures
State:
pending: Map<key → List<Waiter>>— the open batch; map structure gives natural deduplicationtimer: TimerHandle | null— the 100 ms window timer for the pending batchready: Queue<Batch>— closed batches waiting to dispatchinflight: integer— count of active HTTP requests
Waiter:
{
key: string
callback: function(err, value)
done: boolean // exactly-once guard
timeoutHandle: TimerHandle
}
Batch:
{
requests: Map<key → List<Waiter>> // frozen snapshot of pending
retryCount: integer
}
Control Flow
On fetchKey(key, callback):
- Create a Waiter with the callback
- Append to
pending[key](or create the list if new) - Arm a per-request timeout (e.g., 2000 ms) to prevent indefinite waiting
- If
pendingwas empty, start the 100 ms window timer - If
pending.size >= maxKeys, flush immediately - Return a handle for cancellation
On window timer expiry or size cap:
- Flush: Atomically swap
batch = pending; pending = {}and clear the window timer- This swap is the consistency guarantee: any request after this line enters a new batch
- Remove keys whose waiters are all cancelled/timed-out (don't fetch dead keys)
- If
inflight < maxInflight, dispatch immediately; otherwise enqueue inready
On dispatch:
- Build URL:
/read?keys=+ URL-encode and join keys - Call
httpGetAsync(url, responseHandler) - Increment
inflight - The response handler captures the batch in its closure (this is how correlation works—no IDs needed)
On HTTP response:
- Parse body with
parseKvs - For each key in the batch:
- If present in response and waiter not done: call
waiter.callback(null, value), setdone=true, clear timeout - If missing: call
waiter.callback(KeyNotFoundError(key))
- If present in response and waiter not done: call
- On parse or network error: retry with exponential backoff up to
maxRetries, then fail all live waiters - Decrement
inflight - If
readyis non-empty, dispatch the next batch
Edge Cases and Policies
Missing keys: Deliver KeyNotFoundError to the waiter. This is not a transport failure, so no retry.
HTTP failures (network, 5xx): Retry the batch with exponential backoff (50 ms, 100 ms, 200 ms) up to maxRetries. The same frozen batch is reused, restricted to keys with live waiters. After exhausting retries, fail all remaining waiters with the transport error.
Partial success: If the body parses but some keys are absent, resolve present keys successfully and fail absent keys individually.
Timeouts: Each waiter has its own timeout. When it fires, invoke callback(TimeoutError) and set done=true. A late response sees done=true and skips that waiter.
Cancellation: handle.cancel() immediately invokes callback(CancelledError) and sets done=true. If all waiters for a key are cancelled before flush, omit that key from the batch.
Backpressure: Cap ready queue length (e.g., 100 batches). If exceeded, immediately fail new requests with OverloadedError rather than growing memory unbounded.
Concurrency Pitfalls (Single-Threaded Event Loop)
- Re-entrant calls: A callback might call
fetchKeyagain. The atomic swap ensures these go into the next batch, not the one being processed. - Timer ordering: Flushing clears the window timer before swapping, preventing a race where the timer fires during dispatch.
- Exactly-once delivery: The
doneflag prevents double-calls when timeout and response race. - Closure capture: Each HTTP callback captures its own batch, so concurrent in-flight requests never interfere.
Complexity
Time per fetchKey: O(1) amortized—append to a list and set a timer.
Space: O(P + B·K) where P is pending waiters, B is in-flight batches, K is keys per batch. With caps (maxInflight=4, maxKeys=500, maxQueued=100), space is bounded.
Flush: O(K) to iterate keys and build the URL.
Response: O(K·W) where W is average waiters per key (usually 1-3).
Test Strategy
- Basic batching: Issue 5 requests in quick succession; verify a single HTTP call
- Deduplication: Request the same key 3 times; verify one fetch, three callbacks with the same value
- Consistency boundary: Request key A, flush, request key B; verify B is in the next batch
- Concurrent batches: Delay responses; issue requests for batches 1, 2, 3; resolve out of order; verify each response only satisfies its own batch
- Missing keys: Request a key not in the response; verify
KeyNotFoundError - Timeout: Delay the response beyond the per-request timeout; verify callback receives
TimeoutError; verify late response is ignored - Cancellation: Cancel a request before flush; verify key is omitted if it's the only waiter
- Retry: Simulate network failure; verify exponential backoff and eventual success or final failure
- Backpressure: Saturate with requests; verify
OverloadedErrorafter queue cap - Re-entrance: From a callback, issue another request; verify it enters a new batch
Why This Design Works
The atomic swap of pending gives a clean consistency boundary without locks. Closure-captured batches eliminate the need for request IDs. Per-request timeouts and a done flag give exactly-once semantics even under races. The three-state model (pending, queued, in-flight) provides backpressure and caps resource usage. This is a production-grade pattern used in DataLoader (GraphQL), HTTP/2 request coalescing, and database query batchers.