惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX - 技术
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
Recent Announcements
Recent Announcements
V
V2EX
Hugging Face - Blog
Hugging Face - Blog
T
The Exploit Database - CXSecurity.com
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
Microsoft Security Blog
Microsoft Security Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
K
Kaspersky official blog
F
Fortinet All Blogs
GbyAI
GbyAI
Forbes - Security
Forbes - Security
The Cloudflare Blog
博客园 - 司徒正美
博客园_首页
量子位
Schneier on Security
Schneier on Security
G
GRAHAM CLULEY
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Proofpoint News Feed
N
News | PayPal Newsroom
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
T
Tor Project blog
V
Vulnerabilities – Threatpost
Y
Y Combinator Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cybersecurity and Infrastructure Security Agency CISA
Project Zero
Project Zero
N
News and Events Feed by Topic
I
Intezer
B
Blog
美团技术团队
C
CERT Recently Published Vulnerability Notes
NISL@THU
NISL@THU
L
LINUX DO - 最新话题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
AWS News Blog
AWS News Blog
T
Tailwind CSS Blog
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
有赞技术团队
有赞技术团队

The Practical Developer

The Libuv Thread Pool Trap: Why Node.js Async APIs Stall Under Load Postgres Covering Indexes with INCLUDE: Eliminate Heap Fetches on Read-Heavy Workloads Postgres DISTINCT ON: The Fastest Way to Get the Latest Row Per Group Postgres Transaction Isolation: The Anomalies Your App Actually Faces in Production Linux TCP Tuning for Node.js Microservices: The Kernel Settings That Stop Silent Connection Drops Under Load Postgres HOT Updates and Fillfactor: Why Not All Writes Are Created Equal Database Connection Pool Leaks: Finding the Promise That Never Returns Its Seat Linux OOM Killer in Production: Why Your Node.js Containers Die Without a Stack Trace Postgres Materialized Views: Refresh Strategies That Do Not Lock Your Dashboards API Dependency Health Checks: Why /health Is Not Enough Authorization with Zanzibar Tuples: How Google Manages Permissions and How To Build the Same Check in Node.js Postgres Advisory Locks: The 20-Character Primitive That Replaces Redis for Coordination Dead Letter Queues: The Message Queue Pattern That Saves You at 2 a.m. File Descriptor Exhaustion: The Kernel Limit That Silently Drops Node.js Connections Graceful Degradation: The Pattern That Turns Total Outages into Partial Success PostgreSQL Full-Text Search: Dropping Elasticsearch for 90% of Use Cases S3 Presigned Multipart Uploads: Stop Your API Server from Being a File Upload Bottleneck MessagePack vs JSON: The Binary Serialization Switch That Cut Our Internal RPC Overhead by 40% DNS Caching in Node.js: The Silent Cause of Production Latency Spikes Reliable Cron Jobs: The Pattern That Stops Double Runs, Missed Executions, And The 2 AM Page GraphQL Query Complexity: Stop the OOM Query Before It Reaches Your Resolver Node.js Event Loop Lag: The Hidden Metric Behind Random Latency Spikes API Request Validation with Zod: The Schema That Catches Bad Input Before It Corrupts Your Database Load Shedding in Node.js: How to Reject Traffic Before You Drown Request Hedging: Cut Tail Latency In Half Without Overprovisioning Git Bisect: The Automated Binary Search That Finds Breaking Commits in Minutes Node.js Garbage Collection Tuning: Stop Letting V8 Pause Your Event Loop Node.js Server Timeouts: The Settings That Stop Slow Clients from Holding Sockets Hostage Postgres BRIN Indexes: The Time-Series Secret That Shrinks Indexes by 99% Event Sourcing with PostgreSQL: The Pragmatic 80% Solution Node.js Cluster Mode: Scaling the Event Loop Across CPU Cores Postgres Partial Indexes: Stopping Soft Deletes from Ruining Your Query Performance Request Coalescing with the Singleflight Pattern: Stop Drowning Your Database on Every Cache Miss The Bulkhead Pattern: Why One Slow Endpoint Should Not Drown Your Whole Service Node.js AsyncLocalStorage: End-to-End Request Context Without the Propagation Hell Postgres Deadlocks: Logging the Victim, Reproducing the Race, and Fixing the Lock Order Your Node.js HTTP Client Is the Bottleneck: Connection Pool Tuning That Works Optimistic Locking in Postgres: Stop Losing Data to Race Conditions Postgres Read Replicas: Stop Serving Stale Data to Your Users Cursor Pagination: Why Offset Queries Explode at Scale and How to Fix Them Node.js Worker Threads: 60 Lines That Stop a CSV Upload from Timing Out Every Other Request Reliable Webhook Delivery: Architecture for Outbound HTTP You Can Trust Request Timeouts and Deadline Propagation: Stop the Chain of Slowness Advanced Security Practices in Node.js Graceful Shutdown in Node.js: The 40 Lines That Stop 502s During Deploys Finding Node.js Memory Leaks with Heap Snapshots Idempotency Keys in 30 Lines: Stop Your Webhook From Charging Customers Twice Backpressure In Node.js: The Fix For Slow-Motion Queue Meltdowns Retries Done Right: Jitter, Budgets, and the Stampede You Did Not See Coming The Cache Stampede: Why Your "Just Add Redis" Layer Crashes Postgres at 3 a.m. Postgres SKIP LOCKED: An 80-Line Job Queue You Can Run Without Redis Stop Doing Work Nobody Wants: AbortController in Node.js, Done Right The N+1 Query Problem: We Found 23 In One Codebase And Killed Every One I Tried 5 AI Coding Tools for a Month. Here Is What I Actually Use CI/CD From Zero to Production in 30 Minutes With GitHub Actions Node.js vs Bun vs Deno: Which Runtime Should You Pick in 2025? Kubernetes Resource Requests And Limits: The Numbers That Decide If Your Cluster Is Stable The Three Pillars of Observability Are A Myth: What Actually Matters In Production pnpm Vs npm Vs yarn Vs Bun For Monorepos: Which One Earns The Migration In 2024 JSONB Indexing In Postgres: GIN Vs Expression Indexes, And When Each Is The Right Choice A Code Review Checklist That Ends The Same Three Arguments Every Sprint gRPC Vs REST In 2024: When The Switch Pays For Itself React Suspense For Data Fetching: The Pattern That Replaces Half Your Loading State Code The Five-Stage Rollout: How To Ship A Risky Change Without Holding Your Breath GitHub Actions In A Monorepo: Caching, Path Filters, And Secret Boundaries That Actually Work The Blameless Postmortem That Actually Improves Things: A Template And Six Hard-Won Rules Recursive CTEs In Postgres: How To Query A Tree Without N Round Trips Node.js Streams: When They Actually Help, And When They Just Add Complexity Playwright Vs Cypress In 2024: The Honest Comparison Of Which One Earns The Test Time React Server Components: The Mental Model That Makes The "use client" Boundary Obvious Pod Disruption Budgets: The K8s Object That Keeps Your Service Up During Cluster Maintenance Postgres LISTEN/NOTIFY: The Pub/Sub You Already Have And Are Not Using Chaos Engineering Starter Kit: The Five Drills That Don't Need Netflix-Scale Spec-Driven API Development With OpenAPI: How To Stop Drifting From Your Docs Saga Pattern vs Two-Phase Commit: Distributed Transactions Without The Lies Kubernetes Autoscaling Beyond CPU: The Custom-Metric HPA Pattern That Actually Works Postgres Partitioning For Time-Series: The Boring Setup That Saves Your Database Distributed Locks With Redis: An Honest Look At Redlock And When You Don't Need It HTTP/2 vs HTTP/3: What Actually Changes For Your App, And What Doesn't Image Optimization For The Web In 2023: srcset, AVIF, And The Lighthouse Score You Actually Want Kafka vs RabbitMQ: A Decision Tree That Doesn't Hate You UUID vs Bigint Primary Keys In Postgres: The Index Math That Decides For You Flame Graphs: How To Find The Slow Function In 30 Seconds Without Profiling Theatre Postgres Streaming Vs. Logical Replication: Which One Solves Your Actual Problem ESLint Rules That Earn Their Keep: The Twelve I Enable On Every Project Pre-Commit Hooks That Pay For Themselves: Husky, lint-staged, And The Five Rules That Stick Zero-Downtime Database Migrations: The Six-Step Pattern That Rules Them All Circuit Breakers In Node.js: 50 Lines That Stop A Failing Dependency From Taking Down Your Service Postgres VACUUM Is Not Magic: How Your Hot Table Bloats To 80GB And How To Fix It Kubernetes Liveness And Readiness Probes: The Difference That Causes Half Your Outages Rate Limiting In Production: A Token Bucket In 30 Lines Of Redis Load Testing With k6: The Three Scenarios That Find Real Bugs (Not Synthetic Numbers) Postgres Row-Level Security For Multi-Tenant Apps: The Pattern That Stops You From Leaking Data Rebase vs. Merge: The Team Policy That Ends The Argument Forever OpenTelemetry in Node.js: Distributed Tracing That Actually Helps During an Incident Feature Flags That Pay Rent: The 4 Flag Types And When To Delete Each ETag, Last-Modified, and the Caching Headers Most APIs Get Wrong Connection Pooling Without the Cargo Cult: pgbouncer in 100 Lines of Config JSONB Is Not a Schema: When To Reach For It in Postgres, And When To Stop Bash Strict Mode: The Three Lines That Stop Your Deploy Script From Lying To You
The Outbox Pattern: How To Stop Losing Events When Postgres And Kafka Disagree
The Practica · 2022-11-25 · via The Practical Developer

