Data consistency
Transactional outbox pattern
A transactional outbox stores a message to be published in the same database transaction as a business change. A separate relay publishes committed outbox records to a broker. This avoids the gap where a business change commits but the intent to send its event is lost. Do not write the outbox in an unrelated transaction. Do not assume one outbox row means only one transport delivery. Do not delete pending events without an explicit recovery policy. Source: https://microservices.io/patterns/data/transactional-outbox.html Local examples do not establish third-party integration support.
Formal Syntax & Structure
nodejs syntaxnodejs
BEGIN; business write; INSERT INTO outbox ...; COMMIT;Working Example
Example Snippetnodejs
import {DatabaseSync} from 'node:sqlite';import {mkdtempSync,rmSync} from 'node:fs';import {tmpdir} from 'node:os';import {join} from 'node:path';const dir=mkdtempSync(join(tmpdir(),'bm-outbox-'));let db;try{ const path=join(dir,'lab.db');db=new DatabaseSync(path); db.exec('CREATE TABLE orders(id TEXT PRIMARY KEY NOT NULL); CREATE TABLE outbox(id TEXT PRIMARY KEY NOT NULL,order_id TEXT NOT NULL,sent INTEGER DEFAULT 0)'); function order(id,event,fail){db.exec('BEGIN');try{ db.prepare('INSERT INTO orders VALUES(?)').run(id); db.prepare('INSERT INTO outbox(id,order_id) VALUES(?,?)').run(event,id); if(fail)throw new Error('simulated failure');db.exec('COMMIT'); }catch(e){db.exec('ROLLBACK');}} order('o1','e1',false);order('o2','e2',true); db.close();db=new DatabaseSync(path); console.log(JSON.stringify(db.prepare('SELECT id FROM orders ORDER BY id').all())); console.log(JSON.stringify(db.prepare('SELECT id FROM outbox WHERE sent=0 ORDER BY id').all()));}finally{if(db?.isOpen)db.close();rmSync(dir,{recursive:true,force:true});}