Building Resilient Event-Driven Architectures with Postgres and Serverless Queues
Your event pipeline is silently dropping messages every time a transaction commits and the publish call fails. This deep dive shows how to combine the Postgres transactional outbox pattern with QStash to build at-least-once delivery, idempotent consumers, and observable backpressure—without operating a broker.
AI Generated with Qwen 3.0 via CometAPIThe Dual-Write Problem: Why Your Event Pipeline Silently Drops Messages
Almost every event-driven architecture starts with the same innocent two lines:
// ❌ NOT SAFE: two independent writes with no shared atomicity
await db.query('INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)', [id, customerId, total]);
await qstash.publishJSON({ url: INVOICE_URL, body: { orderId: id } });There are exactly two failure modes, and both are production bugs:
- Commit succeeds, publish fails. The order exists, the invoice never gets generated, and no retry loop exists because nothing recorded that an event was owed. This is a silent data loss bug—the worst kind.
- Publish succeeds, commit fails (or the process dies between the two). The downstream billing service charges a customer for an order that does not exist.
You cannot fix this with a try/catch. The database and the queue are two separate systems with two separate commit points. Distributed transactions (XA/2PC) are theoretically available but are operationally hostile: they require coordinator support, hold locks across network calls, and are unsupported by most serverless queue providers. The pragmatic answer is the transactional outbox pattern: make the event part of the same Postgres transaction as the business state change, and let a separate relay process move events from the table to the broker.
┌─────────────┐ 1. BEGIN ┌──────────────────┐
│ API/Worker │──── 2. INSERT orders ────────▶│ PostgreSQL │
│ (Postgres │──── 3. INSERT outbox ────────▶│ (single tx) │
│ client) │──── 4. COMMIT ───────────────▶└────────┬─────────┘
└─────────────┘ │
│ 5. relay drains
▼
┌──────────────────┐
│ QStash (HTTP) │
└────────┬─────────┘
│ 6. signed POST + retries
▼
┌──────────────────┐
│ Idempotent │
│ Consumer │
└──────────────────┘The Transactional Outbox as Your System of Record
Designing the Outbox Table for Throughput
Most outbox tutorials give you a table that becomes a vacuum nightmare at 10k events/minute. Design it deliberately: a monotonic identity column for ordering, a partial index for the hot path, lease columns for safe concurrent relaying, and a retention strategy from day one.
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
aggregate_type text NOT NULL,
aggregate_id text NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
headers jsonb NOT NULL DEFAULT '{}'::jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
available_at timestamptz NOT NULL DEFAULT now(), -- backoff gate
processed_at timestamptz, -- NULL = still owed
attempts integer NOT NULL DEFAULT 0,
last_error text,
locked_by text,
locked_until timestamptz
);
-- The only index the relay hot path needs. Partial => tiny and cache-resident.
CREATE INDEX outbox_pending_idx
ON outbox (available_at, id)
WHERE processed_at IS NULL;
CREATE INDEX outbox_aggregate_idx ON outbox (aggregate_type, aggregate_id, id);Two details that matter more than they look:
- `GENERATED ALWAYS AS IDENTITY` over `serial`. You want
bigint, not a 32-bitintegerthat overflows at 2.1B rows. - `processed_at IS NULL` partial index. The relay's
ORDER BY id LIMIT nscans only unprocessed rows. Once you archive processed rows (see retention below), this index stays small forever.
Writing Events Atomically with Business State
import type { PoolClient } from 'pg';
export interface OrderPlaced {
orderId: string;
customerId: string;
totalCents: number;
currency: 'USD' | 'EUR';
}
export async function placeOrder(client: PoolClient, event: OrderPlaced): Promise<void> {
await client.query('BEGIN');
try {
await client.query(
`INSERT INTO orders (id, customer_id, total_cents, currency, status)
VALUES ($1, $2, $3, $4, 'placed')`,
[event.orderId, event.customerId, event.totalCents, event.currency],
);
await client.query(
`INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload, headers)
VALUES ($1, $2, $3, $4::jsonb, $5::jsonb)`,
[
'order',
event.orderId,
'order.placed',
JSON.stringify(event),
JSON.stringify({ 'x-event-version': '1', 'x-correlation-id': event.orderId }),
],
);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}If COMMIT returns, the event is durable and owed. If it throws, neither row exists. There is no third state.
The Relay: Draining the Outbox Without Locks or Lost Rows
The naive relay—SELECT ... LIMIT 100 then UPDATE—breaks the moment you run two instances: both read the same rows and both publish. Postgres solves this with FOR UPDATE SKIP LOCKED, which lets N relay workers claim disjoint batches with zero contention.
Claiming Batches with SKIP LOCKED
WITH claimed AS (
SELECT id
FROM outbox
WHERE processed_at IS NULL
AND available_at <= now()
AND (locked_until IS NULL OR locked_until < now())
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED
)
UPDATE outbox o
SET locked_by = $2,
locked_until = now() + $3::interval,
attempts = o.attempts + 1
FROM claimed c
WHERE o.id = c.id
RETURNING o.id, o.event_type, o.aggregate_id, o.payload, o.attempts;The locked_until lease is your crash-recovery mechanism: if a relay dies mid-batch, the rows become claimable again after 30 seconds. This is why you must be able to publish the same row twice safely—which is exactly what deduplicationId buys you.
Polling vs. Logical Replication (CDC)
| Approach | Latency | Ops cost | Fits serverless? |
|---|---|---|---|
| Poll + `SKIP LOCKED` | Seconds | Low (a cron + a route) | ✅ Yes |
| `LISTEN`/`NOTIFY` wakeup + poll fallback | Milliseconds | Low | ⚠️ Needs a long-lived connection |
| Logical decoding (Debezium `pgoutput`) | Milliseconds | High (connector cluster, slots, WAL retention) | ❌ No |
NOTIFY is a great optimization but a terrible guarantee: notifications are transactional and only fire on commit, but they are dropped if no listener is connected. Keep polling as the safety net and treat NOTIFY as a latency fast-path.
A Serverless Relay with QStash
The relay itself can be a stateless HTTP handler, invoked by a QStash schedule or a cron. It holds no state—the lease columns are the state.
import { Pool } from 'pg';
import { Client as QStash } from '@upstash/qstash';
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
const qstash = new QStash({ token: process.env.QSTASH_TOKEN! });
const CONSUMER_URL = process.env.EVENT_CONSUMER_URL!;
interface ClaimedRow {
id: string;
event_type: string;
aggregate_id: string;
payload: Record<string, unknown>;
attempts: number;
}
export async function drainOutbox(batchSize = 50) {
const workerId = `relay-${crypto.randomUUID()}`;
const client = await pool.connect();
let rows: ClaimedRow[];
try {
const res = await client.query<ClaimedRow>(
`WITH claimed AS (
SELECT id FROM outbox
WHERE processed_at IS NULL AND available_at <= now()
AND (locked_until IS NULL OR locked_until < now())
ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED)
UPDATE outbox o
SET locked_by = $2, locked_until = now() + $3::interval, attempts = o.attempts + 1
FROM claimed c WHERE o.id = c.id
RETURNING o.id, o.event_type, o.aggregate_id, o.payload, o.attempts`,
[batchSize, workerId, '30 seconds'],
);
rows = res.rows;
} finally {
client.release();
}
let published = 0;
let failed = 0;
for (const row of rows) {
const envelope = {
id: String(row.id), // globally unique → downstream idempotency key
type: row.event_type,
occurredAt: new Date().toISOString(),
aggregateId: row.aggregate_id,
data: row.payload,
meta: { version: 1, correlationId: String(row.id) },
};
try {
await qstash.publishJSON({
url: CONSUMER_URL,
body: envelope,
deduplicationId: `outbox-${row.id}`, // collapses duplicate publishes
retries: 5,
});
await pool.query(
`UPDATE outbox
SET processed_at = now(), locked_by = NULL, locked_until = NULL
WHERE id = $1`,
[row.id],
);
published++;
} catch (err) {
failed++;
const message = (err instanceof Error ? err.message : String(err)).slice(0, 500);
await pool.query(
`UPDATE outbox
SET locked_by = NULL, locked_until = NULL, last_error = $2,
available_at = now() + make_interval(secs => (LEAST(300, power(2, attempts)::int))::double precision)
WHERE id = $1`,
[row.id, message],
);
}
}
return { claimed: rows.length, published, failed };
}Note the ordering: publish first, then mark processed. If the process dies between the two, the row is re-delivered on the next drain—which is safe because deduplicationId is stable. Marking processed before publishing would be an unrecoverable event loss.
// Schedule the relay every minute; QStash retries the schedule invocation on 5xx.
await qstash.schedules.create({
destination: 'https://app.example.com/api/relay/outbox',
cron: '*/1 * * * *',
body: JSON.stringify({ batchSize: 100 }),
});QStash as a Serverless Delivery Layer
QStash is an HTTP-based queue: publishers make a signed HTTP call, and QStash guarantees at-least-once delivery to your endpoint with exponential backoff, a dead-letter path via failure callbacks, and flow control for rate limiting. There is no broker to patch and no VPC to peer—which is precisely why it pairs well with a Postgres outbox.
Key configuration knobs:
- `retries` — how many delivery attempts QStash makes before invoking your failure callback.
- `deduplicationId` — collapses identical publishes within the provider's deduplication window. Treat this as a latency/duplicate-reduction optimization, not as your correctness guarantee. The window is time-bounded; your own idempotency ledger is what makes replay safe.
- `flowControl: { key, parallelism }` — caps concurrency per key so a burst of outbox rows does not stampede your downstream database.
- `failureCallback` — a URL QStash calls after retries are exhausted; this is where you page a human or park the event.
Ordering, Backpressure, and the Illusion of FIFO
ORDER BY id in the relay preserves publish order, but concurrent consumers reorder execution. If order.placed must be handled before order.shipped, do not rely on the queue. Two robust options:
- Partition by aggregate and serialize. Use
flowControl: { key: \order-${aggregateId}\, parallelism: 1 }so all events for a given order are processed one at a time, while different orders proceed in parallel. - Version-guard in the consumer. Store a
versionper aggregate and reject out-of-order updates with a conditionalUPDATE ... WHERE version = $expected—an optimistic concurrency check on the consumer's own table.
Idempotent Consumers: Turning At-Least-Once Into Effectively-Once
At-least-once delivery is the only honest contract any queue can offer. Exactly-once is achieved by making the consumer idempotent, using a ledger table that commits in the same transaction as the side effect.
CREATE TABLE processed_messages (
message_id text PRIMARY KEY,
consumer text NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now()
);
-- Retention: DELETE WHERE processed_at < now() - interval '30 days' (longer than max retry window)import { Receiver } from '@upstash/qstash';
import { Pool } from 'pg';
const receiver = new Receiver({
currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY!,
nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY!,
});
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
interface Envelope<T = unknown> {
id: string;
type: string;
occurredAt: string;
aggregateId: string;
data: T;
meta: { version: number; correlationId: string };
}
export async function POST(req: Request): Promise<Response> {
const signature = req.headers.get('upstash-signature');
if (!signature) return new Response('unauthorized', { status: 401 });
const raw = await req.text();
// Bind the signature to THIS url to prevent replay against another endpoint.
const valid = await receiver
.verify({ signature, body: raw, url: process.env.PUBLIC_CONSUMER_URL })
.catch(() => false);
if (!valid) return new Response('unauthorized', { status: 401 });
const event = JSON.parse(raw) as Envelope<{ orderId: string; totalCents: number }>;
const client = await pool.connect();
try {
await client.query('BEGIN');
// One INSERT decides ownership. Concurrent deliveries of the same message
// serialize on the primary key; exactly one gets rowCount === 1.
const claim = await client.query(
`INSERT INTO processed_messages (message_id, consumer)
VALUES ($1, $2) ON CONFLICT (message_id) DO NOTHING`,
[event.id, event.type],
);
if (claim.rowCount === 0) {
await client.query('ROLLBACK');
return Response.json({ status: 'duplicate' }); // 200 → stop retrying
}
await client.query(`UPDATE orders SET status = 'invoiced' WHERE id = $1`, [
event.data.orderId,
]);
await client.query('COMMIT');
return Response.json({ status: 'processed' });
} catch (err) {
await client.query('ROLLBACK'); // ledger row rolls back with the side effect
return new Response('handler failure', { status: 500 }); // 5xx → QStash retries
} finally {
client.release();
}
}Because the ledger insert and the business UPDATE share a transaction, a failure mid-handler rolls back both. There is no window where the message is marked processed but the work is not done.
Observability: The Four Metrics That Actually Matter
Instrument the outbox itself—it is your ground truth for system health.
SELECT
count(*) FILTER (WHERE processed_at IS NULL) AS backlog,
coalesce(max(now() - created_at) FILTER (WHERE processed_at IS NULL),
interval '0') AS oldest_unprocessed_age,
count(*) FILTER (WHERE processed_at IS NULL AND attempts >= 5) AS poison_rows
FROM outbox;- `backlog` — a monotonically growing value means the relay is under-provisioned or the downstream is throttling.
- `oldest_unprocessed_age` — the real SLI. Page on age, not count; 500 fresh rows are fine, one 40-minute-old row is an incident.
- `poison_rows` — events that keep failing. Route them to a DLQ table and alert.
- Consumer p99 + 5xx rate — QStash retries amplify load; a 20% error rate becomes a thundering herd without flow control.
Propagate x-correlation-id through Upstash-Forward-* headers so a single trace spans the outbox row, the QStash message, and the consumer's logs.
Operational Checklist
- Outbox insert is inside the same
BEGIN/COMMITas the business write. - Relay uses
FOR UPDATE SKIP LOCKEDwith a bounded lease (locked_until). - Publish happens before
processed_atis set;deduplicationIdis the outbox row id. pgbouncerin transaction pooling mode (session mode breaksSKIP LOCKEDsemantics andLISTEN).- Processed rows archived (
INSERT INTO outbox_archive SELECT ... ; DELETE ...) or the table is range-partitioned bycreated_atand old partitions are dropped. - Consumers verify the QStash signature and return 2xx only on success or confirmed duplicate.
- Idempotency ledger retention exceeds your maximum retry + replay window.
failureCallbackwired to a DLQ table plus an on-call alert.- Alerting on
oldest_unprocessed_age, not just backlog count.
Pitfalls to Avoid
- Marking processed before publishing. The single most common outbox bug; it converts at-least-once into at-most-once.
- Relying on `deduplicationId` for correctness. It is time-windowed. Your ledger is the guarantee.
- *Unbounded `SELECT
withoutLIMIT`.** One backlog spike OOMs your serverless function. - Returning 4xx on transient consumer errors. QStash treats 4xx as non-retryable (or retries differently). Return 5xx for transient failures and 4xx only for genuinely malformed, unprocessable payloads.
- Session-mode connection pooling with `SKIP LOCKED`. Locks can be held by a pooled session, starving the relay.
- No outbox retention. Unarchived outbox tables bloat, slow VACUUM, and eventually dominate your database size.
Sources & Technical References
- PostgreSQL Documentation —
SELECT,FOR UPDATE SKIP LOCKED: https://www.postgresql.org/docs/current/sql-select.html - PostgreSQL Documentation —
NOTIFY/LISTEN(transactional semantics, payload limits): https://www.postgresql.org/docs/current/sql-notify.html - PostgreSQL Documentation — Logical Replication and
pgoutput: https://www.postgresql.org/docs/current/logical-replication.html - microservices.io — Pattern: Transactional Outbox: https://microservices.io/patterns/data/transactional-outbox.html
- Debezium Documentation — Outbox Event Router: https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html
- Upstash QStash — Getting Started: https://upstash.com/docs/qstash/overall/getstarted
- Upstash QStash — Verifying Signatures: https://upstash.com/docs/qstash/howto/signature
- Upstash QStash — Retries and Failure Callbacks: https://upstash.com/docs/qstash/features/retry
- Upstash QStash — Deduplication: https://upstash.com/docs/qstash/features/deduplication
- Upstash QStash — Flow Control: https://upstash.com/docs/qstash/features/flow-control
- Upstash QStash — Schedules: https://upstash.com/docs/qstash/features/schedules
- AWS Builders' Library — Timeouts, Retries, and Backoff with Jitter: https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/
- Amazon SQS Developer Guide — At-Least-Once Delivery in Standard Queues: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues-at-least-once-delivery.html
- IETF Draft — The Idempotency-Key HTTP Header Field: https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/
- W3C Recommendation — Trace Context: https://www.w3.org/TR/trace-context/
Discussion (0)
Continue Reading
More production-grade engineering deep dives and architectural guides

Signals vs Virtual DOM at 1B Monthly Renders: React 19 vs SolidJS vs Svelte 5 vs Vue 3.5 — Measured p99 Frame Time, Memory, Bundle Size, and True Cost per 1M Updates
We rebuilt the same 10,000-row update workload in React 19, SolidJS, Svelte 5, and Vue 3.5 and measured p99 frame time, retained heap, bundle weight, and a defensible cost model per million updates. The numbers show that architecture, not micro-optimization, decides whether your tail latency survives a billion renders.

Postgres Egress Cost Optimization: Cutting Network Bandwidth by 70% in High-Throughput APIs
Your Postgres bill is rarely about CPU — it is about bytes leaving the database, crossing an availability zone, and traversing a NAT gateway. Here is the systematic playbook we used to cut data transfer cost by 70% in a high-throughput API without touching query latency.

Gemini 4 Neon: A Principal Engineer's Deep Dive into the Architecture
Gemini 4 Neon is a serving-systems release disguised as a model launch: the interesting engineering lives in its control plane, cache fabric, and streaming transport, not the benchmark table. This analysis breaks down the four-plane topology, the latency budget you must own, and the production patterns that keep a Neon integration from melting down under load.