Bigtable vs MongoDB: Sorted Keyspace Mechanics, Row Atomicity, and the Cost of Secondary Query Flexibility
Bigtable is a wide-column store with a sorted, distributed keyspace. The row key is not just an identifier — it is the physical sort order. Two rows with adjacent keys are stored on adjacent SSTable blocks on the same tablet server. A scan for rows between device#00001 and device#00999 reads a contiguous range of SSTable blocks, achieving sequential I/O throughput on commodity SSDs. A scan for rows matching a complex predicate — where the predicate cannot be expressed as a bounded key range — reads every tablet in the table, regardless of selectivity.
MongoDB stores documents in WiredTiger B-Trees without any assumption about physical sort order relative to field values. Documents are heap-allocated; their physical location on disk is a function of insertion order and compaction history, not field value order. Ordering and filtering by field values is the responsibility of compound B-Tree indexes — separate data structures that WiredTiger maintains in sorted order and traverses during IXSCAN operations. Those indexes are powerful and flexible, but they are not free: each one occupies WiredTiger cache space, each one receives every write the collection does, and each one may or may not be used depending on whether the query planner finds its prefix ordering compatible with the query shape.
The choice between Bigtable and MongoDB is a choice between two fundamentally different theories of where query efficiency lives: in the physical arrangement of data (Bigtable) or in a separately maintained sorted index structure (MongoDB). Both work at billion-record scale. The failure mode in each case is attempting to query data in a way that the physical model does not natively support — and misidentifying the resulting degradation as a database performance problem rather than a schema design problem.
Situation
Bigtable is Google’s globally distributed wide-column store, used internally for Web indexing, Gmail, and YouTube, and available externally as Google Cloud Bigtable. MongoDB is a general-purpose document database used across OLTP, operational analytics, and content management workloads. They share JSON-like data storage but differ substantially in physical architecture.
| Dimension | Google Cloud Bigtable | MongoDB |
|---|---|---|
| Physical storage model | Sorted String Tables (SSTables) — immutable files of sorted key-value pairs; LSM-tree write path (memtable → SSTable flush → compaction) | WiredTiger B-Tree — mutable page tree with in-place updates via MVCC update chains; checkpoint-based persistence |
| Row key model | Single composite row key — arbitrary byte string, determines sort order and tablet placement | Document _id — arbitrary BSON value; shard key (optional) determines chunk placement in sharded deployments |
| Column model | Sparse wide columns — unlimited columns per row, organized in column families; no schema enforcement | BSON document — nested, typed fields; flexible schema per document; schema validation optional |
| Query model | Row key exact match, prefix scan, or bounded range scan; row filter on column values (not indexed — filter is post-scan) | Arbitrary predicate on any indexed field; compound B-Tree index supports multi-field filter, sort, and range |
| Secondary indexes | Not natively supported — must maintain alternate row representations or use Bigtable’s continuous materialized views (preview) | Native compound B-Tree indexes on any field or subfield combination; no hard limit; GSI-equivalent flexibility |
| Write path | LSM-tree: write goes to memtable (in-memory) → WAL → SSTable flush; compaction merges SSTables asynchronously | WiredTiger: write goes to journal (WAL) → in-memory update chain → checkpoint reconciles dirty pages to disk |
| Read path | SSTable scan with bloom filter lookups; no disk read if bloom filter eliminates block; sequential I/O for range scans | WiredTiger IXSCAN: B-Tree traversal on index pages (cache-resident or disk read); random I/O for scattered document fetches |
The Problem
Engineers selecting between Bigtable and MongoDB most commonly make the decision based on throughput benchmarks, not on access pattern expressibility. A benchmark showing Bigtable at 3M ops/sec and MongoDB at 800K ops/sec (at identical instance sizing) correctly represents throughput for the benchmark’s access pattern — but the benchmark is typically a key-value lookup or range scan, which is exactly the workload Bigtable’s architecture optimizes for. The question the benchmark does not answer is: what happens when the application needs to query by a field that is not the row key?
For Bigtable, the answer is a full table scan with row filter — O(N) scan cost regardless of the selectivity of the filter. A table with 10 billion rows, where only 10,000 rows match a filter on firmware_version = "2.4.1", requires reading all 10 billion rows through the filter to return 10,000 matches. The row filter evaluates cheaply (Bigtable’s server-side filtering avoids transmitting non-matching rows to the client) but still reads every SSTable block in the table — consuming the full table’s read bandwidth.
For MongoDB, the same filter with a compound index {firmware_version: 1} executes as an IXSCAN that reads only the index pages for firmware_version = "2.4.1" — O(log N + K) where K is the number of matching documents. But if the WiredTiger cache does not hold those index pages (cache eviction under memory pressure), each index page read is a physical SSD I/O operation. At 10B documents with a 50MB index for firmware_version, the index likely fits in cache if it is frequently used — but if the field has 50,000 distinct values and the index is 500MB, it may be partially evicted.
How do you choose between Bigtable’s sorted keyspace model (efficient for key-range queries, expensive for non-key filters) and MongoDB’s compound index model (flexible for arbitrary predicates, costly in cache and write amplification at scale)?
Bigtable’s LSM-Tree Write Path and Row Key Design Constraints
LSM-tree mechanics. Bigtable uses a Log-Structured Merge-tree (LSM-tree) write path: writes are appended to an in-memory memtable (with a write-ahead log for durability), then flushed to immutable SSTable files on Colossus (Google’s distributed file system) when the memtable fills. Compaction merges SSTables periodically, reclaiming space from deleted/overwritten cells and maintaining read performance by reducing the number of SSTable files the read path must check.
The LSM-tree write path achieves high write throughput by converting random writes to sequential writes (memtable appends are sequential in memory; SSTable flushes are sequential to disk). This is the fundamental reason Bigtable can absorb billions of writes per day without storage I/O bottlenecks — writes never modify existing data in-place; they always append new data, and compaction handles the rest asynchronously.
The tradeoff: reads must check the memtable + all unflushed SSTables + any compacted SSTables that overlap the row key range. Bigtable uses bloom filters per SSTable block to skip blocks that cannot contain the requested key — but for range scans across many rows, bloom filter efficiency diminishes and SSTable traversal dominates.
Row key design — the write distribution constraint. Because Bigtable routes tablets based on row key sort order, monotonically increasing row keys (like a Unix timestamp as the leading component) cause all new writes to land on the rightmost tablet — the “tablet hotspot” failure mode. A device telemetry table with rows keyed as timestamp#deviceId will concentrate all current-time writes on a single tablet, saturating its write throughput while all other tablets are idle.
The standard mitigation is a key prefix that distributes writes across the key space:
import hashlib
import time
from datetime import datetime
from google.cloud import bigtable
client = bigtable.Client(project="my-project", admin=True)
instance = client.instance("my-instance")
table = instance.table("device-telemetry")
def make_row_key(device_id: str, timestamp: datetime) -> str:
"""
Anti-pattern: timestamp#device_id — concentrates writes on one tablet
Pattern: hash_prefix#device_id#reverse_timestamp — distributes writes
reverse_timestamp = (max_timestamp - timestamp) makes recent data sort FIRST
within each device, supporting "get latest N readings for device" efficiently.
"""
# 2-char hash prefix from device_id distributes ~256 tablet regions
prefix = hashlib.md5(device_id.encode()).hexdigest()[:2]
# Reverse timestamp: subtract from max so recent entries sort first
max_ts = 9999999999 # Unix timestamp far in the future
reverse_ts = max_ts - int(timestamp.timestamp())
return f"{prefix}#{device_id}#{reverse_ts:010d}"
def write_telemetry(device_id: str, temperature: float, timestamp: datetime):
row_key = make_row_key(device_id, timestamp)
row = table.direct_row(row_key)
row.set_cell(
column_family_id="telemetry",
column="temperature",
value=str(temperature).encode(),
timestamp_micros=int(timestamp.timestamp() * 1_000_000)
)
row.commit()
def read_latest_n_readings(device_id: str, n: int = 10) -> list:
"""Read latest N readings for a device — efficient bounded key range scan."""
prefix = hashlib.md5(device_id.encode()).hexdigest()[:2]
max_ts = 9999999999
# Start key: device prefix (smallest reverse_ts = most recent)
start_key = f"{prefix}#{device_id}#"
# End key: device prefix + one character beyond (exclusive)
end_key = f"{prefix}#{device_id}$"
rows = table.read_rows(
start_key=start_key.encode(),
end_key=end_key.encode(),
limit=n
)
return list(rows)
Bigtable Key Visualizer — detecting tablet hotspots. Google Cloud Console’s Key Visualizer displays a heatmap of read/write throughput by row key range over time. A healthy Bigtable table shows uniform color distribution across the key space. A table with a monotonic leading key shows a bright right-edge column — the current tablet receiving all writes — while the remainder of the key space is dark. Key Visualizer is the primary diagnostic for Bigtable row key design issues.
# Cloud Bigtable metrics via gcloud — table-level throughput and error rates
gcloud bigtable tables describe my-table --instance=my-instance
# Fetch detailed metrics via Cloud Monitoring
# Key metrics for hotspot detection:
# bigtable.googleapis.com/server/request_count filtered by cluster and table
# bigtable.googleapis.com/server/latencies (p99) — high p99 on one tablet = hotspot
# bigtable.googleapis.com/server/cpu_load — per-node CPU; skew = tablet imbalance
MongoDB Compound Index Mechanics and Write Amplification at Scale
Index write amplification — measured. Each MongoDB compound index requires a WiredTiger B-Tree write for every document operation. The write amplification ratio can be measured directly:
// Measure write amplification ratio — run before and after a bulk operation
const before = db.serverStatus().wiredTiger.cache;
const beforeWrites = before["pages written from cache"];
const beforeInserts = db.serverStatus().opcounters.insert;
// ... perform 10,000 inserts ...
const after = db.serverStatus().wiredTiger.cache;
const afterWrites = after["pages written from cache"];
const afterInserts = db.serverStatus().opcounters.insert;
const pagesPerInsert = (afterWrites - beforeWrites) / (afterInserts - beforeInserts);
const indexCount = db.devices.getIndexes().length;
print(`Indexes: ${indexCount}, Pages written per insert: ${pagesPerInsert.toFixed(1)}`);
// Healthy: ~1.5-3x indexes (not all inserts split a page)
// Concerning: >5x indexes (frequent page splits during bulk insert)
Cache pressure from index pages. For a MongoDB collection with 500M documents at 800 bytes average document size (400 GB total), a compound index on {firmwareVersion: 1, lastSeen: -1} at 50 bytes per index key generates approximately 25 GB of uncompressed index data. With WiredTiger’s B-Tree prefix compression (~60% reduction for low-cardinality leading fields), the compressed index is ~10 GB on disk. The uncompressed WiredTiger cache footprint is 25 GB — meaning this single index occupies 25 GB of the configured cacheSizeGB.
On a server with 128 GB RAM and cacheSizeGB: 76 (60% of RAM), the document working set plus all indexes must fit within 76 GB. With multiple compound indexes, the aggregate cache pressure is the sum of all index working sets plus the active document working set — not just the document set alone.
// Estimate cache impact of each index
db.devices.stats().indexSizes // Compressed on-disk index sizes
// Multiply each value by 2.5-4x for uncompressed WiredTiger cache footprint
// Monitor which indexes are actually loaded into cache (indirectly via usage)
db.devices.aggregate([
{$indexStats: {}},
{$sort: {"accesses.ops": -1}},
{$project: {
name: 1,
ops: "$accesses.ops",
since: "$accesses.since",
diskSizeMB: {$divide: [{$arrayElemAt: [
{$objectToArray: db.devices.stats().indexSizes}, "$$ROOT.name"
]}, 1048576]}
}}
])
In Practice
The access pattern grid — choosing the physical model. The documented guidance from both Google (Cloud Bigtable schema design guide) and MongoDB (data modeling documentation) converges on the same prerequisite: enumerate access patterns before choosing the physical model. The grid below shows which queries are native vs. expensive in each model:
| Access Pattern | Bigtable Efficiency | MongoDB Efficiency |
|---|---|---|
| Get all records for device in time range | ✅ Native — bounded key range scan on device#reverse_ts prefix | ✅ Native — IXSCAN on {deviceId: 1, timestamp: -1} compound index |
| Get latest N records across all devices | ❌ Requires full scan or maintained “latest” row | ✅ IXSCAN on {timestamp: -1} with limit |
| Find devices with firmware = “2.4.1” | ❌ Full scan with row filter — O(N) | ✅ IXSCAN on {firmwareVersion: 1} — O(log N + K) |
| Find devices meeting 3+ field predicates | ❌ Multi-pass scan with compound filter — O(N) per pass | ✅ Compound index following ESR rule |
| Aggregate (count, sum) across all devices by region | ❌ Full scan — expensive but achievable | ⚠️ COLLSCAN or partial index + aggregation pipeline |
| Write 500K telemetry records/sec | ✅ LSM-tree absorbs writes with sequential I/O | ⚠️ WiredTiger random B-Tree writes; scales with IOPS budget |
Where It Breaks
| Failure Mode | Root Cause | Production Blast Radius | Mitigation |
|---|---|---|---|
| Bigtable timestamp-first row key — tablet hotspot | Monotonically increasing leading key component routes all current writes to one tablet; tablet saturates its write throughput | RESOURCE_EXHAUSTED or elevated write latency for all writes; Key Visualizer shows a bright right-edge heatmap column | Redesign row key with distributing prefix (hash of device ID, tenant ID, or geographic shard) as the leading component; test key distribution with Key Visualizer before production launch |
| Bigtable filter on non-key field — full table scan | Application queries Bigtable by a field that is not expressible as a bounded row key range; ReadRows with a RowFilter on a non-key column reads all tablets | Table-level read bandwidth consumed regardless of filter selectivity; at 10B rows, a non-key filter query consumes the same I/O as reading the full table | Maintain alternate row representations for frequent non-key queries (pre-compute a second row with a key that matches the alternate access pattern); for ad-hoc queries, route to a downstream analytical store (BigQuery, OpenSearch) populated via Bigtable Data Boost or Change Data Capture |
| Bigtable row unbounded growth — row size violation | Time-series data accumulated in a single row without time bucketing; row exceeds 256 MB (Bigtable’s hard per-row limit) or causes cell-level lock contention | Write failures with INVALID_ARGUMENT when row exceeds 256 MB; read latency increases as row size grows (entire row must be deserialized); high contention on frequently written rows | Design with time buckets in the row key (e.g., device#YYYY-MM rather than device#all-time); validate maximum row growth rate at design time: bytes_per_event × events_per_second × bucket_duration_seconds < 100MB |
| MongoDB compound index — ESR violation, in-memory sort abort | Compound index field order does not match ESR rule for the query’s filter/sort pattern; planner inserts SORT stage; result set pre-sort exceeds 100MB | Query aborts with Sort exceeded memory limit of 104857600 bytes; application receives error for previously-working queries as data volume grows | Run explain("executionStats") on all production query shapes; any plan containing a SORT stage above the IXSCAN is a latent time-bomb; rebuild compound index with correct ESR ordering |
| MongoDB scatter-gather on non-shard-key filter — shard fanout | Sharded MongoDB collection queried by a field that is not the shard key; mongos broadcasts to all shards; response time is max(all shard latencies) | Latency spikes proportional to shard count; a 10-shard cluster with 5 unhealthy shards produces p99 latency equal to the slowest shard’s latency on every scatter-gather query | Identify scatter-gather queries via explain() looking for SHARD_MERGE stage; include shard key in all production queries where possible; accept explicit scatter-gather only for administrative or analytics queries |
| Bigtable replication eventual consistency — cross-cluster read lag | Multi-cluster Bigtable replication delivers updates asynchronously; reads from a secondary cluster may lag writes to the primary cluster by milliseconds to seconds | Write-then-read patterns fail: device updates its status, status query returns stale pre-update value; for control plane applications this can cause repeated commands | For read-after-write consistency, configure the app profile to route reads and writes to the same cluster (single-cluster routing sacrifices availability for consistency); verify replication lag via the bigtable.googleapis.com/replication/max_delay metric |
| MongoDB index cache eviction — IXSCAN latency spike | A new index is added to a collection; index pages are not cache-resident; first IXSCAN reads index pages from disk | IXSCAN latency is 10–100× higher than normal during the cache warm-up period (seconds to minutes depending on index size and WiredTiger cache headroom) | Pre-warm index cache after creation: run representative queries against the new index during off-peak hours before routing production traffic; monitor pages read into cache metric during warm-up |
| Bigtable Data Boost — analytical query competes with serving | Data Boost provides serverless compute for analytics but still reads from the same underlying SSTable files on Colossus; heavy Data Boost scans can increase tablet server latency by increasing SSTable file access contention | Serving latency increases during Data Boost analytical scans even though Data Boost is designed to isolate analytical workload | Use Data Boost exclusively for analytics that cannot be scheduled off-peak; implement SSTable-level resource quotas; monitor server/latencies on serving cluster during Data Boost jobs and set a latency SLO breach alert that triggers job suspension |
2026 Bigtable and MongoDB Update
Google Cloud Bigtable released continuous materialized views (GA in 2025) — allowing a pre-defined aggregation or projection to be maintained in near-real-time as a separate logical view, addressable by row key. This addresses the most common Bigtable access pattern gap: queries that require grouping or projection on non-key fields can now be served from a maintained view rather than requiring a full table scan. The view is subject to documented replication lag and does not support arbitrary aggregations — but for the specific case of maintaining a “latest state per device” view from a time-series table, continuous materialized views eliminate the previously required dual-write application pattern.
MongoDB 8.0 (GA October 2024) shipped improved shard key analysis via analyzeShardKey — providing cardinality, frequency, and monotonicity analysis for candidate shard keys before committing. The monotonicity check specifically identifies keys that would cause the “write heap” problem in a ranged-sharded collection — the same tablet hotspot failure mode that Bigtable’s sorted keyspace creates with timestamp-first row keys.
What to Do Next
- Problem: Bigtable’s sorted keyspace provides O(1) writes and O(log N) range reads for key-expressible queries, but falls back to O(N) full-table scans for any filter on a non-key field — a degradation that is invisible in benchmarks but catastrophic in production when unanticipated access patterns emerge.
- Solution: Map every application access pattern against the row key before table creation; any pattern that cannot be expressed as a bounded row key range must either be modeled as an alternate row representation, served from a downstream analytical store, or accepted as O(N) cost — explicitly budgeted and capacity-planned.
- Proof: Google’s Bigtable schema design documentation explicitly states: “Bigtable is not a relational database and doesn’t support joins or anything resembling SQL queries”; efficient reads require the row key to express the query’s data locality — every other query pattern incurs full or partial table scan cost.
- Action: For your highest-traffic non-key-column filter query in Bigtable (or the equivalent COLLSCAN in MongoDB), measure its read amplification: how many rows (Bigtable) or documents (MongoDB) does it examine vs. return? That ratio is the cost of your current schema mismatch — and a direct measure of how much your access pattern inventory was incomplete at table design time.
Sources to Verify
- Google Cloud Bigtable — Schema Design Best Practices and Row Key Anti-patterns: https://cloud.google.com/bigtable/docs/schema-design
- Google Cloud Bigtable — Time-Series Schema Design and Key Distribution: https://cloud.google.com/bigtable/docs/schema-design-time-series
- Google Cloud Bigtable — Continuous Materialized Views (GA 2025): https://cloud.google.com/bigtable/docs/continuous-materialized-views
- Google Cloud Bigtable — Data Boost Overview and Resource Isolation: https://cloud.google.com/bigtable/docs/data-boost-overview
- WiredTiger LSM-Tree vs B-Tree Architecture — Storage Engine Design Tradeoffs: https://source.wiredtiger.com/develop/arch-schema.html
- MongoDB Manual — Sharding — analyzeShardKey and Shard Key Selection: https://www.mongodb.com/docs/manual/core/sharding-shard-key/
- LevelDB and LSM-Tree Design — Google Research: https://research.google/pubs/pub33023/