Batched API Delivery with Delay-Aware Retries
Heaps, Sorting & SearchModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1. Walk through the list in steps of 5 and call the client once per slice. The client returns one result per item, so I zip the slice with the response (or look results up by an id) and record each outcome. The number of calls is ceil(n / 5), which is the minimum possible. The last slice is simply shorter.
Part 2. Failures now bring in time, so I split the work into two collections:
ready: a FIFO queue (deque) of items that may be sent right now. It starts with all input items.waiting: a min-heap of(retry_at, seq, item)for items cooling down.seqis a tie-breaker so items themselves never need to be comparable.
Main loop:
- Read
nowfrom a monotonic clock. Pop everything fromwaitingwithretry_at <= nowand push it toready. - If
readyis non-empty, take up to 5 items and send them in one call. For each result: success is recorded; failure with delaydpushes(now_after_response + d, seq, item)ontowaiting, provided the attempt count is under the cap, otherwise the item is recorded as permanently failed. - If
readyis empty butwaitingis not, sleep forwaiting[0].retry_at - now(the time until the earliest item is eligible) and loop again. - Stop when both collections are empty.
This means a failed item never blocks others: healthy items keep going out in full batches, and a failed item re-enters the flow exactly when its cooldown ends.
Design decisions and trade-offs
- Mixing retries with fresh items: I allow it. It keeps batches full and minimizes calls. If the service needed batches of homogeneous items, I would keep separate queues.
- Cooldown start: measured from when the response is received, using the timestamp taken right after the call returns. Using the pre-call time would risk retrying too early.
- Batch filling vs. latency: if only one item is ready, I send it immediately rather than waiting to fill the batch. Waiting for a full batch saves calls but adds latency, and could stall at the end. A small linger window is a reasonable extension if calls are expensive.
- Whole-call failure (timeout, 5xx): treat every item in that batch as failed with a default backoff (for example exponential with jitter), counting it as an attempt. Do not assume the items were not processed unless the API is idempotent; ideally send an idempotency key per item.
- Termination: a max attempt count (and optionally an overall deadline) guarantees the loop ends. Items that exhaust it are returned in a
failedreport with their last error. - Clock: use
time.monotonic(), not wall-clock time, so system clock adjustments do not break scheduling. Injectclockandsleepso tests can use a fake clock and run instantly. - Ordering: results are stored by original index, so the output keeps input order even though delivery order changes after retries.
Code
import heapq
import time
from collections import deque
BATCH = 5
def deliver_all(items, client, max_attempts=5,
clock=time.monotonic, sleep=time.sleep):
"""
client.send(batch) -> list of dicts aligned with batch:
{"ok": True} or {"ok": False, "retry_after": seconds}
Returns (results, failed) where results[i] is True/False for items[i].
"""
results = [None] * len(items)
attempts = [0] * len(items)
ready = deque(range(len(items))) # indices ready to send
waiting = [] # heap of (retry_at, seq, index)
seq = 0
while ready or waiting:
now = clock()
while waiting and waiting[0][0] <= now:
_, _, idx = heapq.heappop(waiting)
ready.append(idx)
if not ready:
sleep(max(0.0, waiting[0][0] - now))
continue
batch_idx = [ready.popleft() for _ in range(min(BATCH, len(ready)))]
batch = [items[i] for i in batch_idx]
try:
responses = client.send(batch)
except Exception:
responses = [{"ok": False, "retry_after": 1.0}] * len(batch)
after = clock()
for i, resp in zip(batch_idx, responses):
attempts[i] += 1
if resp["ok"]:
results[i] = True
elif attempts[i] >= max_attempts:
results[i] = False
else:
seq += 1
heapq.heappush(waiting, (after + resp["retry_after"], seq, i))
failed = [items[i] for i, r in enumerate(results) if r is False]
return results, failed
Complexity
Let n be the number of items and R the total number of retries (at most n * max_attempts).
- Each submission or re-submission costs one heap push and one pop:
O(log w)wherewis the number of waiting items. - Total time is
O((n + R) log n)excluding the time actually spent sleeping and in the API. - Number of calls is at least
ceil((n + R) / 5)and close to it when retries rejoin full batches. - Space is
O(n).
Common mistakes
- Sleeping for the failed item's delay inside the loop, which stalls every other item.
- Busy-waiting on
while time < retry_at, which burns CPU. - Sleeping a fixed interval instead of until the earliest eligible time.
- Measuring cooldown from before the call, causing early retries.
- Using the wall clock instead of a monotonic one.
- Putting non-comparable items directly in the heap (tie on time raises an error); use a sequence number.
- Retrying forever with no attempt cap, or losing items when a whole call raises.
- Mapping results by assumption rather than by position or id, so outcomes get attached to the wrong item.
Testing
Use a fake client that scripts failures with specific delays and a fake clock whose sleep advances time. Assert that no item is sent before its allowed time, that every batch has at most 5 items, that every item ends up in exactly one final state, and that the number of calls matches expectation.