KatInterview

Batched API Delivery with Delay-Aware Retries

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchbatchingretryscheduling

Last updated

Deliver a list of requests through an API capped at five per call, retrying failures only after each request's own cooldown, without busy-waiting or blocking on one failure.

You have a list of items to push to a remote service. The service is batch-oriented: one call accepts at most 5 items, sent together in a single payload. The service is represented by a dummy client that you can replace with a fake in tests.

Part 1: Plain batching

Write a function that takes the full list of items and delivers all of them to the service, using as few calls as the limit of five allows.

Your solution should:

  • Split the list correctly, including a last batch that has fewer than five items. No item may be skipped or sent twice.
  • Match every per-item result in a response to the item that caused it.
  • Hide the service behind a small interface so the delivery logic can be tested against a fake.

Part 2: Retrying with a cooldown

Some items are rejected. For each rejected item, the response tells you how many seconds must pass before that specific item may be submitted again. Extend your solution so that:

  • Every rejected item is eventually retried, and never earlier than its cooldown permits.
  • Other items continue to be sent while rejected ones are waiting.
  • Calls are filled up to five items using whatever is currently eligible.
  • When nothing is eligible, the program waits efficiently: no busy loop, and no blocking sleep tied to a single failed item.

Decide and state your assumptions on points such as:

  • Is the cooldown counted from the moment the response arrives?
  • Can a retried item share a call with items that have not been sent yet?
  • Can an item be rejected repeatedly? What happens if it never succeeds, and what happens if a whole call fails (for example a timeout)?
  • Should results come back in the original input order?

Explain your approach, give its complexity, and write the code.

Hints

Hint 1

Part 1 is just slicing the list in steps of 5. The harder question is how to keep track of which response entry belongs to which item, for example by using an id or the position within the batch.

Hint 2

Keep two structures: a queue of items that are ready to send now, and a min-heap keyed by the earliest allowed retry time for items that are cooling down. Before building each batch, move everything whose time has come from the heap to the ready queue.

Hint 3

When the ready queue is empty but the heap is not, sleep only until the earliest timestamp at the top of the heap. Use a monotonic clock and inject the clock and sleep function so tests do not really wait. Add a maximum attempt count so the loop is guaranteed to end.