KatInterview

Build an Event-Loop Request Batcher with Deduplication

System DesignModel answer
HardModel answerSystem Designasyncbatchingevent-loop

Last 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:

  1. Windowed batching: Collect all requests arriving within a 100 ms window and issue a single HTTP call for that window
  2. Deduplication: If five callers request the same key in one window, include it only once in the HTTP request but notify all five callers
  3. 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
  4. Concurrent batches: Support multiple in-flight HTTP requests without mixing up which response satisfies which callbacks
  5. Error handling: Define behavior for missing keys, partial failures, HTTP errors, timeouts, and request cancellation
  6. 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