The handler updates the order to paid in Postgres, then publishes an OrderPaid event to Kafka so the email service and the analytics pipeline pick it up. Most days, both succeed. Once a week, the database write commits and the Kafka publish times out, leaving the order paid in the database and no event for the rest of the system. The customer never gets a receipt. The dashboard undercounts revenue. The on-call gets paged Wednesday.

This is the classic dual-write problem: two systems, no common transaction. There is no clever ordering that fixes it. “Publish first, then write” has the symmetrical bug. The fix is the outbox pattern: write the event into the same database transaction as the state change, and publish it from there asynchronously. About 60 lines of code. Solves the problem permanently.

The pattern in one diagram

[ HTTP POST /pay ]


   BEGIN
     ├── UPDATE orders SET status='paid' WHERE id=42
     └── INSERT INTO outbox (topic, payload) VALUES ('OrderPaid', {...})
   COMMIT             ← atomic. Both rows committed or neither.

   ───── async, separate process ─────

  [ outbox dispatcher ]

     ├── SELECT * FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100
     ├── for each row: publish to Kafka
     └── UPDATE outbox SET published_at=now() WHERE id IN (...)

The state change and the intent to emit an event are in the same database transaction. They commit together. They roll back together. The dispatcher is a separate process that polls the outbox and publishes to Kafka. If the dispatcher crashes, events sit in the outbox until it comes back. If Kafka is down, events sit in the outbox until Kafka returns. There is no way for the database to commit a state change without the corresponding event being eventually delivered.

