Senior 3 min · March 17, 2026

Polyglot Persistence — Dual Write Failure Omits Search

A PostgreSQL write succeeded but Elasticsearch timed out — no rollback left products missing from search.

N
Naren · Founder
Plain-English first. Then code. Then the interview question.
About
 ● Production Incident 🔎 Debug Guide
Quick Answer
  • Polyglot persistence: each access pattern gets its own database type.
  • Relational (PostgreSQL) for transactional data with ACID guarantees.
  • Redis for sub-millisecond session and cache lookups.
  • Elasticsearch for full-text search with typo tolerance.
  • Neo4j for graph traversal (recommendations, social features).
  • Hardest part: keeping data consistent across these systems — dual writes fail silently.
Plain-English First

Polyglot persistence means using different types of databases for different jobs. Think of a toolbox: you wouldn't use a hammer for every task — you use a screwdriver for screws, a wrench for bolts. Similarly, you use a relational database for orders, a cache for sessions, a search engine for product search, and a graph database for recommendations. Each database is optimised for a specific type of work.

Database Types and Their Sweet Spots

Each database type excels at specific access patterns. Relational databases enforce ACID and support complex joins – they're for transactional core. Document databases tolerate schema variations – ideal for catalogs. Key-value stores provide constant-time lookups – perfect for session data. Search engines invert indices for fast full-text queries. Graph databases traverse relationships efficiently. Time-series databases optimize for write-heavy append-only data. Choosing the wrong database for a pattern leads to painful workarounds: for example, using a relational database for full-text search leads to inefficient LIKE queries and poor relevance ranking.

ExamplePYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Package: io.thecodeforge.python.system_design

# Typical polyglot architecture for an e-commerce system:

# PostgreSQL — relational: users, orders, products, payments
# - ACID transactions: order.create() and inventory.decrement() atomically
# - Complex queries: reporting, joins between entities
# - Example: user creates an order

# Redis — key-value: sessions, caching, rate limiting
# - Sub-millisecond reads: session token → user object
# - TTL-based expiry: sessions expire automatically
# - Example: cache product page for 10 minutes

# Elasticsearch — search: product search with relevance
# - Full-text search with typo tolerance
# - Faceted search: filter by price, brand, rating
# - Example: user searches 'wireless headphones'

# MongoDB (document) — product catalogue
# - Flexible schema: different products have different attributes
# - Laptop has CPU, RAM; T-shirt has size, colour
# - Example: store varied product attributes without schema migration

# Neo4j (graph) — social features, recommendations
# - 'Users who bought X also bought Y'
# - Friend-of-friend queries
# - Example: find all users within 3 hops in social graph

# InfluxDB (time-series) — metrics, analytics
# - Write-optimised for timestamped data
# - Example: page views, API response times
Output
# Each database chosen for its access pattern strengths
The Full Toolbox Analogy
  • Relational = socket wrench (precise, standard, can handle many bolts)
  • Document = adjustable wrench (flexible, fits odd shapes)
  • Key-Value = screwdriver (fast, specific, limited range)
  • Search = power drill (specialized for one task but extremely fast)
  • Graph = pliers (excellent for gripping complex relationships)
Production Insight
Using the wrong database type for a workload creates production pain that's hard to undo.
Teams often attempt to 'make it work' with feature X of a relational DB, only to hit scaling limits.
Rule: if you're writing a full-text search engine on top of PostgreSQL FTS, buy yourself time but plan to migrate to a search-specific database.
Key Takeaway
Pick the database that matches the access pattern, not the one you're most comfortable with.
Your PostgreSQL won't become Elasticsearch with enough indices.
The best database is the one that makes your code simpler.
Choosing a Database Type
IfNeed ACID transactions across entities
UseUse a relational database (PostgreSQL, MySQL)
IfData structure varies per record (product attributes differ)
UseUse a document database (MongoDB, Couchbase)
IfSub-millisecond reads with TTL required
UseUse a key-value store (Redis, Memcached)
IfFull-text search with relevance ranking
UseUse a search engine (Elasticsearch, Solr)
IfDeep relationship traversal (friend-of-friend, recommendations)
UseUse a graph database (Neo4j, Amazon Neptune)
IfHigh-write throughput of timestamped data
UseUse a time-series database (InfluxDB, TimescaleDB)

Data Consistency Across Systems

