Migrating MongoDB to Postgres JSONB
Fast recall
Quick revision
Core answer
Whether you can orchestrate a zero-downtime heterogeneous data-store migration with correctness and rollback guarantees
Big-bang cutover, assuming MongoDB and Postgres indexes are equivalent, or forgetting to reconcile lost writes
Use Debezium CDC + Kafka for dual-write, checksum-based reconciliation, feature-flagged read cutover, and a decision on which JSON fields to promote to real columns
Interview-ready guide
Interview answer
Frame the migration
- Zero downtime in three phases: backfill, dual-write, read cutover
- Always have rollback behind a feature flag
Describe each phase
- Phase 1: target schema with hot fields promoted, rest in JSONB + GIN; throttled backfill; row-count and checksum verification
- Phase 2: dual-write via Debezium CDC or app-level; idempotent upserts with
updated_atguard; DLQ for failed events - Phase 3: read cutover 1% → 10% → 50% → 100% with shadow-compare; retire MongoDB after a holding period
Call out pitfalls
- Schema drift — audit before; version if needed
- Oplog retention must exceed CDC lag
- BSON types need explicit mapping
- Index parity is not automatic; re-tune
Close
- The migration is mechanical if the schema is clean; messy if it isn't — so schema-audit first
Migrating MongoDB to Postgres JSONB
Direct Answer
The migration runs as a three-phase online cutover: (1) set up Postgres with a JSONB column and GIN indexes, backfill historical data with a one-shot batch job, and verify row counts and checksums; (2) dual-write from the application or via Debezium CDC + Kafka so new writes land in both stores, then reconcile; (3) switch reads gradually (10% → 50% → 100%) behind a feature flag, monitor parity and latency, then retire MongoDB. Key discipline is idempotent writes, checksum-based reconciliation, and rolling back per-read-path instead of big-bang. The migration is easy when the Mongo schema is reasonable; messy when documents have legacy shapes — so run a schema audit first and normalize flat fields out of JSONB into real columns only where query patterns demand it.
Common Mistakes & Pitfalls
Big-bang cutover, assuming MongoDB and Postgres indexes are equivalent, or forgetting to reconcile lost writes
Check your understanding
Answer these without looking back at the article.
- Which JSON fields would you promote to real columns and which keep in JSONB?
- How do you reconcile documents where MongoDB and Postgres diverge during dual-write?
- Why use Debezium CDC over application-level dual-write?
- How does `pg_trgm` compare to MongoDB text indexes for fuzzy search post-migration?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.