The schema

CREATE TABLE outbox (
  id            bigserial PRIMARY KEY,
  topic         text       NOT NULL,
  key           text,
  payload       jsonb      NOT NULL,
  published_at  timestamptz,
  attempts      int        NOT NULL DEFAULT 0,
  last_error    text,
  created_at    timestamptz NOT NULL DEFAULT now()
);

-- Partial index: the only rows we care about are unpublished.
CREATE INDEX outbox_unpublished_idx ON outbox (id)
  WHERE published_at IS NULL;

topic is the Kafka topic. key is the partition key (lets ordered consumers process events for the same entity in order). payload is the event body. published_at is the only “state”: null means not yet sent, non-null means sent.

The partial index keeps the dispatcher query fast even after millions of historical events live in the table. After a row is published, it is invisible to the index.

The producer side

This is the only thing application code has to remember: when you change state, also insert into outbox, in the same transaction.

async function markOrderPaid(orderId: string) {
  await db.transaction(async (tx) => {
    await tx.query(
      `UPDATE orders SET status = 'paid', paid_at = now() WHERE id = $1`,
      [orderId],
    );
    await tx.query(
      `INSERT INTO outbox (topic, key, payload) VALUES ($1, $2, $3)`,
      ['orders.paid', orderId, JSON.stringify({ orderId, paidAt: new Date() })],
    );
  });
}

That is the application’s entire responsibility. No fancy framework, no special “event” abstraction. A row in the outbox is a promise to publish, and the dispatcher fulfills the promise.

To prevent the same kind of bug elsewhere, wrap the pattern in a thin helper:

