Structuring the Answer
I’m thinking about crafting the answer in Markdown format. I want to include sections for shared principles, specifics on DynamoDB, specifics on Bigtable, examples, how to mitigate hot partitions, and TTL (time to live). It seems important to maintain a moderate length throughout the response, ensuring it’s informative but not overwhelming. I’ll make sure each section flows well into the next to provide a coherent explanation for the user.
Shared principles (DynamoDB + Bigtable)
- Design from access patterns, not entities. Start with the queries you must support (point lookups, range-by-time, “latest N”, fan-out by user/tenant, etc.). Shape keys so those become single-partition operations.
- Avoid “monotonic” keys (timestamps, auto-increment IDs) as the leading part of the key. They concentrate traffic on a small key range → hot partition/hot tablet.
- Prefer bounded scans: range scans within a single partition/rowkey prefix are fine; full-table scans are typically a smell (expensive/slow).
DynamoDB: keys, indexes, hot partitions, TTL
1) Primary key design (Partition key + optional Sort key)
Partition key (PK) decides which partition holds the data. It must have high cardinality and even access distribution.
Sort key (SK) lets you:
- query multiple items under one PK
- do range queries (
begins_with, BETWEEN)
- model time ordering, type grouping, etc.
Common patterns
- Multi-tenant:
PK = TENANT#<tenantId> and then add entity type to SK.
- User timeline:
PK = USER#<userId>
SK = TS#<reverseTimestamp>#<eventId> (reverse timestamp gives “latest first”)
- Entity + edges (single-table style):
PK = ACCOUNT#123
SK = PROFILE and SK = ORDER#2025-12-13#<orderId>
Rule of thumb: If a query needs “all items for X ordered by Y”, put X in PK and Y in SK.
2) Secondary indexes
DynamoDB has:
- GSI (Global Secondary Index): new partition key + sort key, can project subsets of attributes.
- LSI (Local Secondary Index): same PK as base table, different SK (must be defined at table creation).
Use GSIs when
- you need a different “lookup dimension” (e.g., find by email, status, externalId).
- you can tolerate eventual consistency on the index (GSIs are eventually consistent).
Index design tips
- Keep projected attributes minimal (lower cost).
- Treat each GSI like its own table: it has its own hot-partition risks.
- For “inverted index”-style lookups (e.g., tag → items):
- GSI PK could be
TAG#<tag> and SK could be <timestamp>#<itemId>.
3) Hot partitions (and how to avoid them)
Hot partitions happen when too many reads/writes hit the same PK values or a small set of partitions.
Common causes
- PK is low-cardinality (e.g.,
status=OPEN)
- time-based PK (e.g.,
PK = 2025-12-13)
- “global counters” or aggregates stored under one key
- GSI keys that collapse many items under one value (again:
status=OPEN)
Mitigations
- Write sharding: add a small random/bucket suffix to PK.
- Example:
PK = USER#123#SHARD#07, choose shard = hash(userId) % N or random 0..N-1
- Reads: query N shards in parallel (or maintain a routing item).
- Time bucketing: distribute by time window.
PK = USER#123#DAY#2025-12-13, SK = timestamp
- Atomic counters: shard counters and sum on read, or use DynamoDB’s patterns for distributed counters.
- For “status” queries: use a GSI PK like
STATUS#OPEN#BUCKET#<0..N-1> where bucket is derived from item id hash.
4) TTL (Time To Live)
- TTL is enabled by selecting an attribute (epoch seconds).
- Expiration is eventual (items can remain visible for a while after TTL).
- Deletes caused by TTL still consume some internal resources; do not assume TTL is a free bulk-delete mechanism.
- TTL does not guarantee immediate removal for compliance; if you need hard deadlines, explicitly delete.
Pattern
- Store
expiresAt on items that are cache-like, session-like, dedupe windows, etc.
- Combine TTL with time-bucketed PKs to keep partitions from accumulating unbounded history.
Bigtable: row keys, “indexes”, hot spotting, TTL/GC
1) Row key design (the critical choice)
Bigtable is ordered lexicographically by row key. Tablets split by contiguous key ranges.
Goal: evenly distribute writes across the keyspace while keeping useful locality for reads.
Good row-key patterns
- Prefix by high-cardinality id (tenant/user/device) and then time:
rowkey = <tenantId>#<userId>#<reverseTimestamp>#<eventId>
- Reverse timestamp for “latest first” scans:
revTs = maxTs - ts to make newest sort earlier.
- Salting/prefix hashing to avoid hotspotting:
rowkey = <hashPrefix(tenantId,userId)>#<tenantId>#<userId>#<ts>...
Avoid
- Leading with raw timestamp:
2025-12-13T... → all writes go to the “end” tablet.
- Sequential IDs as the leading component.
2) Secondary indexes in Bigtable (roll your own)
Bigtable doesn’t have native secondary indexes like DynamoDB GSIs. Common approaches:
- Index table: create a separate table keyed by the alternate dimension.
- Base table rowkey:
USER#123#revTs#eventId
- Index table rowkey:
EMAIL#alice@example.com#USER#123 → points to base rowkey(s)
- Materialized views: duplicate rows in a second table optimized for another access pattern.
- Per-field inverted index (for limited equality lookups):
FIELD#value#primaryKey.
Trade-off: you must keep index tables consistent (usually “best effort” or via streaming pipelines).
3) Hot tablets / hotspotting
Bigtable hotspotting is usually from append-only key patterns (monotonic rowkeys). Symptoms: one tablet gets most writes, high latency.
Mitigations
- Salting/hash prefix (most common): 16–256 buckets often used depending on throughput.
- Shard by time bucket:
<bucket>#<yyyyMMddHH>#<id>... if your reads align with time windows.
- Use reverse timestamps if you mainly read “latest N” and write sequentially.
4) TTL in Bigtable (Garbage Collection policies)
Bigtable TTL is handled via GC rules at the column family level, e.g.:
- Max age (delete cells older than X)
- Max versions (keep last N versions)
- Or both
Notes:
- GC is not always instantaneous; it’s enforced over time.
- TTL is per cell/column family, not “delete the whole row at timestamp” unless your schema aligns to make that true.
Pattern
- Put time-series cells in a family with
max_age = 30d.
- Keep “profile/current state” in a separate family with no TTL or longer TTL.
Quick comparison table
| Topic | DynamoDB | Bigtable |
|---|
| Primary key | PK (+ optional SK) determines partition | Row key determines sort order + tablet ranges |
| Range queries | Only within same PK via SK | Efficient over contiguous row key ranges |
| Secondary indexes | Native GSIs/LSIs | Build your own (index tables/materialized views) |
| Hot partitions | Hot PKs and hot GSI keys | Hot tablets from monotonic row keys |
| TTL | Per-item attribute, eventual expiration | GC policies per column family (age/versions) |
Practical heuristics (both systems)
- Put the highest-cardinality, most-evenly accessed dimension first in the key.
- Put time later in the key, and consider reverse time for “latest first”.
- If any single key value can exceed your per-partition/tablet throughput, add controlled sharding (hash/bucket).
- If you add an index (GSI or index table), re-check hot keys—indexes often reintroduce hotspotting even if the base table is fine.
- TTL/GC is great for bounded retention, but don’t rely on it for exact-time deletion semantics.
If you share 2–3 concrete access patterns (e.g., “get latest 50 events per user”, “query by status”, “dedupe by idempotency key for 24h”), I can propose specific key/index schemas for DynamoDB and Bigtable and call out where hotspots will appear.