Sub topic 14
Scheduling and batching
This chapter covers two ways to change when and how often a notification reaches a user. Scheduling delays a send until a chosen time. Batching combines several events into one send. It assumes you know the queue and worker model from the earlier chapters, can read short Python snippets, and have used a key-value store or a database index.
Why both matter
Some notifications should not go out the moment the event arrives. A reminder fires 24 hours before an appointment. A marketing message waits until 9:00 in the user's own time zone. A non-critical alert that arrives at 2 a.m. waits until quiet hours end. These cases need scheduling.
Other notifications are better merged. Twenty "someone liked your photo" pushes in ten minutes are noise. One message saying "20 people liked your photo" is better. This is batching, usually called a digest.
The two features share one mechanism: something has to wake up later and act. Batching also needs scheduling to decide when to flush a buffer.
Scheduling
Where scheduled work waits
A normal channel queue delivers messages as soon as workers are free. Scheduled work needs a store that is ordered by due time. Common options:
| Option | How it works | Fits | Limits |
|---|---|---|---|
| Queue with native delay | Message becomes visible after N seconds | Short delays | Many queues cap the delay (SQS allows 15 minutes) |
| Sorted set in a key-value store | Score is the due timestamp, a poller reads items with score at or below now | Medium volume, delays of minutes to days | Needs persistence settings and care on failover |
| Database table with an index on `send_at` | Poller selects rows where `send_at <= now` and `status = 'pending'` | Long delays, cancellation, auditing | Polling load grows with table size |
Many systems combine them. The database is the source of truth for long-lived schedules, and a scheduler loads the next few minutes of work into a fast structure.
The scheduler flow
A scheduler process polls for due items, claims them, and pushes them onto the normal channel queues. The workers do not know the send was scheduled.
Here is a minimal in-memory version of the due-time store. It shows the core idea: order by due time and pop only what is ready.
import heapq
import itertools
class DelayQueue:
def __init__(self):
self._heap = []
self._counter = itertools.count() # tie-breaker so items are never compared
def schedule(self, due_ts, item):
heapq.heappush(self._heap, (due_ts, next(self._counter), item))
def pop_due(self, now_ts, limit=100):
ready = []
while self._heap and self._heap[0][0] <= now_ts and len(ready) < limit:
ready.append(heapq.heappop(self._heap)[2])
return ready
q = DelayQueue()
q.schedule(1000, "reminder-1")
q.schedule(500, "reminder-2")
print(q.pop_due(now_ts=600)) # ['reminder-2']
print(q.pop_due(now_ts=1200)) # ['reminder-1']The limit matters. If a scheduler was down for an hour, it must not dump the whole backlog onto the queue at once. Pop in bounded pages and let rate limiting absorb the rest.
Deferring for quiet hours
Quiet hours are evaluated in the user's time zone, so store the zone name (such as Europe/Berlin), not a fixed UTC offset. Offsets change with daylight saving time. The function below returns the UTC time at which a non-critical notification may be sent. It handles an overnight window, where the start is later than the end.
from datetime import datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo
def next_send_time(now_utc, tz_name, quiet_start=time(22, 0), quiet_end=time(7, 0)):
zone = ZoneInfo(tz_name)
local = now_utc.astimezone(zone)
t = local.time()
in_quiet = t >= quiet_start or t < quiet_end
if not in_quiet:
return now_utc
end_date = local.date() if t < quiet_end else local.date() + timedelta(days=1)
end_local = datetime.combine(end_date, quiet_end, tzinfo=zone)
return end_local.astimezone(timezone.utc)
now = datetime(2026, 11, 26, 23, 30, tzinfo=timezone.utc)
print(next_send_time(now, "UTC")) # 2026-11-27 07:00:00+00:00Compare this with choose_channels from the preferences chapter. That function drops intrusive channels during quiet hours. This function keeps the intrusive channels but delays the send. Which one to use is a product decision. Many systems deliver in-app immediately and schedule the push for the morning.
Scheduling gotchas
- Re-check at send time. The user may opt out or change preferences between scheduling and sending. The worker must evaluate preferences again before calling the provider.
- Cancellation. A reminder for an appointment that was cancelled must not fire. Keep a stable
schedule_idso you can mark the row cancelled, and have the worker check that status. - Multiple scheduler instances. For availability you will run more than one. Claim items atomically (for example, an
UPDATE ... WHERE status = 'pending'that reports rows changed, or a set-if-absent key), and use the idempotency key from the earlier chapter as a second guard. - Top-of-the-hour spikes. A campaign set for 09:00 across a million users creates a burst. Add random jitter of a few minutes, or spread sends across a window.
- Clock skew. Compare due times using one clock, the store's or the scheduler's, not each worker's local time.
Batching
Digest strategies
| Strategy | Flush trigger | Example |
|---|---|---|
| Time window | Window closes after N minutes or at a fixed hour | Daily summary at 08:00 |
| Count threshold | Buffer reaches N items | Flush at 20 likes |
| Collapse key | A newer event replaces an older one | Only the latest "sync status" |
Most systems combine a window with a count cap, so a burst flushes early and a trickle still flushes eventually. Buffers are keyed by user and by a digest key, such as user-42:post-9:likes.
class DigestBuffer:
def __init__(self, window_s=300, max_items=20):
self.window_s = window_s
self.max_items = max_items
self._open = {} # key -> (opened_at, items)
def add(self, key, event, now):
opened, items = self._open.setdefault(key, (now, []))
items.append(event)
if len(items) >= self.max_items:
return self._open.pop(key)[1]
return None
def flush_due(self, now):
due = [k for k, (opened, _) in self._open.items() if now - opened >= self.window_s]
return {k: self._open.pop(k)[1] for k in due}
buf = DigestBuffer(window_s=300, max_items=3)
key = "user-42:post-9:likes"
buf.add(key, "like-1", now=0)
buf.add(key, "like-2", now=10)
print(buf.add(key, "like-3", now=20)) # ['like-1', 'like-2', 'like-3']
buf.add(key, "like-4", now=30)
print(buf.flush_due(now=400)) # {'user-42:post-9:likes': ['like-4']}Batching gotchas
- Critical events bypass batching. A security alert or a one-time code must not wait in a digest. Check
prioritybefore buffering. - Buffers must survive crashes. This in-memory class loses events if the process dies. In production, keep buffers in a durable store and use the scheduler to fire the flush.
- Idempotency of the digest. Build the key from the user, the digest key, and the window start, so a retried flush does not send the digest twice.
- Latency is the price. A five-minute window adds up to five minutes of delay. Choose windows per notification type.
- Template changes. A digest needs its own template that renders a list and a count, and handles very long lists ("and 14 more").
Batching at the provider
A different kind of batching reduces calls to providers. Some email and push APIs accept many recipients per request. This cuts overhead and helps with provider rate limits. The user still receives separate messages. Handle partial failure: the response usually reports a status per recipient, and you must retry only the failed ones, not the whole call.
Choosing between them
Use scheduling when the content is known and only the time changes. Use batching when several events should become one message. Use provider batching when you only want fewer network calls. They compose: a digest is a buffer whose flush is a scheduled job, and its result can then be sent in a provider batch.
Exercise
A user in a time zone with daylight saving time has quiet hours from 22:00 to 07:00. Why should you store the zone name rather than a UTC offset, and what must a worker do when a deferred push becomes due?
Show answer
A zone name lets the code compute the correct local time on each date, so quiet hours stay at 22:00 to 07:00 local time across daylight saving changes, while a fixed offset becomes wrong twice a year. When the deferred push is due, the worker must re-check the user's current preferences, opt-outs, and the state of the underlying object before sending, because they may have changed since scheduling.
Exercise
A digest buffer holds likes in memory and flushes after a 5-minute window. The service restarts, and the buffered likes are lost. Name two changes that fix this and one more that stops a retried flush from sending the digest twice.
Show answer
Keep the buffer in a durable shared store instead of process memory, and trigger the flush from a scheduled job so any instance can run it after a restart. To avoid duplicates, build an idempotency key from the user, the digest key, and the window start, and claim it before sending.