Video in progress
You need to send millions of reminders to users at a set time (for example, "your lesson starts in 1 hour"). How do you build this?
Each reminder is stored in the database with a due_at, picked up in batches by indexed time and split between workers with SKIP LOCKED; sending goes through a queue and is idempotent. A separate in-memory timer or cron per reminder is out of the question.
📖 Answer
The first solutions that come to mind don't work at large volume:
TaskScheduler.schedule(...)per reminder lives in memory, is lost when the pod restarts, and millions of tasks fill the heap.- Running
SELECT * FROM reminder WHERE due_at <= now()every minute with ShedLock means one instance does everything, and at a peak (200 thousand reminders at 9:00) it falls behind.
A scheme that works:
CREATE TABLE reminder (
id bigserial PRIMARY KEY,
due_at timestamptz NOT NULL,
status text NOT NULL DEFAULT 'PENDING',
payload jsonb NOT NULL,
attempts int NOT NULL DEFAULT 0
);
CREATE INDEX ix_reminder_due ON reminder(due_at) WHERE status = 'PENDING';
The worker in every pod:
UPDATE reminder SET status = 'PROCESSING'
WHERE id IN (
SELECT id FROM reminder
WHERE status = 'PENDING' AND due_at <= now()
ORDER BY due_at LIMIT 500
FOR UPDATE SKIP LOCKED)
RETURNING id, payload;
SKIP LOCKED: workers don't wait for each other and don't pick up the same row twice. If you add pods, throughput grows linearly.- The partial index covers only the pending rows, so it stays fast even when the table grows.
- Rows stuck in
PROCESSING(the worker died) are taken back based onupdated_at. - The send itself is a message to the notification service;
reminder.idis the idempotency key.
Other aspects:
- Cancelling and rescheduling: if the lesson time changes, update or delete the row. That is much harder with messages already put on a queue (for example, delayed RabbitMQ messages); the row in the database gives you control.
- Peaks: bunching at the top of the hour is normal. Whether a small delay (1–2 minutes) is allowed is agreed with the business; if needed, prepare the sending ahead of time.
- Time zone:
due_atis always in UTC (timestamptz), and the user's zone is used only in the calculation. - Cleanup: use partitions (by month) for sent ones and drop old partitions, because DELETE is heavy on millions of rows.
If the volume is tens of millions and above, you'd look at time-bucketed storage or dedicated tools (for example Temporal timers), but PostgreSQL + SKIP LOCKED is enough for most systems and is the simplest operationally.
Sign up to mark studied questions and save your progress.