Sub topic 14
Scheduling and batching
This chapter assumes you know the pipeline from earlier chapters: events enter through an ingestion API, go onto queues, and channel workers send them through providers. It also assumes you can read short Python snippets. Here we add two controls that change when and how many messages go out.
Why schedule and batch
Not every notification should be sent the moment its event arrives.
- Scheduling delays a send until a chosen time. Examples are a reminder one hour before an appointment, or a message held until quiet hours end.
- Batching combines several events for one user into a single message. Examples are a daily digest or "5 people liked your post".
Both reduce noise for the user and spread load on your providers.
Scheduling
A scheduler stores a notification with a send_at time and releases it when that time arrives. A common design keeps scheduled items in a store ordered by time, and a poller moves due items onto the normal queue.
import heapq
import time
class Scheduler:
def __init__(self):
self._heap = [] # (send_at, event_id, event)
def schedule(self, event_id, event, send_at):
heapq.heappush(self._heap, (send_at, event_id, event))
def pop_due(self, now=None):
now = time.time() if now is None else now
due = []
while self._heap and self._heap[0][0] <= now:
due.append(heapq.heappop(self._heap))
return due
s = Scheduler()
s.schedule("evt-1", {"type": "reminder"}, send_at=100)
s.schedule("evt-2", {"type": "reminder"}, send_at=50)
print([item[1] for item in s.pop_due(now=75)])This prints ['evt-2']. In production the heap would be a durable store, such as a database table indexed on send_at or a sorted set, because an in-memory list is lost on restart.
Scheduling gotchas
- Store times in UTC and keep the user's time zone separately. Convert only when you compute quiet hours or "9 am local".
- The poller may run on several workers. Claim each due item atomically, and reuse the idempotency key from the earlier chapter so a double claim does not cause a double send.
- Re-check preferences and opt-outs at send time, not only at schedule time. A user may opt out in between.
Batching
Batching groups events by a key, usually user and type, and flushes the group when a window closes or a size limit is reached.
from collections import defaultdict
class Batcher:
def __init__(self, max_size=5):
self.max_size = max_size
self._groups = defaultdict(list)
def add(self, user_id, kind, item):
key = (user_id, kind)
self._groups[key].append(item)
if len(self._groups[key]) >= self.max_size:
return self.flush(key)
return None
def flush(self, key):
return key, self._groups.pop(key, [])
b = Batcher(max_size=3)
for name in ["Ana", "Ben", "Chi"]:
result = b.add("user-42", "like", name)
print(result)The third call reaches the size limit and returns (('user-42', 'like'), ['Ana', 'Ben', 'Chi']). A real batcher also flushes on a timer, so a group of two does not wait forever.
Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Longer batch window | Fewer messages, less noise | Added delay |
| Shorter batch window | Faster delivery | More messages |
| Precise scheduling | On-time sends | Polling load and clock concerns |
Exercise
A user receives a digest scheduled for 8 am, but opted out of email at 7 am. What should the system do, and why?
Show answer
It should skip the email at send time. Preferences must be re-checked when the item is released, because the schedule was created before the opt-out.