Batched Notification Sender with Cooldown-Aware Retries
Heaps, Sorting & SearchModel answerLast updated
Push messages through a provider that accepts at most 5 per call, and retry each failure only after its own cooldown expires, with an attempt cap and no busy-waiting.
You are building the delivery layer for a notification service. All messages go out through an external provider with two rules:
- A single call accepts at most 5 messages.
- For each message in the call, the provider answers
(True, payload)on success, or(False, cooldown_seconds)on failure. The cooldown is how long you must wait, counted from when you received that response, before that particular message may be sent again.
Responses come back in the same order as the messages in the call.
Part 1: Plain batching
Write send_all(messages, send_batch). It must deliver every message using the minimum number of calls allowed by the size limit. Nothing may be skipped or sent twice, and the final, smaller group must be handled. Return one outcome per message, in input order.
def send_all(messages: list, send_batch) -> list:
"""send_batch takes a list of up to 5 messages and returns one
(ok: bool, payload) pair per message, in the same order."""
Part 2: Retries with per-message cooldowns
Write send_with_retries(messages, send_batch, max_attempts=5). Failed messages are retried once their own cooldown has passed. Requirements:
- A message in cooldown must not hold up messages that are ready.
- Ready messages keep flowing in batches of up to 5.
- When nothing is ready, the program must not spin on the clock.
max_attemptscounts every send of a message, including the first. A message that is still failing when it reaches the cap is reported as a permanent failure, as(False, last_payload).
def send_with_retries(messages: list, send_batch, max_attempts: int = 5) -> list:
...
Example
Take a fake provider where message i fails its first i % 3 attempts, each time reporting a 0.01 s cooldown, and then succeeds.
messages = list(range(12))
# Every message ends as (True, "ok:<i>"), after 1, 2 or 3 attempts depending on i % 3.
Constraints
- Up to
10^4messages. - Cooldowns are non-negative numbers of seconds. They are tiny in tests but the code must work unchanged for multi-second values.
- Return results in the original input order.
What to cover in your answer
Explain your data structures, how you avoid busy-waiting, the complexity, and the edge cases. Also say which clarifying questions you would ask, for example whether calls may run concurrently.
Hints
Hint 1
Part 1 is just slicing the list in steps of 5. The only thing to get right is writing each response back to the original position, using the slice's starting offset.
Hint 2
Keep two collections in Part 2: a queue of messages that can be sent now, and a min-heap keyed by the time each cooling-down message becomes eligible. The heap's top always tells you the earliest wake-up time.
Hint 3
When the ready queue is empty, sleep for exactly (earliest ready time - current time), then move every due entry from the heap to the ready queue. Take the cooldown timestamp right after the response arrives, and use a per-message attempt counter to enforce the cap.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
The two parts have different shapes, so I would keep them separate. Part 1 is pure chunking. Part 2 is a small scheduler: messages are either ready or cooling down, and the right structure for cooling-down items is a min-heap ordered by eligibility time.
Part 1: chunking
Step through the list in strides of 5, send each slice, and store each outcome at start + offset. Because the provider preserves order inside a call, no other bookkeeping is needed. The number of calls is ceil(n / 5), which is the minimum possible, and the last slice may simply be shorter. An empty list makes zero calls.
BATCH = 5
def send_all(messages, send_batch):
results = [None] * len(messages)
for start in range(0, len(messages), BATCH):
chunk = messages[start:start + BATCH]
for k, outcome in enumerate(send_batch(chunk)):
results[start + k] = outcome
return results
Part 2: readiness-driven scheduling
State
ready: a FIFO deque of message indices that may be sent now. It starts with every index.cooling: a min-heap of(eligible_at, index).tries[i]: how many times messageihas been sent.results[i]: the final outcome once the message is finished.
Loop, while ready or cooling is non-empty
- Move every heap entry with
eligible_at <= nowintoready. - If
readyis still empty, sleep forcooling[0].eligible_at - now(clamped at 0) and go round again. This is the only place we wait, and we wait exactly as long as needed, with no fixed polling interval. - Otherwise pop up to 5 indices and send them in one call.
- Read the clock once after the response arrives, since the cooldown is measured from receipt. For each outcome, increment
tries. If it succeeded, ortrieshas reachedmax_attempts, record the final result. Otherwise push(received + cooldown, index)onto the heap.
import heapq
import time
from collections import deque
BATCH = 5
def send_with_retries(messages, send_batch, max_attempts=5,
now=time.monotonic, sleep=time.sleep):
n = len(messages)
results = [None] * n
tries = [0] * n
ready = deque(range(n))
cooling = [] # (eligible_at, index)
def release_due():
t = now()
while cooling and cooling[0][0] <= t:
ready.append(heapq.heappop(cooling)[1])
while ready or cooling:
release_due()
if not ready:
sleep(max(0.0, cooling[0][0] - now()))
continue
idxs = [ready.popleft() for _ in range(min(BATCH, len(ready)))]
outcomes = send_batch([messages[i] for i in idxs])
received = now()
for i, (ok, payload) in zip(idxs, outcomes):
tries[i] += 1
if ok or tries[i] >= max_attempts:
results[i] = (ok, payload)
else:
heapq.heappush(cooling, (received + payload, i))
return results
The clock and sleep functions are injectable. Tests can then use a fake clock that advances instantly, which keeps them fast and deterministic.
Why this design
- Heap instead of scanning. Finding the next message to wake is
O(log n)per operation instead ofO(n), and the heap top gives the exact sleep duration. - No head-of-line blocking. A message with a 30 s cooldown sits in the heap while others with short cooldowns, or fresh messages, keep flowing.
- Exact sleeping. Sleeping until the earliest
eligible_atneither burns CPU nor oversleeps. Messages that become due at the same moment are drained together and can share a batch. - Same-call guarantees. A message is in at most one place at a time (
ready,cooling, or finished), so it cannot be sent twice concurrently.
Complexity
Each message enters the heap at most max_attempts - 1 times. Total heap work is O(n * max_attempts * log n). Provider calls number at most about n * max_attempts / 5 in the worst case where everything keeps failing, plus a few extra from partial batches. Space is O(n).
Worked example
With messages 0..11 and i % 3 initial failures, the first two calls send 0-4 and 5-9, and a third sends 10-11. Messages with i % 3 == 0 succeed immediately. The rest go to the heap with a roughly 10 ms cooldown. The loop then sleeps about 10 ms, releases them, and sends them in batches. Messages with i % 3 == 2 come around once more. Each message finishes as (True, "ok:<i>") after exactly (i % 3) + 1 attempts.
Edge cases and common mistakes
- Empty input. Both collections are empty, so the loop never runs and the result is
[]. - Zero cooldown.
eligible_atequals the receive time, so the entry is released on the next iteration with no sleep. - Attempt cap. The cap includes the first send. With
max_attempts=1a failure is final straight away. The last failure's payload (its cooldown) is kept in the result. - Mistake: measuring cooldown from send time. Use the time the response arrived, as the spec states. Otherwise you may retry too early.
- Mistake: calling
now()once per message in a way that drifts. Reading the clock once per response batch is simpler and consistent. - Mistake:
while True: check clock. This busy-waits. Sleep until the heap's earliest time instead. - Mistake: assuming response order differs from request order. Zip the indices with the outcomes of the same call and nothing else.
- Mistake: re-sending finished messages. Only unfinished ones are ever re-queued.
Trade-offs and follow-ups
- Partial batches. I send whatever is ready, up to 5, rather than waiting to fill a batch. This minimises latency but can use more calls. If call cost dominates, you could wait a short, bounded time to coalesce.
- Fairness. FIFO
readymeans retried messages queue behind fresh ones, which prevents starvation in either direction. - Concurrency. To allow several calls in flight, put the scheduler behind a lock, or use an async loop where a single task owns the heap and worker tasks perform calls. Sleep becomes
await asyncio.sleepor waiting on a condition with a timeout, so a newly pushed earlier deadline can wake the scheduler. - Backoff and jitter. If the provider returned no cooldown, you would substitute exponential backoff with jitter to avoid synchronised retry storms.
- Overall deadline. A deadline could be added by finishing any message whose next
eligible_atwould exceed it.