Skip to content
jshacks.dev
Patterns

Implement the outbox pattern with a database table

Implement the outbox pattern with a database table in JavaScript: write the event in the same transaction as the data. Node.js 24.

1 min read
Summarize in AI

Saving an order and then publishing an event are two writes, and a crash between them loses the event. The outbox pattern stores the event in the same transaction as the order and sends it afterwards.

JavaScript
import { DatabaseSync } from 'node:sqlite';

const db = new DatabaseSync(':memory:');
db.exec(`
  CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER);
  CREATE TABLE outbox (id INTEGER PRIMARY KEY, type TEXT, payload TEXT, sent INTEGER DEFAULT 0);
`);

db.exec('BEGIN');
db.prepare('INSERT INTO orders (total) VALUES (?)').run(4000);
db.prepare('INSERT INTO outbox (type, payload) VALUES (?, ?)').run('OrderPlaced', '{"orderId":1}');
db.exec('COMMIT');

for (const row of db.prepare('SELECT * FROM outbox WHERE sent = 0').all()) {
  console.log('publish', row.type, row.payload);
  db.prepare('UPDATE outbox SET sent = 1 WHERE id = ?').run(row.id);
}
console.log(db.prepare('SELECT COUNT(*) AS pending FROM outbox WHERE sent = 0').get().pending);
Text
publish OrderPlaced {"orderId":1}
0

Both inserts commit together or not at all. A separate loop reads unsent rows, publishes them and marks them sent, so a crash after publishing and before marking sends the event again.

That makes delivery at least once, so consumers must tolerate duplicates. node:sqlite is built into Node.js 22.5 and later and prints an experimental warning on some versions.

Taggednode 24
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.