Should We Move Off MySQL? Assessing a Document Database Migration
System DesignModel answerLast updated
Decide whether replacing MySQL with MongoDB makes sense for a live service by analyzing workload evidence, correctness needs, and a safe dual-run cutover plan with measurable proof.
You lead the backend of a customer-facing service that has run on MySQL for several years with no major incidents. Another engineer proposes rewriting the storage layer on MongoDB, arguing it will "scale better" and that the flexible document model fits the service's JSON-heavy API responses.
You are skeptical but open-minded. Your task:
- Frame the decision. What evidence would you gather about the current workload before taking the proposal seriously? What specific pain points (if any) would actually justify a storage change?
- Compare the two options. Contrast the relational and document data models against this service's access patterns, covering joins, multi-record transactions, uniqueness and integrity constraints, schema flexibility, and indexing.
- Design the migration, assuming you decide to proceed: keep the service available throughout, move historical data, keep both stores consistent during transition, cut over safely, and be able to roll back.
- Prove the improvement. Define quantitative success criteria and how you'd measure them. Note explicitly why "we migrated" is not itself a result.
Constraints
- Zero-downtime is expected; the service cannot stop for a maintenance window.
- Correctness guarantees that MySQL currently provides (e.g., transactional updates across multiple rows, unique keys, foreign-key-style integrity) must not silently weaken.
- If the evidence does not support migrating, recommending "stay on MySQL" (possibly with tuning or sharding) is a fully valid answer.
Be concrete: name the artifacts you'd produce (dashboards, traces, benchmarks, runbooks) and the failure modes you'd guard against.
Hints
Hint 1
Start from access patterns, not from the database feature list: log the top queries, their fan-out joins, write/read ratio, p99 latencies, and transaction shapes before comparing engines.
Hint 2
MongoDB multi-document transactions exist but carry costs (snapshot isolation limits, retry logic, no FK enforcement) — map each MySQL guarantee to a concrete replacement or an explicit acceptance of weaker semantics.
Hint 3
Avoid naive dual-writes: application-level writes to two stores can diverge silently. Consider CDC (change data capture / binlog tailing) for the replication leg instead.
Hint 4
Define success numerically before cutover (p99 latency, throughput, error rate, cost per request) measured against a pre-migration baseline captured under representative traffic.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong answer treats this as a risk-management exercise driven by evidence, not a database comparison essay. Here's how I'd structure it.
1. Gather evidence first
The proposal is unfalsifiable until we know what's actually slow or painful. I'd collect:
- Query and workload profile: enable MySQL's slow-query log and performance schema for a representative week. Identify the top 20 queries by frequency and by total time, the read/write ratio, row sizes, result set sizes, and whether hot queries touch many tables via joins.
- Transaction and constraint inventory: list which code paths rely on multi-statement transactions, unique constraints (e.g., email uniqueness at signup), and foreign keys (or application-enforced equivalents). These are the guarantees that may be weaker or more expensive on MongoDB.
- Pain classification: is the actual pain (a) write throughput hitting single-primary limits, (b) read latency on complex joins, (c) painful schema migrations (ALTER TABLE locking), (d) operational scaling (replica lag, connection limits), or (e) developer friction mapping rows to JSON? Each pain has a different best remedy, and only some point to MongoDB.
- Growth projections: current QPS, data volume, and 2–3 year growth. If MySQL at 10k QPS with 500 GB won't hit meaningful limits for five years, migration cost likely exceeds benefit.
Key point to state explicitly: if the pain is read latency from bad indexes or N+1 queries, or ALTER TABLE pain, neither is solved uniquely by MongoDB — MySQL tuning, covering indexes, read replicas, or a schema-change tool (pt-online-schema-change, gh-ost) may fix it far cheaper. "Stay on MySQL" is a legitimate recommendation.
2. Model comparison against access patterns
When the document model genuinely wins: the dominant access pattern fetches a whole aggregate in one lookup — e.g., a user profile with embedded addresses, preferences, and recent activity. One find({_id}) replaces a five-table join. Writes also cluster inside that aggregate. Schema variance across documents (optional fields, evolving structures) avoids migrations entirely.
When it loses:
- Joins across aggregates: MongoDB's
$lookupis slower and less optimizable than a relational join with good indexes; frequent cross-entity queries argue for keeping the relational model. - Multi-record transactions: MySQL gives these for free with well-understood isolation. MongoDB supports multi-document ACID transactions since 4.0, but they're heavier — requiring retryable write logic, holding snapshot locks, and performing worse at scale. Money-movement or inventory-decrement paths that rely on
SELECT ... FOR UPDATEsemantics need careful redesign. - Integrity: no foreign keys or unique enforcement across collections beyond single-field unique indexes. Every invariant MySQL enforced declaratively becomes application code (with race conditions unless wrapped in transactions) or a background reconciliation job.
- Secondary indexes and ad-hoc queries: relational schemas handle exploratory/reporting queries gracefully; document models punish queries that don't match the pre-planned shape.
I'd draw the boundary explicitly: identify the 2–3 aggregates that dominate reads/writes, sketch the BSON documents, and check that ≥90% of hot operations become single-document or single-aggregate operations. If they don't, stop here.
3. Migration plan (zero downtime)
Phases:
- Baseline: capture current p50/p99 read and write latencies, error rates, throughput, and infra cost per request under production traffic. Freeze these numbers.
- Schema + validation: define collections, shard keys if sharding (chosen to match dominant query filters and distribute writes evenly — a bad shard key is the classic fatal mistake), JSON schema validators as a partial substitute for DDL constraints.
- Backfill: bulk-copy historical data from MySQL to MongoDB (mysqldump/streaming reader → bulk inserts), running throttled to avoid impacting production. Since backfill takes hours to days, use...
- Change data capture: tail the MySQL binlog (Debezium or similar) and stream ongoing changes to MongoDB. This avoids the divergence risk of application-level dual-writes: with dual-writes, a failed Mongo insert after a successful MySQL commit leaves the stores inconsistent with no recovery record; with CDC, MySQL remains the single source of truth and the pipeline replays deterministically. Dual-writes are acceptable only for low-stakes caches, not primary data.
- Verification: a reconciliation job comparing row/document counts and sampling checksums per key range; a shadow-read path that executes real queries against MongoDB and compares results (not returned to users yet).
- Gradual cutover: route 1% of reads to MongoDB behind a feature flag, compare latency/error metrics, ramp 5% → 25% → 100%. Then move writes — this is the hard part because we can't accept writes in both places safely with bidirectional sync. Options: a brief write-freeze of a few seconds while switching the primary (often acceptable even under "zero downtime" if the API queues requests), or a short dual-write window with CDC back-checks and a documented inconsistency repair. Read-only toggle should be reversible instantly; write cutover needs the most scrutiny.
- Rollback: keep MySQL fully functional and CDC-reverse-synced (or at least untouched) for a defined window (e.g., 2 weeks). Rollback = flip reads back, replay/verify writes made to MongoDB back into MySQL. Practice the rollback in staging before going live; an untested rollback isn't a rollback.
Runbook everything: each phase has entry criteria, exit criteria, abort triggers (error rate >X%, p99 regression >Y%), and an owner.
4. Proving improvement
"A technology change is not itself a performance result." Success must be numeric and pre-declared:
- p99 read latency for the top 10 queries improved by ≥N% vs. baseline.
- Sustained write throughput headroom increased by X factor.
- Error rate not worse than baseline (say, <0.01%).
- Infra cost per million requests decreased.
- Developer velocity proxy: schema-change lead time reduced.
Measure under real traffic (staged rollout cohorts, A/B between backends) — synthetic benchmarks routinely mislead because they miss production data distributions, lock contention, and connection patterns. Report regressions as honestly as wins; if the numbers show parity, say so and weigh the operational cost of running two skill sets and two backup/monitoring stacks.
Common pitfalls to call out
- Migrating because "JSON APIs map nicely to documents" — the ORM already handles that; serialization cost is rarely the bottleneck.
- Dual-writes without CDC or reconciliation.
- Choosing shard keys by convenience, creating hotspots or unshardable query patterns.
- Dropping referential integrity silently — bugs surface weeks later as orphaned data.
- No tested rollback path.
Bottom line: I'd spend the first week producing the workload evidence and a side-by-side cost estimate. Roughly speaking, migrations like this are justified maybe one time in three; when the workload is genuinely aggregate-centric with high write fan-out inside those aggregates and weak cross-entity query needs, MongoDB earns its place — otherwise tune, shard, or add caching on MySQL instead.