async function withOutbox<T>(
  events: { topic: string; key?: string; payload: unknown }[],
  fn: (tx: Tx) => Promise<T>,
): Promise<T> {
  return db.transaction(async (tx) => {
    const result = await fn(tx);
    for (const e of events) {
      await tx.query(
        `INSERT INTO outbox (topic, key, payload) VALUES ($1, $2, $3)`,
        [e.topic, e.key ?? null, JSON.stringify(e.payload)],
      );
    }
    return result;
  });
}

// Usage
await withOutbox(
  [{ topic: 'orders.paid', key: orderId, payload: { orderId } }],
  async (tx) => {
    await tx.query(`UPDATE orders SET status = 'paid' WHERE id = $1`, [orderId]);
  },
);

This eliminates the chance of a developer “forgetting” to insert into outbox: every state change goes through withOutbox, and the helper makes the event mandatory.

The dispatcher

import { Pool, PoolClient } from 'pg';
import { Kafka } from 'kafkajs';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const kafka = new Kafka({ brokers: process.env.KAFKA_BROKERS!.split(',') });
const producer = kafka.producer({ idempotent: true, maxInFlightRequests: 1 });

const POLL_INTERVAL_MS = 500;
const BATCH_SIZE       = 100;

export async function startDispatcher() {
  await producer.connect();
  let stopped = false;

  async function loop() {
    while (!stopped) {
      const sent = await tick();
      if (sent === 0) await sleep(POLL_INTERVAL_MS);
    }
  }
  loop().catch((e) => console.error('[outbox] crashed', e));
  return () => { stopped = true; };
}

async function tick(): Promise<number> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // Lock the next batch so a second dispatcher instance never picks the same rows.
    const { rows } = await client.query(
      `SELECT id, topic, key, payload
         FROM outbox
        WHERE published_at IS NULL
        ORDER BY id
        FOR UPDATE SKIP LOCKED
        LIMIT $1`,
      [BATCH_SIZE],
    );
    if (rows.length === 0) {
      await client.query('COMMIT');
      return 0;
    }

    // Publish to Kafka. Idempotent producer ensures Kafka does not duplicate
    // even if we retry the same message.
    await producer.send({
      topic: rows[0].topic, // assume one batch = one topic; or send per-row.
      messages: rows.map(r => ({
        key: r.key,
        value: JSON.stringify(r.payload),
        headers: { outbox_id: String(r.id) },
      })),
    });

    // Mark sent inside the same DB transaction we used to claim them.
    await client.query(
      `UPDATE outbox SET published_at = now() WHERE id = ANY($1)`,
      [rows.map(r => r.id)],
    );

    await client.query('COMMIT');
    return rows.length;
  } catch (err) {
    await client.query('ROLLBACK').catch(() => {});
    throw err;
  } finally {
    client.release();
  }
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

The key construct is FOR UPDATE SKIP LOCKED on the SELECT, the same trick the SKIP LOCKED job queue post uses. It lets multiple dispatcher instances run in parallel without coordinating, and without ever picking the same row.

A few non-obvious decisions baked in:

Idempotent producer. idempotent: true and maxInFlightRequests: 1 make Kafka deduplicate retries from the same producer instance, so if the network drops between producer.send and the database update, the next attempt does not produce a duplicate message in Kafka. Combined with the database update, you get effectively-once delivery into Kafka.

Batch publish, then update. The producer.send with multiple messages reduces round-trips. The follow-up UPDATE marks the whole batch published in one statement. If the producer fails, the transaction rolls back and the rows are unclaimed, and the next tick retries.

Transactional outbox insertion + marking. The BEGIN ... COMMIT around the whole dispatcher tick is what makes the system safe against dispatcher crashes mid-publish. If the process dies after producer.send but before UPDATE, the next dispatcher instance will pick the same rows and re-send. Idempotency on the consumer side handles the duplicate.

Idempotency on the consumer

Outbox guarantees at-least-once delivery, not exactly-once. Consumers must be idempotent. The standard pattern: every event has an ID (the outbox.id); the consumer keeps a record of processed IDs and ignores duplicates.

async function handleOrderPaid(event: { id: bigint; orderId: string; ... }) {
  await db.transaction(async (tx) => {
    const existing = await tx.query(
      `INSERT INTO processed_events (id) VALUES ($1) ON CONFLICT DO NOTHING`,
      [event.id],
    );
    if (existing.rowCount === 0) return; // already processed

    await sendReceiptEmail(event.orderId);
  });
}