Data consistency across multiple databases is the central challenge of polyglot persistence. When the same logical entity (e.g., a product) lives in PostgreSQL (source of truth) and Elasticsearch (search index), any update must propagate to both. Two common patterns: dual writes (application writes to both) and change data capture (CDC) where the primary database's write-ahead log is streamed to secondary systems. Dual writes are simple but fragile – partial failures leave data permanently inconsistent. The outbox pattern mitigates this by writing a message within the same transaction as the primary write, then having a separate process deliver it asynchronously. CDC avoids application-level dual writes entirely but adds infrastructure complexity (Debezium, Kafka).

ExamplePYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import asyncio

# When a product is created: must update PostgreSQL AND Elasticsearch
# Option 1: Dual write (naive — risks partial failure)
async def create_product_bad(product):
    await postgres.insert('products', product)      # succeeds
    await elasticsearch.index('products', product)  # what if this fails?
    # Product exists in Postgres but not in search — inconsistency

# Option 2: Write to primary, sync via CDC (Change Data Capture)
# Debezium reads PostgreSQL WAL → publishes to Kafka → Elasticsearch consumer
# Primary write is source of truth; Elasticsearch is eventually consistent

# Option 3: Outbox pattern
async def create_product_outbox(product):
    async with postgres.transaction():
        await postgres.insert('products', product)
        await postgres.insert('outbox', {
            'event': 'product_created',
            'data': product,
            'processed': False
        })
    # Separate process reads outbox and syncs to Elasticsearch
    # If it fails, retries safely (at-least-once delivery)

print('Outbox pattern ensures eventual consistency')
Output
Outbox pattern ensures eventual consistency
Production Insight
Dual writes fail silently in production – a timeout on the secondary write doesn't roll back the primary.
The outbox pattern gives you at-least-once delivery guarantees, but requires careful deduplication.
Rule: never dual-write to two databases without a transactional outbox or CDC.
Key Takeaway
Dual writes are the #1 cause of data inconsistency in polyglot systems.
Use the outbox pattern or CDC for reliable synchronization.
Accept eventual consistency – your users will forgive a few seconds of lag, not permanently missing data.

When to Adopt Polyglot Persistence

Polyglot persistence adds operational cost. Adopt it only when a single database clearly fails to meet requirements. Signs you need multiple databases: your relational database has a 3-second full-text search query, your document database can't enforce a unique constraint across documents, your key-value store can't do aggregation queries. Start with one database (usually relational) and add others incrementally. The rule: each new database must solve a problem that the existing stack cannot solve without significant hackery. If you can solve it with a secondary index, a materialized view, or a dedicated read replica, do that first.

Production Insight
Teams often adopt polyglot persistence prematurely, adding five databases to a system that only serves 1000 QPS.
The operational burden of managing multiple DBs – backups, monitoring, patching – grows non-linearly.
Rule: only add a database when you can't make the existing one work, and be ready to hire specialists for each.
Key Takeaway
Polyglot persistence is a solution, not a design goal.
Start with one database – add others only when you hit a measurable wall.
Each additional database is a long-term commitment to operational maintenance.
Should You Add Another Database?
IfCurrent database handles 95% of patterns adequately
UseDo not adopt polyglot – optimize existing database first.
IfSpecific pattern is 10x slower than alternative database
UseConsider adding one more database for that pattern.
IfTwo distinct patterns with conflicting requirements
UseSplit into two databases, each optimized for its pattern.

Operational Complexity Realities

Running a polyglot system means managing multiple database technologies, each with its own backup strategy, monitoring stack, scaling approach, and failure modes. You need expertise in each database – a PostgreSQL DBA might not know Elasticsearch shard sizing. Monitoring must cover each database's health metrics. Incident response becomes more complex because a single business transaction touches multiple systems. Invest in automation: consistent deployment via IaC, standardized monitoring dashboards, and runbooks for each database. The cost of this operational overhead must be justified by the business value gained from using the right tool.

Production Insight
In an outage, diagnosing a polyglot system takes longer because you have to check multiple databases and their sync state.
Example: a product reduction in PostgreSQL not reflecting in search because the CDC consumer crashed 4 hours ago.
Rule: invest heavily in observability (distributed tracing, log aggregation, synthetic transactions) across all databases.
Key Takeaway
Polyglot persistence doesn't eliminate operational complexity – it distributes it.
Your monitoring and alerting must cover every database's health and sync pipeline.
You can't have a polyglot system without a dedicated SRE team or equivalent automation.

