MongoDB vs Cassandra¶
1. Decision¶
Choose MongoDB for flexible document-centric applications requiring rich secondary index filtering, ad-hoc nested queries, and master-slave single-leader consistency; choose Apache Cassandra (or ScyllaDB) for massive scale-out write throughput, masterless peer-to-peer ring architecture, zero single point of failure, and predictable high-velocity time-series/telemetry storage.
2. 30-Second Answer¶
MongoDB is a document-oriented database utilizing single-leader Replica Sets (CP in CAP theorem by default) optimized for dynamic schema flexibility, rich secondary indexes, and expressiveness via aggregation pipelines. Apache Cassandra is a masterless, wide-column distributed NoSQL database based on Amazon Dynamo and Google Bigtable architectures (AP in CAP theorem by default). Cassandra uses consistent hashing ring topologies, LSM-tree storage engines, and append-only commit logs, allowing linear write scalability across hundreds of nodes with zero master failover downtime. However, Cassandra requires strict access pattern modeling upfront around Partition Keys and Clustering Keys.
3. Decision Matrix¶
| Option | Best For | Avoid When | Latency | Scalability | Consistency | Operational Complexity |
|---|---|---|---|---|---|---|
| MongoDB | Dynamic document catalogs, e-commerce, user profiles, rich ad-hoc queries | Extreme write throughput (>100k QPS), zero-downtime multi-region masterless active-active writes | Low (<3ms read/write) | Horizontal via shard clusters (Config Servers + Mongos) | Strong (Single-leader primary); Configurable Read/Write Concerns | Medium |
| Apache Cassandra | High-velocity time-series, IoT telemetry, messaging logs, multi-region active-active | Ad-hoc filtering without partition key, multi-table joins, ACID transactions | Sub-millisecond append writes; Low reads | Extreme Linear Scale (Add nodes to ring seamlessly) | Tunable Quorum (\(R + W > N\)); Eventual consistency | High (JVM garbage collection, SSTable compaction) |
4. Selection Rules¶
| Requirement | Best Choice | Rationale / Example |
|---|---|---|
| Ultra-High Write Throughput (>100k QPS) | Cassandra | Append-only LSM-tree commit log writes without master node bottlenecks |
| Multi-Region Active-Active Writes | Cassandra | Masterless ring topology accepts writes in any data center simultaneously |
| Flexible Ad-Hoc Secondary Queries | MongoDB | Rich secondary indexes, geospatial indexing, and flexible aggregation stages |
| Time-Series / Immutable Append Logs | Cassandra | Data partitioned cleanly by entity ID and sorted on disk by timestamp clustering key |
| Single-Leader Strong Consistency Default | MongoDB | Reads/writes routed through single primary node prevent dirty reads |
| Zero Single Point of Failure Architecture | Cassandra | All nodes are equal peers; node failure causes zero election downtime |
5. Tradeoffs¶
- Master-Slave (MongoDB) vs Peer-to-Peer Masterless (Cassandra)
- Gain (MongoDB): Strong consistency per partition; simple single-leader mental model.
- Lose (MongoDB): Primary node failover causes temporary write outage (~2-5s election window).
- Query Flexibility vs Strict Access Pattern Modeling
- Gain (MongoDB): Query any nested document field dynamically with index support.
- Lose (MongoDB): Inferior write throughput scaling compared to Cassandra's append-only path.
- B-Tree/WiredTiger (MongoDB) vs LSM-Tree/SSTables (Cassandra)
- Gain (Cassandra): Sequential disk write performance (\(O(1)\) commit log append).
- Lose (Cassandra): Read amplification; requires compaction (Size-Tiered / Leveled) and Bloom filters.
- Tunable Quorum vs Fixed Master Read/Write Concerns
- Gain (Cassandra): Fine-grained control over read/write latency vs consistency per query (
ONE,QUORUM,ALL). - Lose (Cassandra): Eventual consistency anomalies (phantom reads, out-of-order writes without LWT).
- Operational Maintenance Overhead
- Gain (MongoDB): Simpler schema iteration and driver integration.
- Lose (MongoDB): Manual chunk balancing tuning under heavy write auto-sharding.
6. Interview Counter Questions¶
- How do MongoDB Replica Set elections differ from Cassandra's Gossip protocol and Hinted Handoff?
- What is the difference between a Partition Key and a Clustering Key in Cassandra?
- What is Read Amplification in Cassandra and how do Bloom Filters and Compaction mitigate it?
- How do you implement Strong Consistency in Cassandra using Tunable Quorum (\(R + W > N\))?
- Why are secondary indexes considered anti-patterns in Cassandra but encouraged in MongoDB?
- How does Cassandra handle node failures without data loss (Hinted Handoff & Read Repair)?
- What is Lightweight Transactions (LWT) in Cassandra and how does Paxos impact its performance?
- How does MongoDB WiredTiger storage engine compare to Cassandra's Memtable + SSTable architecture?
- When would you choose ScyllaDB over Apache Cassandra?
- How do you handle schema migrations in Cassandra when query patterns change?
10. Gold Standard Answers¶
- MongoDB relies on Raft-like primary node elections; if the primary dies, writes pause until a secondary is elected. Cassandra uses masterless Gossip protocol for cluster state detection and Hinted Handoff to store writes temporarily on peer nodes when a target node is down.
- In Cassandra, the Partition Key determines which node in the hash ring stores the data. The Clustering Key determines the physical sort order of rows within that partition on disk (e.g., Partition Key:
user_id, Clustering Key:timestamp DESC). - Read Amplification occurs because data for a row may span multiple immutable SSTables on disk. Cassandra mitigates this using Bloom Filters in RAM to instantly rule out SSTables that don't contain the key, and background Compaction to merge SSTables.
- Set Read Consistency + Write Consistency > Replication Factor (\(R + W > N\)). For example, with Replication Factor \(N=3\), choosing \(W=\text{QUORUM}\) (2 nodes) and \(R=\text{QUORUM}\) (2 nodes) ensures at least one node in the read response has the latest write.
- In Cassandra, data is distributed by Partition Key. A secondary index scan forces a scatter-gather query across every single node in the cluster. In MongoDB, secondary indexes can be routed effectively or filtered within shards.
- When a replica is down, the coordinator node writes a "hint" to its local disk. Once the target node recovers, the coordinator replays hints (Hinted Handoff). During reads, if data mismatches across replicas, Cassandra returns the newest timestamp and asynchronously triggers Read Repair.
- LWT uses a 4-round-trip Paxos consensus protocol to achieve linearizable consistency for conditional updates (
INSERT ... IF NOT EXISTS). It degrades Cassandra write performance significantly (4x latency overhead) compared to standard asynchronous writes. - WiredTiger (MongoDB) uses B-Trees / LSM with in-memory cache eviction and block compression. Cassandra uses pure append-only Memtables in RAM, flushed to immutable SSTables on disk, sacrificing read latency for extreme write throughput.
- ScyllaDB is a C++ rewrite of Cassandra that uses a thread-per-core asynchronous architecture, bypassing JVM Garbage Collection pauses and delivering 10x throughput with significantly lower tail latency (p99).
- Because Cassandra tables are designed strictly around query patterns, changing a query pattern requires creating a new table with a new partition/clustering key structure, backfilling historical data via Spark/CDC, dual-writing, and migrating read traffic.
8. Common Mistakes¶
- Using Cassandra like a relational or document DB by attempting ad-hoc
WHEREclause filtering on non-partition key columns. - Assuming Cassandra provides ACID transactions by default, leading to silent concurrency race conditions.
- Choosing MongoDB for multi-region active-active write topologies across global data centers (MongoDB single-primary causes high cross-region latency).
- Failing to monitor Cassandra JVM Garbage Collection (GC) pauses, which trigger false-positive node death signals in Gossip protocol.
- Over-indexing fields in Cassandra tables, creating massive scatter-gather read bottlenecks.
9. Keywords¶
Cassandra, MongoDB, Masterless Ring, Consistent Hashing, Partition Key, Clustering Key, SSTable, Memtable, LSM Tree, Bloom Filter, Compaction, Tunable Quorum, Gossip Protocol, Hinted Handoff, ScyllaDB, LWT Paxos.
10. Cheat Sheet¶
- Architecture: MongoDB = Single-leader primary per shard (CP default); Cassandra = Masterless Peer-to-Peer ring (AP default).
- Data Model: MongoDB = Dynamic BSON documents; Cassandra = Wide-column key-value/time-series partitions.
- Write Path: Cassandra append-only LSM Memtable/SSTable gives higher write throughput (>100k QPS) than MongoDB.
- Consistency: Cassandra = Tunable Quorum (\(R + W > N\)); MongoDB = Configurable Read/Write Concerns on Primary/Replicas.
- Query Flexibility: MongoDB supports arbitrary secondary index queries; Cassandra requires strict partition key modeling upfront.
- Multi-Region: Cassandra natively handles multi-region active-active writes; MongoDB primary must sit in a single region.