What You'll Learn
- 1Explain the tablet server model and how it differs from a primary-replica database
- 2Design row keys that spread load instead of concentrating it on one node
- 3Choose column families and garbage collection policies per access pattern
- 4Pick the right consistency and routing option for a read path
Bigtable is a sparse, distributed, persistent multidimensional sorted map keyed by row key, column qualifier, and timestamp. Everything practical about it follows from that definition: there are no schemas beyond column families, an absent column costs nothing, reads and writes are scoped to a row range, and the sort order of row keys determines which servers do the work. It is the storage behind Google Search and Maps, and the same shape suits telemetry, time series, and event logs where the access pattern is append and scan rather than ad hoc join.
Bigtable Architecture
A cluster is made of one or more nodes, each serving a slice of the tablet space. Tables are partitioned into tablets of roughly one hundred to two hundred megabytes, and tablets are distributed across nodes by key range, so scaling is a matter of splitting ranges and moving them rather than redesigning anything. Because the split point follows the key, the row key design is not a storage detail: it decides load balance for the life of the table.
Storage is separate from serving. Nodes hold cached blocks and handle requests, while the durable copy lives in Colossus with replication across zones, so losing a node degrades cache warmth rather than data. That split is why adding nodes improves throughput almost immediately while disk capacity grows independently.
| Property | Bigtable | Firestore | BigQuery |
|---|---|---|---|
| Model | Wide column, sorted rows | Documents in collections | Columnar warehouse tables |
| Key access | Row key range scan | Point and indexed queries | SQL over the whole table |
| Peak throughput | Millions of ops per node | Tens of thousands per doc rules | Queries, not row operations |
| Schema | Column families only | Flexible per document | Declared columns and types |
| Best fit | Telemetry, time series | Profiles, sessions, state | Analytics and reporting |
Architecture Overview
Schema Design
Row key design is the single decision with the largest blast radius. The key determines physical locality, so two rows with adjacent keys are stored together and are likely served by the same tablet. The failure mode is a monotonically increasing key such as a timestamp prefix, which sends every new write to the last tablet and leaves the rest of the cluster idle while one node saturates. The fix is to reverse the leading component or to prefix a hash bucket, so writes spread across the key space while reads still target a known range.
The second decision is how the row key encodes the query. Bigtable has no secondary indexes, so a read must be expressible as a key range: put the entity identifier first for per-entity lookups, or put time first if the workload is a scan across entities over a window, and accept that the other query will need a different layout or a second table.
from google.cloud import bigtable
from google.cloud.bigtable import column_family
from google.cloud.bigtable.row_set import RowSet
import datetime
# Initialize Bigtable client
client = bigtable.Client(project="my-project", admin=True)
instance = client.instance("my-instance")
# Create table with column families
table_id = "sensor_data"
table = instance.table(table_id)
# Define column families with GC policies
cf_readings = column_family.MaxVersionsGCPolicy(1) # Keep 1 version
cf_metadata = column_family.MaxVersionsGCPolicy(10) # Keep 10 versions
table.create(column_families={
"readings": cf_readings,
"metadata": cf_metadata
})
print(f"Created table: {table.table_id}")
Row Key Examples
import hashlib
import time
def design_row_key(device_id, timestamp):
"""Design an efficient row key for time-series data."""
# Option 1: Device ID + reversed timestamp
max_ts = 9999999999999 # Max timestamp
reversed_ts = max_ts - int(timestamp.timestamp() * 1000)
row_key = f"{device_id}#{reversed_ts:013d}"
return row_key
def design_row_key_with_salt(device_id, timestamp):
"""Add salt for even distribution."""
# Hash device ID for even distribution
hash_prefix = hashlib.md5(device_id.encode()).hexdigest()[:2]
# Reverse timestamp for time-series ordering
max_ts = 9999999999999
reversed_ts = max_ts - int(timestamp.timestamp() * 1000)
return f"{hash_prefix}#{device_id}#{reversed_ts:013d}"
# Example usage
device_id = "sensor_123"
timestamp = datetime.datetime.now()
row_key = design_row_key(device_id, timestamp)
print(f"Row key: {row_key}") # sensor_123#9999999999999
Writing Data
Writes in Bigtable are mutations against a row: set a cell, delete a column qualifier, delete a row, or delete a row range. There is no read-modify-write cycle unless you ask for one, so a counter pattern must either reserve a separate cell per writer or use a check-and-mutate transaction on a single row. Mutation latency is paid per request, which is why applications that emit telemetry batch cells for the same row into one call instead of issuing three.
Throughput is quoted per node rather than per table, and it is sustained only when keys are well distributed. A single node handles on the order of tens of thousands of writes per second with an appropriate row key, and a table with a hotspot key will not get faster by adding nodes. When a workload genuinely needs more, the usual answer is more nodes plus a key redesign, because the second half of that sentence is the one that actually fixes it.
from google.cloud import bigtable
from google.cloud.bigtable import column_family
from google.cloud.bigtable.row import DirectRow
import datetime
def write_sensor_data(instance, table_id, device_id, readings):
"""Write sensor data to Bigtable."""
table = instance.table(table_id)
# Create row with timestamp-based key
timestamp = datetime.datetime.now()
max_ts = 9999999999999
reversed_ts = max_ts - int(timestamp.timestamp() * 1000)
row_key = f"{device_id}#{reversed_ts:013d}"
# Create row
row = table.direct_row(row_key)
# Add readings
row.set_cell(
"readings",
"temperature".encode(),
str(readings["temperature"]).encode(),
timestamp=timestamp
)
row.set_cell(
"readings",
"humidity".encode(),
str(readings["humidity"]).encode(),
timestamp=timestamp
)
row.set_cell(
"readings",
"pressure".encode(),
str(readings["pressure"]).encode(),
timestamp=timestamp
)
# Add metadata
row.set_cell(
"metadata",
"location".encode(),
readings.get("location", "unknown").encode(),
timestamp=timestamp
)
# Commit the row
row.commit()
print(f"Written row: {row_key}")
# Example usage
readings = {
"temperature": 23.5,
"humidity": 65.2,
"pressure": 1013.25,
"location": "warehouse_a"
}
write_sensor_data(instance, "sensor_data", "sensor_123", readings)
Reading Data
A read is either a point lookup on an exact row key or a scan over a row range, and the range is where cost and latency live. Scanning from a prefix and stopping at the next prefix touches only the tablets covering that span, while an open-ended scan pulls the rest of the table through the service. Cell filters narrow the read further: ask for one column qualifier, one family, or a timestamp range, and the server returns only those cells instead of every version stored.
The pattern to internalise is that Bigtable optimises for sequential access. Reading one device's history for the last hour is a single narrow range and is fast; reading the latest reading for every device is a scatter across the entire key space and costs one round trip per device. The second shape is what dashboards usually want, so it is usually answered by a second table whose key is designed for that access pattern instead.
def read_time_range(instance, table_id, device_id, start_time, end_time):
"""Read data for a device within a time range."""
table = instance.table(table_id)
# Create row range based on reversed timestamps
max_ts = 9999999999999
start_reversed = max_ts - int(end_time.timestamp() * 1000)
end_reversed = max_ts - int(start_time.timestamp() * 1000)
row_range = bigtable.row_range.RowRange(
start_key=f"{device_id}#{start_reversed:013d}".encode(),
end_key=f"{device_id}#{end_reversed:013d}".encode()
)
# Read rows
rows = table.read_rows(row_range=row_range)
results = []
for row in rows:
readings = {
"row_key": row.row_key.decode(),
"temperature": float(row.cells["readings"][b"temperature"][0].value.decode()),
"humidity": float(row.cells["readings"][b"humidity"][0].value.decode()),
"pressure": float(row.cells["readings"][b"pressure"][0].value.decode()),
}
results.append(readings)
return results
Garbage Collection Policies
Garbage collection is the only retention control Bigtable has, and it is defined per column family at table creation. The policy compacts old versions away in the background rather than deleting rows outright, so storage shrinks gradually and reads never return superseded values that a policy already ruled out. Choosing the policy is really choosing what a reader is allowed to see, which is why different families on the same table carry different rules.
The three shapes cover nearly every workload. Keep the newest version only for sensor readings, where the current value is the query. Keep versions for a bounded window when audit history matters. Combine a maximum age with a maximum version count when both matter, using a union rule so whichever bound is hit first wins. Row-level deletion is a separate operation and is how a record is removed from the table entirely.
from google.cloud.bigtable import column_family
# Policy 1: Keep last N versions
cf_versions = column_family.MaxVersionsGCPolicy(5)
# Policy 2: Keep data for N days
cf_days = column_family.MaxAgeGCPolicy(datetime.timedelta(days=30))
# Policy 3: Combined policy
cf_combined = column_family.GCRules.union(
column_family.MaxVersionsGCPolicy(3),
column_family.MaxAgeGCPolicy(datetime.timedelta(days=7))
)
# Policy 4: Per-column-family GC
table.create(column_families={
"readings": column_family.MaxVersionsGCPolicy(1), # Latest only
"metadata": column_family.MaxAgeGCPolicy(datetime.timedelta(days=365)),
"logs": column_family.MaxAgeGCPolicy(datetime.timedelta(days=30))
})
â¨
Best Practice: Use MaxVersionsGCPolicy(1) for sensor readings (keep latest), MaxAgeGCPolicy for historical data retention, and combined policies for complex requirements. GC policies are critical for controlling storage costs in Bigtable.
Common Interview Questions
Q1: What is the difference between Bigtable and Firestore?
Answer: Bigtable is a wide-column store optimized for high-throughput time-series and analytical workloads (IoT, metrics, logs). Firestore is a document database for structured data with complex queries. Bigtable has higher throughput (millions of ops/sec) but limited query capabilities. Firestore supports richer queries but has lower throughput limits.
Q2: How do you design row keys for time-series data?
Answer: Use composite keys such as device_id then a reversed millisecond timestamp. Reversing the timestamp ensures newest data is read first. Add a hash prefix for even distribution across nodes. Avoid monotonically increasing keys as they create hotspots. Consider using device_id or user_id as the entity prefix.
Q3: What is the purpose of column families?
Answer: Column families group columns by access pattern and enable garbage collection policies. They determine data locality and storage efficiency. Keep a table to fewer than 100 column families. Use different GC policies per family: MaxVersions for sensor data, MaxAge for historical data.
Q4: How does Bigtable replication work?
Answer: Bigtable automatically replicates data across clusters for high availability. You can configure cluster storage type (SSD/HDD) per cluster. Replication is eventually consistent (typically <10 seconds). Use multi-cluster routing for automatic failover. Replication is critical for disaster recovery.
Q5: How do you optimize Bigtable for cost?
Answer: 1) Use SSD for hot data, HDD for cold data, 2) Configure aggressive GC policies, 3) Use replication only for availability, not performance, 4) Right-size nodes based on throughput, 5) Use batch operations for bulk writes, 6) Monitor and optimize row key design to prevent hotspots.
Common Mistakes
Prefixing row keys with a timestamp
Fix: Reversing or hashing the time spreads writes across tablets; a leading timestamp concentrates every new write on one node.
Creating a column family per attribute
Fix: Group families by access pattern, keep them few, and let qualifiers carry the attributes so storage and cache behaviour stay predictable.
Leaving retention to an occasional manual cleanup
Fix: Set a garbage collection policy per family at creation so old versions are compacted continuously and cost stays bounded.
Best Practices
- Design the row key against the query, since Bigtable has no secondary index
- Batch cells for the same row into one mutation instead of one call per column
- Size nodes against sustained throughput and re-check after any key redesign
- Give each family a policy that matches what a reader should be allowed to see
Key Takeaways
- Tablets are split by row key, so the key decides load balance as much as it decides storage
- Wide and sparse: column families fix storage layout, qualifiers carry the sparse attributes
- Garbage collection is per family and is the only automatic retention mechanism available
- Point lookups and narrow range scans are cheap; scatter reads across entities are not
Interview Questions
Q1: What is the difference between Bigtable and Firestore?
Bigtable is a wide-column store tuned for very high throughput scans and appends with row-key access only, which suits time series and telemetry. Firestore is a document database with indexed queries, listeners, and per-document limits, which suits profiles and application state.
Q2: How do you design a row key for time-series data?
Encode the entity first and a reversed or hashed time component second, so one device's history is a contiguous range while writes spread across the key space. Prefix a short hash bucket when a single entity could still dominate a tablet.
Q3: What is a column family for?
It defines the physical storage layout, the cache granularity, and the garbage collection policy for a group of qualifiers. Families should be few and chosen by access pattern, because each family stores its own blocks and carries its own retention rule.
Q4: How does replication behave across clusters?
Data is replicated to every cluster in the instance and replication is eventually consistent, typically converging within seconds. Multi-cluster routing can send reads to the nearest healthy cluster, which gives availability without a client-side failover step.