Data Synchronization Patterns (Outbox, CDC, Batch)

Three common patterns to synchronize data between databases: 1) Outbox pattern: write to primary and an outbox table in the same transaction. A separate process reads the outbox and pushes to secondary systems. Guarantees at-least-once delivery. Requires deduplication. 2) Change Data Capture: use a tool like Debezium to stream changes from the primary database's transaction log. Decouples application from sync logic. Adds infrastructure components (Kafka, connectors). 3) Batch synchronization: scheduled jobs that periodically compare data between systems. Simple to implement but latency can be minutes to hours. Only suitable for non-critical data. Choose based on latency requirements and infrastructure maturity.

ExamplePYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Package: io.thecodeforge.python.sync_patterns

# Outbox pattern - reliable async sync
# Write to PostgreSQL and outbox in same transaction
async def outbox_create_product(product):
    async with postgres.transaction():
        await postgres.insert('products', product)
        await postgres.insert('outbox', {
            'event': 'product_created',
            'data': product,
            'processed': False
        })

# Worker process (runs periodically or via message queue)
async def outbox_worker():
    events = await postgres.query(
        "SELECT * FROM outbox WHERE processed = false"
    )
    for event in events:
        try:
            await elasticsearch.index('products', event.data)
            await postgres.update('outbox', 
                {'processed': True}, 
                {'id': event.id}
            )
        except Exception:
            # Retry later (exponential backoff)
            pass

print('Outbox pattern ensures eventual consistency with retries')
Output
Outbox pattern ensures eventual consistency with retries
Production Insight
CDC via Debezium + Kafka is the gold standard for low-latency sync, but it introduces operational complexity.
The outbox pattern is simpler and works well for most systems, provided the worker is resilient and idempotent.
Batch sync is the fallback – good for reporting systems where hourly updates are acceptable.
Rule: choose outbox for new systems; CDC for existing ones where you can't modify the application.
Key Takeaway
Outbox pattern is the simplest reliable sync mechanism – start there.
CDC decouples sync from application code but adds infrastructure.
Batch sync is for non-critical, high-latency-tolerant use cases only.
Choosing a Sync Pattern
IfLow latency required (< 1s), can modify application code
UseUse outbox pattern with a dedicated worker.
IfLow latency required, cannot modify application
UseUse CDC (Debezium + Kafka).
IfHigh latency acceptable (minutes to hours)
UseUse batch synchronization (cron job, scheduled query).
● Production incidentPOST-MORTEMseverity: high

Lost Products in Search After Dual Write Failure

Symptom
Users reporting that newly added products do not appear in search results. Old products are searchable.
Assumption
Search indexing is near-real-time; any delay should be seconds.
Root cause
Dual write pattern without transactional guarantees. PostgreSQL write succeeded, Elasticsearch write threw a timeout – no rollback, no retry. Products were permanently missing from search.
Fix
Implemented the outbox pattern: write product to PostgreSQL within a transaction, also insert an event row in an outbox table. A background worker reads outbox events and pushes them to Elasticsearch with retries. CDC via Debezium is an alternative.
Key lesson
  • Dual writes are fragile – a partial failure leaves data inconsistent.
  • Always use an outbox or CDC for multi-database updates.
  • Search should be eventually consistent – accept the delay, but guarantee delivery.
