Database Events, Queues and Notifications
What you will learn
- Why programs sometimes need to react to changes in data
- Polling versus notifications
- How to use a table as a job queue and claim jobs safely
- The outbox pattern for reliable events
- What a notification feature such as PostgreSQL
NOTIFYoffers
1. Reacting to change
Sometimes a program must do something after data changes: send a receipt email after an order, resize a photo after an upload, update a search index after an edit. The database holds the data, but how does the other program find out?
| Approach | How it works | Cost |
|---|---|---|
| Polling | the program asks every few seconds "anything new?" | simple, but wasteful and always a little late |
| Notification | the database pushes "something changed" | quick, but needs support and does not store history |
| Queue / outbox table | changes are written as rows to be processed | reliable and easy to understand |
2. A table as a job queue
This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds small tables and a trigger of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.
The simplest queue is a table of jobs with a status. A worker program picks one waiting job, marks it running, does it, then marks it done. The danger: two workers must never take the same job. First, the naive way, in two steps (read the next waiting job, then mark it):
CREATE TABLE jobs (id INTEGER PRIMARY KEY, task TEXT, status TEXT NOT NULL DEFAULT 'waiting', worker TEXT);
INSERT INTO jobs (task) VALUES ('send email 1'), ('send email 2'), ('resize photo');
SELECT id, task FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1;
id task
-- ------------
1 send email 1
(1 row)
UPDATE jobs SET status = 'running', worker = 'w1' WHERE id = 1 AND status = 'waiting';
SELECT id, status, worker FROM jobs ORDER BY id;
id status worker
-- ------- ------
1 running w1
2 waiting NULL
3 waiting NULL
(3 rows)
CREATE TABLE jobs (id INTEGER PRIMARY KEY, task TEXT, status TEXT NOT NULL DEFAULT 'waiting', worker TEXT);
INSERT INTO jobs (task) VALUES ('send email 1'), ('send email 2'), ('resize photo');
SELECT id, task FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1;
id task
-- ------------
1 send email 1
(1 row)
UPDATE jobs SET status = 'running', worker = 'w1' WHERE id = 1 AND status = 'waiting';
SELECT id, status, worker FROM jobs ORDER BY id;
id status worker
-- ------- ------
1 running w1
2 waiting NULL
3 waiting NULL
(3 rows)
CREATE TABLE jobs (id INTEGER PRIMARY KEY, task TEXT, status TEXT NOT NULL DEFAULT 'waiting', worker TEXT);
INSERT INTO jobs (task) VALUES ('send email 1'), ('send email 2'), ('resize photo');
SELECT id, task FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1;
id task
-- ------------
1 send email 1
(1 row)
UPDATE jobs SET status = 'running', worker = 'w1' WHERE id = 1 AND status = 'waiting';
SELECT id, status, worker FROM jobs ORDER BY id;
id status worker
-- ------- ------
1 running w1
2 waiting NULL
3 waiting NULL
(3 rows)
This code reads and then writes in two steps. With a server database and many workers at once, two workers could read the same waiting row before either writes (a race, lesson 6.4). The extra test AND status = 'waiting' helps, but the cleanest fix is to claim in a single statement. Put the jobs back and let two workers take turns until the queue is empty:
UPDATE jobs SET status = 'waiting', worker = NULL;
UPDATE jobs SET status = 'running', worker = 'w1'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
1 send email 1
(1 row)
UPDATE jobs SET status = 'running', worker = 'w2'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
2 send email 2
(1 row)
UPDATE jobs SET status = 'running', worker = 'w1'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
3 resize photo
(1 row)
The fourth claim finds the queue empty and returns no row:
UPDATE jobs SET status = 'running', worker = 'w2'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ----
(0 rows)
UPDATE jobs SET status = 'waiting', worker = NULL;
UPDATE jobs SET status = 'running', worker = 'w1'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
1 send email 1
(1 row)
UPDATE jobs SET status = 'running', worker = 'w2'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
2 send email 2
(1 row)
UPDATE jobs SET status = 'running', worker = 'w1'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
3 resize photo
(1 row)
The fourth claim finds the queue empty and returns no row:
UPDATE jobs SET status = 'running', worker = 'w2'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ----
(0 rows)
UPDATE jobs SET status = 'waiting', worker = NULL;
UPDATE jobs SET status = 'running', worker = 'w1'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
1 send email 1
(1 row)
UPDATE jobs SET status = 'running', worker = 'w2'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
2 send email 2
(1 row)
UPDATE jobs SET status = 'running', worker = 'w1'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ------------
3 resize photo
(1 row)
The fourth claim finds the queue empty and returns no row:
UPDATE jobs SET status = 'running', worker = 'w2'
WHERE id = (SELECT id FROM jobs WHERE status = 'waiting' ORDER BY id LIMIT 1)
RETURNING id, task;
id task
-- ----
(0 rows)
UPDATE ... RETURNING finds the job, marks it and hands it back in one statement, so there is no gap for another worker to slip into. SQLite lets one writer work at a time (lesson 6.6), which already protects this; other systems need such single-statement claims, and many offer extra row-locking options for queues. Check the documentation of your product.
Quick check: why is "read the waiting job, then update it" risky with many workers?
Two workers can read the same row before either updates it, so both think they own the job.
3. The outbox pattern
Suppose placing an order must also tell another system (send an email, update stock elsewhere). If the program saves the order and then separately calls the other system, a crash in between loses the message or sends it for an order that was never saved.
The outbox pattern writes the event in the same transaction as the order into an outbox table. A separate process reads unsent events and marks them sent. Either both the order and its event exist, or neither does. A trigger (lesson 11.1) can even write the event for you:
Here the new rows are shop orders:
Here the new rows are bank transfers:
Here the new rows are school enrollments:
CREATE TABLE outbox (id INTEGER PRIMARY KEY, event TEXT, payload TEXT, sent INTEGER NOT NULL DEFAULT 0);
CREATE TRIGGER row_created AFTER INSERT ON orders
BEGIN INSERT INTO outbox (event, payload) VALUES ('order_created', json_object('id', NEW.order_id, 'customer', NEW.customer_id)); END;
BEGIN;
INSERT INTO orders (customer_id, order_date, status, ship_city) VALUES (1, '2026-10-01', 'pending', 'Leeds');
INSERT INTO orders (customer_id, order_date, status, ship_city) VALUES (2, '2026-10-02', 'pending', 'Leeds');
COMMIT;
SELECT id, event, payload, sent FROM outbox ORDER BY id;
id event payload sent
-- ------------- ------------------------ ----
1 order_created {"id":2601,"customer":1} 0
2 order_created {"id":2602,"customer":2} 0
(2 rows)
The "publisher" reads the unsent events, sends them, and marks them sent:
UPDATE outbox SET sent = 1 WHERE sent = 0;
SELECT id, sent FROM outbox ORDER BY id;
id sent
-- ----
1 1
2 1
(2 rows)
CREATE TABLE outbox (id INTEGER PRIMARY KEY, event TEXT, payload TEXT, sent INTEGER NOT NULL DEFAULT 0);
CREATE TRIGGER row_created AFTER INSERT ON transfers
BEGIN INSERT INTO outbox (event, payload) VALUES ('transfer_created', json_object('id', NEW.transfer_id, 'cents', NEW.amount_cents)); END;
BEGIN;
INSERT INTO transfers (from_account, to_account, amount_cents, created_on, status) VALUES (1, 2, 4400, '2026-10-01', 'done');
INSERT INTO transfers (from_account, to_account, amount_cents, created_on, status) VALUES (3, 4, 900, '2026-10-02', 'done');
COMMIT;
SELECT id, event, payload, sent FROM outbox ORDER BY id;
id event payload sent
-- ---------------- ----------------------- ----
1 transfer_created {"id":601,"cents":4400} 0
2 transfer_created {"id":602,"cents":900} 0
(2 rows)
The "publisher" reads the unsent events, sends them, and marks them sent:
UPDATE outbox SET sent = 1 WHERE sent = 0;
SELECT id, sent FROM outbox ORDER BY id;
id sent
-- ----
1 1
2 1
(2 rows)
CREATE TABLE outbox (id INTEGER PRIMARY KEY, event TEXT, payload TEXT, sent INTEGER NOT NULL DEFAULT 0);
CREATE TRIGGER row_created AFTER INSERT ON enrollments
BEGIN INSERT INTO outbox (event, payload) VALUES ('student_enrolled', json_object('student', NEW.student_id, 'section', NEW.section_id)); END;
BEGIN;
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (360, 1, '2026-10-01');
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (359, 1, '2026-10-02');
COMMIT;
SELECT id, event, payload, sent FROM outbox ORDER BY id;
id event payload sent
-- ---------------- --------------------------- ----
1 student_enrolled {"student":360,"section":1} 0
2 student_enrolled {"student":359,"section":1} 0
(2 rows)
The "publisher" reads the unsent events, sends them, and marks them sent:
UPDATE outbox SET sent = 1 WHERE sent = 0;
SELECT id, sent FROM outbox ORDER BY id;
id sent
-- ----
1 1
2 1
(2 rows)
Two events were written together with the two rows. The publisher sent each and marked it done. If the publisher crashes after sending but before marking, the event is sent again next time, so receivers should handle duplicates safely (this is called being idempotent, meaning that doing it twice has the same effect as once).
4. Notifications
Some systems can push a signal instead of waiting to be asked. The PostgreSQL documentation describes NOTIFY as a simple interprocess communication mechanism for processes accessing the same database, where a payload string can be sent along with the notification. A program asks to receive such messages with LISTEN. (PostgreSQL feature, not run here; SQLite has no equivalent.)
Remember what a signal like this is: a wake-up call, not a durable record. If nobody is listening at that moment, the message is not kept for later. That is why many designs combine both: the queue or outbox table stores the work reliably, and a notification just tells workers to look now instead of in five seconds.
Worked example: photo uploads
A site resizes photos after upload.
- Saving the photo inserts a row in
jobs(statuswaiting) in the same transaction. - Several worker programs repeatedly claim a job with the single-statement
UPDATE ... RETURNING. - A worker marks the job
donewhen finished, orfailedwith an error message so it can be retried. - Optionally a notification wakes idle workers immediately; if it is missed, polling every few seconds still finds the job.
Nothing is lost on a crash: a job stuck in running can be detected by its age and reset to waiting. The site is made up.
Common mistakes
- Claiming jobs with a separate read then write under many workers.
- Treating a notification as a reliable message. It can be missed; keep the real work in a table.
- Sending a message outside the transaction and losing it or sending it for a rolled-back change.
- Assuming each event arrives exactly once. Design receivers to cope with duplicates.
- Never cleaning up old finished jobs and events, so the table grows without end.
Key takeaways
- To react to data changes you can poll, use notifications, or store work in a queue table.
- A job queue table needs a safe claim: do it in one statement such as
UPDATE ... RETURNING. - The outbox pattern writes an event in the same transaction as the change, so the two cannot disagree.
- Notifications (for example PostgreSQL
NOTIFY) are wake-up signals, not durable messages. - Receivers must tolerate duplicate events.
Practice
1. What is the difference between polling and a notification?
Show answer
Polling: the program asks repeatedly whether anything changed. Notification: the database tells interested programs when something changes.
2. Why does claim2 use a single UPDATE ... RETURNING statement?
Show answer
Finding and marking the job happen in one step, so another worker cannot take the same job in between.
3. What problem does the outbox pattern solve?
Show answer
It keeps a change and its event consistent. Both are written in one transaction, so you never have an order without its event or an event for an order that was rolled back.
4. Why must receivers of outbox events handle duplicates?
Show answer
If the publisher crashes after sending but before marking the event as sent, it will send it again later.
5. Why is a notification alone not enough for important work?
Show answer
It is only a wake-up signal and is not stored; if no program is listening at that moment, it is missed. The work itself should be in a table.
6. A job has been running for three hours but its worker crashed. How could your design recover it?
Show answer
Store when the job was claimed, find jobs that have been running longer than a limit, and set them back to waiting so another worker retries them.