Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Eliminating Dual-Write Drift Between
DB & Search.

Eliminating dual-write drift between PostgreSQL and Elasticsearch requires replacing application-level REST calls with a Transactional Outbox + Debezium WAL CDC pipeline and Elasticsearch external_version concurrency control.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, never dual-write to Postgres and Elasticsearch in an HTTP handler—commit mutations to Postgres (with an Outbox or WAL CDC), stream via Kafka/Debezium, and apply version_type=external on ES upserts.

TL;DR30-second simplified summary
▾

Core Mechanics: Calling es.index(doc) inside the same request handler that writes to PostgreSQL (15M SKUs, 2,500 writes/sec peak) guarantees permanent index drift (3.2% stale prices and phantom in-stock items).

Visual & Structural Flow: Depicts Out-of-Order Dual-Write Overwrite vs. Debezium + ES External Version (Catalog API -> Postgres WAL -> Debezium/Kafka -> Elasticsearch); Postgres ACID Commit -> WAL Logical Replication -> Kafka -> ES Bulk (Catalog API -> PG WAL / Outbox -> Debezium + Kafka -> Elasticsearch).

Trade-Offs & Production: Two common patches still lose or reorder data: Async Fire-and-Forget: Spawning a background HTTP call to ES still drops updates on pod crashes and reorders concurrent edits. Zero-drift search sync decouples the write path completely: Single Source of Truth: The API writes only to PostgreSQL (optionally writing a compact outbox row in the same ACID transaction).

Failure Modes & Application: The Outbox/CDC + idempotent sink pattern is the universal antidote to dual-write drift: DB-to-Search Sync: Keeping Postgres/MySQL synchronized with Elasticsearch or OpenSearch.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Transactional Outbox Pattern
The Transactional Outbox pattern eliminates dual-write split-brain by inserting domain events into an outbox table inside the exact same ACID database transaction as the business state change, then relaying them asynchronously to Kafka/RabbitMQ.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why dual-write drift between PostgreSQL and Elasticsearch is inevitable.

Why this matters: The mechanism: understand how Why dual-write drift between PostgreSQL and Elasticsearch is inevitable works from first principles.

Think of Why dual-write drift between PostgreSQL and Elasticsearch is inevitable as the intuition layer for Eliminating Dual-Write Drift Between DB & Search: The mechanism: understand how Why dual-write drift between PostgreSQL and Elasticsearch is inevitable works from first principles.

Calling es.index(doc) inside the same request handler that writes to PostgreSQL (15M SKUs, 2,500 writes/sec peak) guarantees permanent index drift (3.2% stale prices and phantom in-stock items). Without a distributed 2PC transaction, Postgres can roll back after ES succeeded, ES can 429/timeout after Postgres committed, or concurrent updates can arrive at ES out of order.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

What happens under partial failures and out-of-order updates.

Why this matters: The problem: see what breaks without What happens under partial failures and out-of-order updates under real concurrency or scale.

Application-level dual writes fail in three ways:

  1. Phantom Stock: Postgres transaction rolls back, but ES already indexed stock = 5.
  2. Silent Missing Updates: ES returns 429 or times out after Postgres committed, leaving old prices live for hours.
  3. Out-of-Order Overwrites: Thread A's older $100 update arrives at ES after Thread B's newer $80 flash-sale update, overwriting $80 with $100.
Dual-Write Race vs. Versioned CDC

Out-of-Order Dual-Write Overwrite vs. Debezium + ES External Version

Catalog APIPostgres WALDebezium/KafkaElasticsearch1. TX1 ($100) then TX2 ($80)commit2. WAL streams LSN 101 ($100), 102($80)3. Bulk upsert version=102 ($80)4. Stale retry version=101 -> 409Drop!

Passing the monotonic LSN/version with version_type=external ensures Elasticsearch drops any stale out-of-order write.

Engineering Decision Framework
Problem
How to implement Eliminating Dual-Write Drift Between DB & Search without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep the architecture evolvable without sacrificing reliability, never dual-write to Postgres and Elasticsearch in an HTTP handler—commit mutations to Postgres (with an Outbox or WAL CDC), stream via Kafka/Debezium, and apply version_type=external on ES upserts.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Eliminating Dual-Write Drift Between DB & Search experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive solution (and why async fire-and-forget or updated_at polling breaks).

Why this matters: The problem: see what breaks without Naive solution under real concurrency or scale.

Two common patches still lose or reorder data:

  • Async Fire-and-Forget: Spawning a background HTTP call to ES still drops updates on pod crashes and reorders concurrent edits.
  • SELECT * WHERE updated_at > last_poll: Polls miss hard deletes, struggle at 2,500 writes/sec, and hammer the primary DB.
Component Topology

Naive solution (and why async fire-and-forget or updated_at polling breaks)

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Postgres WAL CDC (Debezium) + Kafka + ES External Versioning.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Zero-drift search sync decouples the write path completely:

  • Single Source of Truth: The API writes only to PostgreSQL (optionally writing a compact outbox row in the same ACID transaction).
  • WAL-Based CDC (Debezium -> Kafka): Debezium tails Postgres logical replication (pgoutput) with zero polling load on primary tables and publishes ordered events keyed by sku_id.
  • Idempotent Bulk Sink (<= 2 s p99): A Kafka Connect / consumer worker batches updates into ES _bulk using version=<lsn_or_epoch>&version_type=external so ES rejects stale versions (409 Conflict).
  • Backfill: Run an initial Debezium snapshot or sku_id-range backfill job to heal the existing 3.2% drift.
Zero-Drift CDC Pipeline

Postgres ACID Commit -> WAL Logical Replication -> Kafka -> ES Bulk

Catalog APIWrites PG onlyPG WAL / OutboxMonotonic LSNDebezium + KafkaKeyed by sku_idElasticsearchversion_type=external

1.Atomic Capture: Every committed PG mutation is guaranteed to appear in the WAL.

2.Zero DB Polling: Logical replication streams changes without SELECT * load on primary.

3.Ordered Partition: Keying Kafka by sku_id preserves per-SKU mutation order.

4.External Version: ES drops out-of-order/replayed updates with version <= current.

WAL CDC + ES external versioning eliminates partial failures and out-of-order overwrites within <= 2s p99.

// Elasticsearch _bulk upsert with monotonic external version (LSN / row_version)
{ "index": { "_index": "catalog_skus", "_id": "sku_98124", "version": 48291044, "version_type": "external" } }
{ "sku_id": "sku_98124", "price_cents": 7999, "in_stock": true, "updated_at": "2026-11-18T09:00:01Z" }
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where CDC + External Versioning applies in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

The Outbox/CDC + idempotent sink pattern is the universal antidote to dual-write drift:

  • DB-to-Search Sync: Keeping Postgres/MySQL synchronized with Elasticsearch or OpenSearch.
  • DB-to-Cache Invalidation: Invalidating or updating Redis keys from Debezium WAL streams.
  • CQRS Read Projections: Building denormalized read models and analytical lakes from OLTP primaries.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How does Elasticsearch version_type=external prevent out-of-order updates from corrupting catalog prices during retries or parallel consumers?

Recommended Learning Flow