Production debug guideCommon symptoms and immediate diagnostic steps when synchronization fails3 entries
Symptom · 01
Product shows in PostgreSQL but not in Elasticsearch
Fix
Check the outbox table for unprocessed events. Query: SELECT * FROM outbox WHERE processed = false;. Also examine the CDC consumer lag if using Debezium.
Symptom · 02
Session data not found in Redis
Fix
Verify TTL expiry and Redis memory eviction policy (check maxmemory and eviction strategy). Use redis-cli to check memory usage and key count.
Symptom · 03
Graph recommendations stale or missing
Fix
Verify the CDC pipeline (Debezium + Kafka) is running and consumer lag is low. Check Kafka consumer offsets.
★ Polyglot Sync Quick DebugFive-minute diagnose for data synchronization issues in polyglot systems
New record missing in secondary database
Immediate action
Check application logs for write errors in the last 5 minutes.
Commands
SELECT * FROM outbox WHERE processed = false;
kubectl logs -l app=outbox-worker --tail=50
Fix now
Manually trigger a sync job: invoke /sync endpoint or run outbox worker once.
Stale data in search after update+
Immediate action
Check the last successful sync timestamp on Elasticsearch document.
Commands
curl -XGET 'localhost:9200/products/_search?q=_id:123'
kubectl logs -l app=cdc-connector --tail=20
Fix now
Force index refresh: POST /products/_refresh
Redis session not found but PostgreSQL session row exists+
Immediate action
Check Redis maxmemory and eviction policy.
Commands
redis-cli INFO memory | grep maxmemory
redis-cli CONFIG GET maxmemory-policy
Fix now
Increase maxmemory or adjust eviction policy; flush expired keys with redis-cli.
Database TypeBest ForExampleNot Good For
Relational (PostgreSQL)Transactional data, complex queriesOrders, users, paymentsFull-text search, graph traversal
Document (MongoDB)Flexible schema, nested dataProduct catalogue, CMSComplex multi-document transactions
Key-Value (Redis)Caching, sessions, queuesSession store, rate limiterComplex queries, large datasets
Search (Elasticsearch)Full-text search, analyticsProduct search, log analyticsPrimary storage, ACID transactions
Graph (Neo4j)Relationships, recommendationsSocial graph, fraud detectionWrite-heavy, simple key-value lookups
Time-Series (InfluxDB)Timestamped metricsMonitoring, IoTRelational data, flexible schema

Key takeaways

1
Polyglot persistence
use the right database for each access pattern, not one database for everything.
2
The hardest problem
keeping data consistent across multiple systems.
3
CDC (Change Data Capture) + Kafka is the standard pattern for syncing across systems.
4
Outbox pattern ensures at-least-once delivery without dual-write inconsistency.
5
Operational complexity increases with each database technology
justify each addition.
6
Start with one database, measure the pain, then add another only if necessary.

Common mistakes to avoid

3 patterns
×

Dual-writing to multiple databases without a transactional outbox

Symptom
Some data appears in PostgreSQL but not in Elasticsearch. Users report missing search results. Operational errors show intermittent timeouts on Elasticsearch writes.
Fix
Implement the outbox pattern: within the same database transaction, write the entity and an event record to an outbox table. A background worker reads unprocessed events and writes to secondary databases with retry logic.
×

Assuming all databases have the same consistency model

Symptom
A user reads from a read replica of PostgreSQL and sees stale data minutes after a write. Team assumes eventual consistency is 'instant' and makes business decisions based on stale data.
Fix
Understand each database's consistency guarantees. For PostgreSQL read replicas, there is replication lag. For Elasticsearch, index refreshes are near-real-time (1s default). Design your application to tolerate this staleness or use strong consistency reads where needed.
×

Adding a new database for every new feature without operational readiness

Symptom
Team struggles to manage backups, monitoring, and DB-specific failures. Each new database adds a new learning curve and pager duty rotation.
Fix
Establish a database onboarding process: assess operational impact, ensure monitoring and backup automation, document runbooks, and assign an owner before adding a new database to production.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
What is polyglot persistence and what are its benefits and drawbacks?
Q02SENIOR
How do you maintain consistency when data exists in both PostgreSQL and ...
Q03SENIOR
When would you choose Redis over a relational database for session stora...
Q04SENIOR
What operational challenges arise when managing a polyglot persistence s...
Q01 of 04SENIOR

What is polyglot persistence and what are its benefits and drawbacks?

ANSWER
Polyglot persistence is using multiple database technologies within a single application, each chosen for its specific strengths. Benefits: optimal performance per access pattern, reduced workarounds, better scalability. Drawbacks: operational complexity, data consistency challenges, higher cost for monitoring and expertise.
FAQ · 4 QUESTIONS

Frequently Asked Questions

01
When is polyglot persistence worth the complexity?
02
What is the biggest mistake teams make when adopting polyglot persistence?
03
How do you handle backups across different databases?
04
What is the difference between the outbox pattern and CDC?
🔥

That's Database Design. Mark it forged?

3 min read · try the examples if you haven't

Previous
CQRS with Databases
15 / 16 · Database Design
Next
Single Table Inheritance: When to Use It and When to Avoid It