The ON CONFLICT DO NOTHING is the deduplication gate. If a duplicate event arrives, the insert is a no-op, the email is not sent, and the consumer commits. This pattern is identical to the idempotency-key approach for inbound webhooks: same problem, same shape, different layer.

Performance and operational notes

Outbox table grows fast. A high-throughput service writes one outbox row per event. After a year, that table is huge. Two strategies: a periodic cleanup job that deletes rows older than N days where published_at IS NOT NULL, or partitioning by week and dropping old partitions. Whichever you pick, do it from day one. The table is much harder to clean up after a year of inattention.

Dispatcher latency. The polling interval determines worst-case publish latency. 500ms is fine for most use cases. If you need lower (sub-100ms), use Postgres LISTEN / NOTIFY: the producer fires NOTIFY outbox_new after inserting, the dispatcher LISTENs and only polls on the wakeup. Latency drops to single-digit milliseconds and CPU spent polling drops to zero.

Multiple dispatchers. Run two or three for redundancy. Because of SKIP LOCKED, they will not collide. If you run dozens, you may want partitioning of the outbox table by hash so each dispatcher polls a partition.

Backlog alerts. A growing count(*) WHERE published_at IS NULL is the signal that something is wrong: either the dispatcher is down, Kafka is unhappy, or the rate of writes has outpaced publish capacity. Alert on it.

-- Dashboard query:
SELECT count(*) FROM outbox WHERE published_at IS NULL;
SELECT count(*) FROM outbox WHERE published_at IS NULL AND created_at < now() - interval '5 minutes';

The second query is the one to alert on. Anything older than five minutes unprocessed is a problem.

Why not Debezium / CDC?

Debezium reads Postgres’ write-ahead log (WAL) and turns row changes into Kafka events directly, no outbox table needed. It is a real alternative, and the right choice if you can run it. Two reasons it does not always fit:

Operational complexity. Debezium adds a Kafka Connect cluster, a managed plugin, and a deep dependency on the Postgres replication slot, which, if the connector fails, will pin WAL forever and fill your disk. Most teams discover this at 3 a.m. The outbox pattern requires no extra infrastructure.

Schema control. With Debezium, your Kafka events are derived from row changes, so you cannot easily emit a “high-level” event (“OrderPaid”) that summarizes multiple row changes. Outbox lets you write whatever event shape your consumers want.

For teams already running Kafka Connect at scale, Debezium is great. For everyone else, especially anyone wanting their event schema decoupled from their database schema, outbox is simpler.

When you do not need the outbox

Two cases where the pattern is overkill:

Best-effort events. Notifications, analytics pings, events you can lose without a customer noticing. Direct publish-then-write or fire-and-forget is fine.

Synchronous downstream. If the downstream is the same database (a different table in the same Postgres), wrap both in one transaction. No queue needed.

For everything else where “this event must be delivered” (payment confirmations, fulfillment, audit logs, downstream search index updates), the outbox is the cheapest reliable choice.

The takeaway

The dual-write problem is permanent. It is not solved by ordering (“write first then publish”), retries (“just retry the publish”), or distributed transactions (XA / 2PC, which has its own catastrophic failure modes). It is solved by making the event part of the same database transaction as the state change, and publishing the event from the database to the message broker asynchronously.

Sixty lines of dispatcher code, one outbox table, idempotent consumers. That is the entire pattern. No team I have seen regrets adopting it. Several have regretted not adopting it, usually after a Saturday spent reconciling event streams against the database to find the events that got lost.


A note from Yojji

The kind of cross-system reliability work that prevents “the database said paid but no event went out” (outbox patterns, idempotent consumers, dispatcher monitoring) is the unglamorous backend work that decides whether your data and your event stream stay in agreement. It is the kind of engineering Yojji’s teams build into the production systems they ship.

Yojji is an international custom software development company founded in 2016, with teams across Europe, the US, and the UK. They specialize in the JavaScript ecosystem (React, Node.js, TypeScript), cloud platforms (AWS, Azure, GCP), and event-driven backends, including the message-flow plumbing that decides whether a system can be trusted with the customer’s money.