Partition keys and caching
Partition keys determine where load goes
A partition key is a value used to locate or distribute data. A logical partition groups records under a key; a physical partition is infrastructure that stores some portion of the data. A hot partition receives disproportionately high traffic or consumes disproportionate capacity. Even with many keys, a single popular value can dominate writes or reads.
Consider a teaching model with four partitions, each serving 100 writes per second. The measured loads are 160, 40, 40, and 40 writes/s. Total load is 280 writes/s, below the aggregate 400, but the first partition exceeds its local capacity by 60 writes/s. This model predicts a local bottleneck, not actual provider throttling. Real systems may have adaptive capacity, splits or different quotas.
Choose and test keys before deployment
A key that is only a date concentrates the current day's writes. A tenant key may work for many similarly sized tenants but a large tenant can dominate. A composite key can include a stable shard suffix when the write pattern requires it. For example, distribute 160 events/s across four suffixes, approximately 40 per suffix if the distribution is balanced. Reading all events now needs multiple queries and a merge; physical placement may still collide. Preserve the access pattern and test with realistic skew.
Monitor per-key or per-partition request distribution where available, throttling, latency, retries and consumed capacity. Investigate whether one key, an index or a downstream service is saturated. Adding aggregate capacity alone may not fix a hot key. Do not expose sensitive IDs in telemetry.
Capacity and request cost
DynamoDB provisioned capacity illustrates how units can differ from raw requests. For ordinary nontransactional operations on a base table, a strongly consistent read of an item up to 4 KB consumes one read capacity unit for one read per second; eventually consistent reads consume half that amount. A write up to 1 KB consumes one write capacity unit per write per second. Larger items round up in the respective increments. Example: 20 strongly consistent reads/s of 6 KB items need 40 RCU; 10 writes/s of 1.5 KB items need 20 WCU. Indexes, queries, transactions, replication and other operations may add different consumption. These are simplified sizing calculations, not quotes or a universal service limit.
Cosmos DB request units (RU) measure normalized operation resource consumption; RU/s describes throughput. If observed point reads cost 1 RU each and writes 6 RU each in a fictional trace, 100 reads/s and 20 writes/s consume 220 RU/s. A measured RU charge is not a fixed price per request, and the same workload may consume different RUs with different consistency, item size and indexing. Firestore bills according to its own operation and storage dimensions; Bigtable and Spanner have separate capacity models. Never convert RCU to RU as if they were the same currency.
Hypothetical monthly example: 2 million reads at $0.30 per million, 0.5 million writes at $1.20 per million and 10 GB-month at $0.20 per GB-month cost $3.20 before cache, backups, networking and other charges. These invented rates are only for arithmetic; verify region, mode, currency and actual billing dimensions for production.
Cache-aside: read, write, invalidate
A cache stores a copy of frequently used data so that repeated requests do not always reach the source. Cache-aside means the application manages the cache: on a miss, read the source and populate the cache; on a hit, reuse the cached value if it is still acceptable. After a successful source write, remove the corresponding cache entry so the next read can fetch the new version.
Read: application -> cache hit -> return cached valueRead: application -> cache miss -> database -> fill cache -> returnWrite: application -> database commit -> invalidate cache keySet a TTL according to freshness requirements. Eviction removes items because of resource pressure or policy, even before expiration. A miss is normal, not a data-loss event, if the source remains authoritative. Never treat a general-purpose cache as durable storage without a separately verified persistence and recovery design. Amazon ElastiCache, Azure Managed Redis, and Google Cloud Memorystore are managed cache candidates; engine, cluster mode, availability and persistence must be verified separately.
A cache is not an authorization layer. Include tenant and representation scope in cache keys, authorize before looking up or returning private data, and avoid shared caching of sensitive or personalized results without a reviewed isolation policy.
Run a deterministic cache trace
This Python 3 example runs locally without external libraries. It models one key, a five-second TTL, and sequential writes, not concurrent Redis or a cloud service.
source = {"book-17": 1800}cache = {}
def read(key, now): if key in cache and now < cache[key][1]: return cache[key][0], "hit" value = source[key] cache[key] = (value, now + 5) return value, "miss"
def update(key, value): source[key] = value cache.pop(key, None)
print(read("book-17", 0))print(read("book-17", 2))update("book-17", 1900)print(read("book-17", 3))print(read("book-17", 8))Expected output:
(1800, 'miss')(1800, 'hit')(1900, 'miss')(1900, 'miss')The first read fills the cache, the second is a hit, and the update invalidates the old price. The entry inserted at second 3 expires at second 8. This toy cache uses explicit time instead of a wall clock. It does not implement concurrent updates, network errors, eviction or distributed TTL behavior.
Failure, races and cache economics
Cache-aside does not guarantee database/cache consistency. A reader can fetch the old value before a writer commits, then fill the cache with that old value after invalidation. Invalidation may also fail after the database commits. Use a freshness policy, version-aware or coordinated updates where required, durable invalidation delivery and bounded retries; test the race instead of claiming TTL alone solves it. For stock reservations or permission decisions requiring current state, use the authoritative store and correct atomic operations.
A cache stampede occurs when many requests miss together (for example after expiration). Bound concurrency and use request coalescing for identical keys, expiration jitter, and controlled fallback. If the cache fails, falling back to the database can overload it; plan rate limits and overload behavior.
In a simplified 1,000-read/s trace with 80% cache hits, 200 requests/s reach the database (assuming one origin read per miss). At 2 ms hit latency and 22 ms miss latency including lookup and source, mean latency is 6 ms. That is not p95 or p99 latency. During complete cache failure, origin demand can rise to 1,000 reads/s, five times the normal miss load. Compare avoided source costs with cache, network, invalidation and operational costs.
Practice and next step
Use four partitions with 100 writes/s each and measured loads of 180, 30, 30, 30. Calculate aggregate utilization and local overload. For a separate workload, 500 reads/s at 90% hits and 3 ms/33 ms hit/miss latency: compute source load and mean latency; predict origin load on cache failure. Explain a stale-fill race and one mitigation. Check your reasoning using the staged manual task and offline fixture.
Next: PaaS and managed application hosting, where application scaling can increase pressure on data stores.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Partition keys and caching — knowledge check
Choose the best answer for each offline scenario.
Four partitions each handle 100 writes/s; the first receives 160. What is its modeled overload?
How many RCU are needed for 20 ordinary strongly consistent base-table reads/s of 6 KB items in the simplified DynamoDB example?
After a successful source update, what is the basic cache-aside action?
At 500 reads/s with 90% hits and one source read per miss, what is normal source read load?
A reader fetches old data, a writer commits and invalidates, then the reader fills the cache. What is the problem?