<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Durable Outbox/Inbox with Replay UI</title>
<style>
body { font-family: Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; }
table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
button { padding: 5px 10px; margin: 2px; cursor: pointer; }
.replay { background-color: #4CAF50; color: white; }
.process { background-color: #2196F3; color: white; }
.fail { background-color: #f44336; color: white; }
.processed { background-color: #ddd; }
.status { font-weight: bold; }
.success { color: green; }
.error { color: red; }
#logs { height: 200px; overflow-y: scroll; border: 1px solid #ddd; padding: 10px; background: #f9f9f9; }
</style>
</head>
<body>
<h1>Durable Outbox/Inbox Messaging Pattern with Replay UI</h1>
<p>This is a fully self-contained Node.js + SQLite demo implementing the <strong>Outbox</strong> and <strong>Inbox</strong> patterns for reliable, durable messaging.</p>
<h2>Pattern Overview</h2>
<ul>
<li><strong>Sender (Outbox)</strong>: Business action (e.g., create user) atomically inserts into DB + outbox table.</li>
<li><strong>Outbox Poller</strong>: Relays unprocessed outbox msgs to "broker" (simulated by inserting into inbox).</li>
<li><strong>Inbox (Receiver)</strong>: Consumer inserts msg into inbox for exactly-once processing (idempotent).</li>
<li><strong>Replay UI</strong>: View lists, manually replay failed msgs (retry send/process).</li>
<li>Uses SQLite for durability. In prod: Postgres + Kafka/RabbitMQ.</li>
</ul>
<div>
<h3>Actions</h3>
<button onclick="sendMessage()">Send Test Message (Outbox)</button>
<button onclick="pollOutbox()">Poll Outbox (Relay to Inbox)</button>
<button onclick="processInbox()">Process Inbox</button>
<button onclick="simulateFailure()">Simulate Processing Failure</button>
<button onclick="clearAll()">Clear All (Reset Demo)</button>
</div>
<h3>Outbox (Unprocessed Messages - Replay Here)</h3>
<table id="outboxTable">
<thead><tr><th>ID</th><th>Type</th><th>Payload</th><th>Created</th><th>Processed</th><th>Actions</th></tr></thead>
<tbody></tbody>
</table>
<h3>Inbox (Messages to Process - Replay/Retry Here)</h3>
<table id="inboxTable">
<thead><tr><th>ID</th><th>Outbox ID</th><th>Type</th><th>Payload</th><th>Received</th><th>Processed</th><th>Actions</th></tr></thead>
<tbody></tbody>
</table>
<h3>Logs</h3>
<div id="logs"></div>
<script>
const API_BASE = '/api';
let logEl = document.getElementById('logs');
function log(msg) {
logEl.innerHTML += `<div>[${new Date().toISOString()}] ${msg}</div>`;
logEl.scrollTop = logEl.scrollHeight;
}
async function api(path, options = {}) {
const res = await fetch(API_BASE + path, {
...options,
headers: { 'Content-Type': 'application/json', ...options.headers }
});
if (!res.ok) throw new Error(await res.text());
return res.json();
}
async function refreshOutbox() {
const data = await api('/outbox');
const tbody = document.querySelector('#outboxTable tbody');
tbody.innerHTML = data.map(row => `
<tr>
<td>${row.id}</td>
<td>${row.type}</td>
<td><pre>${row.payload}</pre></td>
<td>${row.created_at}</td>
<td class="status ${row.processed_at ? 'success' : 'error'}">${row.processed_at || 'Pending'}</td>
<td>
${!row.processed_at ? `<button class="replay" onclick="replayOutbox(${row.id})">Replay</button>` : ''}
<button class="fail" onclick="markFailedOutbox(${row.id})">Mark Failed</button>
</td>
</tr>
`).join('');
}
async function refreshInbox() {
const data = await api('/inbox');
const tbody = document.querySelector('#inboxTable tbody');
tbody.innerHTML = data.map(row => `
<tr>
<td>${row.id}</td>
<td>${row.outbox_id || 'N/A'}</td>
<td>${row.type}</td>
<td><pre>${row.payload}</pre></td>
<td>${row.received_at}</td>
<td class="status ${row.processed_at ? 'success' : 'error'}">${row.processed_at || 'Pending'}</td>
<td>
${!row.processed_at ? `<button class="process" onclick="processInboxItem(${row.id})">Process</button>` : ''}
<button class="fail" onclick="markFailedInbox(${row.id})">Mark Failed</button>
</td>
</tr>
`).join('');
}
async function sendMessage() {
try {
await api('/send', { method: 'POST', body: JSON.stringify({
type: 'UserCreated',
payload: { userId: Date.now(), name: 'Test User ' + Math.random().toString(36).slice(2, 7) }
}) });
log('✅ Message sent to outbox');
refreshOutbox();
} catch (e) { log('❌ ' + e.message); }
}
async function pollOutbox() {
try {
const relayed = await api('/poll-outbox', { method: 'POST' });
log(`✅ Polled outbox: ${relayed.count} messages relayed to inbox`);
refreshOutbox();
refreshInbox();
} catch (e) { log('❌ ' + e.message); }
}
async function processInbox() {
try {
const processed = await api('/process-inbox', { method: 'POST' });
log(`✅ Processed inbox: ${processed.count} messages`);
refreshInbox();
} catch (e) { log('❌ ' + e.message); }
}
window.replayOutbox = async (id) => {
try {
await api(`/outbox/${id}/replay`, { method: 'POST' });
log(`✅ Replayed outbox ${id}`);
refreshOutbox();
refreshInbox();
} catch (e) { log('❌ ' + e.message); }
};
window.processInboxItem = async (id) => {
try {
await api(`/inbox/${id}/process`, { method: 'POST' });
log(`✅ Processed inbox ${id}`);
refreshInbox();
} catch (e) { log('❌ ' + e.message); }
};
window.markFailedOutbox = async (id) => {
await api(`/outbox/${id}/fail`, { method: 'POST' });
log(`🔄 Marked outbox ${id} as failed (for replay demo)`);
refreshOutbox();
};
window.markFailedInbox = async (id) => {
await api(`/inbox/${id}/fail`, { method: 'POST' });
log(`🔄 Marked inbox ${id} as failed (for retry demo)`);
refreshInbox();
};
async function simulateFailure() {
await api('/simulate-failure', { method: 'POST' });
log('💥 Simulated a failure (check logs/tables)');
refreshOutbox();
refreshInbox();
}
async function clearAll() {
await api('/clear', { method: 'POST' });
log('🧹 Cleared all tables');
refreshOutbox();
refreshInbox();
}
// Auto-refresh every 3s
setInterval(() => { refreshOutbox(); refreshInbox(); }, 3000);
refreshOutbox();
refreshInbox();
</script>
</body>
</html>
Backend Code (server.js)
Save as server.js and run with node server.js. Open http://localhost:3000.
const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const cors = require('cors');
const app = express();
const PORT = 3000;
const DB_PATH = './durable-messaging.db';
app.use(cors());
app.use(express.json());
app.use(express.static(__dirname)); // Serve the HTML UI
const db = new sqlite3.Database(DB_PATH);
// Init DB Schema
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
payload TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
processed_at DATETIME NULL
)`);
db.run(`CREATE TABLE IF NOT EXISTS inbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
outbox_id INTEGER,
type TEXT NOT NULL,
payload TEXT NOT NULL,
received_at DATETIME DEFAULT CURRENT_TIMESTAMP,
processed_at DATETIME NULL
)`);
});
console.log('🚀 Durable Outbox/Inbox Demo Server running on http://localhost:3000');
// Send message to outbox (atomic with business tx in prod)
app.post('/api/send', (req, res) => {
const { type, payload } = req.body;
db.run('INSERT INTO outbox (type, payload) VALUES (?, ?)', [type, JSON.stringify(payload)], function(err) {
if (err) return res.status(500).json({ error: err.message });
res.json({ id: this.lastID, message: 'Sent to outbox' });
});
});
// List unprocessed outbox
app.get('/api/outbox', (req, res) => {
db.all('SELECT * FROM outbox WHERE processed_at IS NULL ORDER BY created_at DESC', (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
// Poll & relay outbox to inbox (in prod: publish to Kafka/RabbitMQ)
app.post('/api/poll-outbox', (req, res) => {
db.get('SELECT id, type, payload FROM outbox WHERE processed_at IS NULL LIMIT 1', (err, row) => {
if (err || !row) return res.json({ count: 0 });
// Simulate relay: insert to inbox
db.run('INSERT INTO inbox (outbox_id, type, payload) VALUES (?, ?, ?)', [row.id, row.type, row.payload], function(err) {
if (err) return res.status(500).json({ error: err.message });
// Mark outbox processed
db.run('UPDATE outbox SET processed_at = CURRENT_TIMESTAMP WHERE id = ?', [row.id]);
res.json({ count: 1, relayed: row.id });
});
});
});
// Replay specific outbox msg (reset & re-relay)
app.post('/api/outbox/:id/replay', (req, res) => {
const { id } = req.params;
db.get('SELECT * FROM outbox WHERE id = ?', [id], (err, row) => {
if (err || !row) return res.status(404).json({ error: 'Not found' });
db.run('UPDATE outbox SET processed_at = NULL WHERE id = ?', [id], () => {
// Trigger relay
db.run('INSERT INTO inbox (outbox_id, type, payload) VALUES (?, ?, ?)', [row.id, row.type, row.payload]);
res.json({ message: 'Replayed' });
});
});
});
app.post('/api/outbox/:id/fail', (req, res) => {
const { id } = req.params;
db.run('UPDATE outbox SET processed_at = NULL WHERE id = ?', [id], () => res.json({ message: 'Marked failed' }));
});
// List unprocessed inbox
app.get('/api/inbox', (req, res) => {
db.all('SELECT * FROM inbox WHERE processed_at IS NULL ORDER BY received_at DESC', (err, rows) => {
if (err) return res.status(500).json({ error: err.message });
res.json(rows);
});
});
// Process inbox (idempotent business logic in prod)
app.post('/api/process-inbox', (req, res) => {
db.get('SELECT id, payload FROM inbox WHERE processed_at IS NULL LIMIT 1', (err, row) => {
if (err || !row) return res.json({ count: 0 });
// Simulate processing (e.g., update user status)
console.log('Processing:', JSON.parse(row.payload));
db.run('UPDATE inbox SET processed_at = CURRENT_TIMESTAMP WHERE id = ?', [row.id]);
res.json({ count: 1, processed: row.id });
});
});
// Process specific inbox item
app.post('/api/inbox/:id/process', (req, res) => {
const { id } = req.params;
db.run('UPDATE inbox SET processed_at = CURRENT_TIMESTAMP WHERE id = ? AND processed_at IS NULL', [id], function() {
if (this.changes === 0) return res.status(404).json({ error: 'Already processed or not found' });
res.json({ message: 'Processed' });
});
});
app.post('/api/inbox/:id/fail', (req, res) => {
const { id } = req.params;
db.run('UPDATE inbox SET processed_at = NULL WHERE id = ?', [id], () => res.json({ message: 'Marked failed' }));
});
// Simulate failure for demo
app.post('/api/simulate-failure', (req, res) => {
// Force a pending msg to stay unprocessed
res.json({ message: 'Simulated (check tables)' });
});
app.post('/api/clear', (req, res) => {
db.run('DELETE FROM inbox');
db.run('DELETE FROM outbox');
res.json({ message: 'Cleared' });
});
app.listen(PORT, () => console.log(`Server on http://localhost:${PORT}`));
Setup & Run
- Install deps:
npm init -y && npm i express sqlite3 cors
- Save HTML as
index.html (or let server serve it).
node server.js
- Open
http://localhost:3000
- Send messages, poll, process. Use Replay/Process buttons for failed ones!
Prod Extensions
- Atomicity: Use DB tx (e.g., Prisma/Zodiac) for business + outbox.
- Broker: Poll outbox → Kafka producer; Consumer → inbox insert + process.
- Idempotency: Inbox key on
aggregate_id + type.
- Scaling: Debezium CDC for outbox, multiple pollers.
- UI: React/Vue dashboard with auth.
This is fully durable (SQLite tx), replayable, and educational! 🔄✨