Sub topic 8
Choose storage that fits the access pattern
This chapter assumes you have read the earlier chapters on requirements, capacity estimation, building blocks, and the API and data model. You should be comfortable with HTTP APIs, basic SQL, and short Python snippets. The goal here is to pick a storage system by looking at how the data is read and written, not by looking at which database is popular.
Start from the access pattern
A storage choice is a prediction about how your system will touch data. Before you name a database, write down the operations the API from the previous chapter requires, and answer these questions for each one:
- Is it a read or a write?
- Does it look up one record by key, scan a range, or search by content?
- How many times per second does it run? Use the numbers from your capacity estimate.
- What consistency does it need? Must a reader see the latest write right away?
- How long must the data live, and how large will it grow?
Take the sketch API from the earlier chapter:
POST /v1/items
Content-Type: application/json
{"owner_id": "user:42", "body": "hello"}
GET /v1/items/{item_id}
GET /v1/users/{owner_id}/items?limit=20&cursor=abc123This gives three access patterns:
| Operation | Pattern | Rate (from the estimate) | Notes |
|---|---|---|---|
| Create item | Single-record insert | about 579 writes/s average, about 1,158 at peak | Must not lose data |
| Get item | Point lookup by `item_id` | Share of about 11,574 reads/s | Key is known exactly |
| List items by owner | Range scan by `owner_id`, newest first | Share of about 11,574 reads/s | Needs ordering and a cursor |
The estimate also gave about 25 GB of new data per day and about 9.1 TB per year. That is small enough for one large machine to hold for a while, but large enough that you should plan how to split it.
Compare the main storage families
Most designs choose from a short list of families. Each is good at some access patterns and weak at others.
| Family | Strong at | Weak at | Typical examples |
|---|---|---|---|
| Relational (SQL) | Joins, transactions, flexible queries, constraints | Horizontal write scaling across many machines | PostgreSQL, MySQL |
| Key-value store | Very fast point lookups and writes, easy partitioning | Queries on anything but the key | DynamoDB, Redis, etcd |
| Wide-column store | High write throughput, range scans within a partition key | Ad hoc queries, joins, transactions | Cassandra, HBase |
| Document store | Nested records read as one unit, flexible schema | Multi-document transactions, joins | MongoDB, Couchbase |
| Search index | Full-text search, filtering, ranking | Being the source of truth, strong consistency | Elasticsearch, OpenSearch |
| Object store | Large blobs, cheap, durable | Low-latency small reads, queries | Amazon S3, GCS |
The "weak at" column matters as much as the "strong at" column. A design fails when an access pattern lands on a store that is weak at it.
Relational databases
A relational database stores rows in tables and lets you query across tables with SQL. It supports ACID transactions: a group of changes either all happen or none do. Choose it when you need joins, constraints such as uniqueness, or multi-row updates that must be atomic, for example moving money between two accounts.
A single well-tuned relational server often handles several thousand writes per second. That covers the 1,158 peak writes per second in the example above. Do not reach for a distributed store when one primary with read replicas meets the numbers.
Key-value and wide-column stores
A key-value store maps a key to a value and nothing more. Lookups by key are fast, and partitioning is simple because the key decides where the data lives. The cost is that you cannot ask "find all values where field X equals Y" unless you built an index for it yourself.
A wide-column store adds a second level. A partition key chooses the machine, and a clustering key orders rows inside that partition. This fits the "list items by owner, newest first" pattern: use owner_id as the partition key and a time-ordered id as the clustering key. One partition read returns the whole page.
Document stores
A document store keeps a self-contained record, usually JSON, and reads it in one operation. It works well when the unit you read is the unit you write, such as a user profile with nested settings. It works poorly when the same data is shared by many documents, because you must update every copy.
Search indexes and object stores
A search index answers "which items contain this word, ranked by relevance". It is usually a secondary copy of data kept elsewhere, fed by a stream of changes. Do not make it your only copy, because most search systems favor query speed over strict durability and consistency.
An object store holds large files such as images or videos. Store the file in the object store and keep only its URL and metadata in your database. A 5 MB image in a relational row hurts cache use and backups.
Use a short decision procedure
You do not need to memorize products. Walk through the questions in order.
placeholderThe block above is replaced by the diagram below.
Two points about this flow. First, relational is the default when the numbers allow it, because it gives you the most query flexibility for the least design work. Second, the search index is an addition to a primary store, never a replacement.
Match the data model to the pattern
The same data can be laid out differently depending on how it is read. For the "list items by owner" pattern, a relational table needs an index that matches the query:
CREATE TABLE items (
item_id BIGINT PRIMARY KEY,
owner_id TEXT NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX items_owner_created_idx
ON items (owner_id, created_at DESC, item_id DESC);
SELECT item_id, body, created_at
FROM items
WHERE owner_id = 'user:42'
AND (created_at, item_id) < ('2026-11-01T00:00:00Z', 900001)
ORDER BY created_at DESC, item_id DESC
LIMIT 20;The composite index lets the database read the first 20 matching entries in order without sorting the whole table. The WHERE clause on (created_at, item_id) is keyset pagination: the cursor from the API carries the last row seen, and the next query continues from there. The alternative, OFFSET 10000, forces the database to walk and discard 10,000 rows, so it gets slower the deeper the user pages.
Without that index, the same query scans the whole table. At 9.1 TB per year, that is the difference between milliseconds and minutes.
Plan for partitioning early
If the estimate says one machine will not hold the data or the writes, the choice of partition key is a storage decision, not a later detail. The key should spread load evenly and keep the data for a common query together.
import hashlib
def shard_for(key: str, shard_count: int) -> int:
digest = hashlib.md5(key.encode("utf-8")).digest()
return int.from_bytes(digest[:8], "big") % shard_count
print(shard_for("user:42", 4))
print(shard_for("user:43", 4))Partitioning by owner_id keeps all of one user's items on one shard, so "list items by owner" reads one shard. Partitioning by item_id spreads writes evenly but forces that list query to ask every shard and merge results. Each choice favors one pattern at the cost of another, which is the trade-off the next chapters examine.
Common mistakes
- Choosing by familiarity or fashion. Naming a database before listing the access patterns. State the patterns first, then justify the store.
- Using one store for everything. Real systems often combine a primary store, a cache, an object store, and a search index. Each does what it is good at.
- Ignoring write cost of indexes. Every index speeds some reads and slows every write. Add indexes for the patterns you listed, not for ones you might want.
- Picking a hot partition key. A key such as
countryor a single celebrityowner_idsends a large share of traffic to one shard. - Forgetting the second copy. A search index or cache that is fed from the primary store can fall behind. Decide how stale it is allowed to be, and how you rebuild it.
- Overbuilding. A distributed store for 1,158 writes per second adds operational cost with no benefit. Use the capacity estimate to justify complexity.
Summary of the process
- List each operation from the API and classify it as a point lookup, range scan, search, or blob access.
- Attach a rate and a consistency need to each, using the capacity estimate.
- Start with a relational database if one primary can meet the numbers, and move to a key-value or wide-column store only when writes or size demand it.
- Add an object store for blobs, a cache for hot reads, and a search index for text queries as separate, rebuildable components.
- Choose indexes and the partition key to match the most frequent and most demanding queries.
Exercise
A messaging feature must show the latest 50 messages in a conversation, newest first, at 20,000 reads per second. Writes are 2,000 per second. Messages never change after they are sent. Which storage family would you choose for the messages, what would the partition key and ordering key be, and what is one risk of your choice?
Show answer
A wide-column store (or a relational database with sharding) fits well. Use conversationid as the partition key and a time-ordered message id as the clustering key, sorted descending, so one partition read returns the latest 50 messages. Messages are immutable, which suits append-heavy storage. A risk is a hot partition: a very active conversation, such as a large group chat, concentrates traffic on one partition. Mitigations include splitting a conversation's partition by time bucket (for example conversationid plus day) and caching the most recent messages.
Exercise
Your team stores product descriptions in a relational table and adds a search index for text queries. The search index goes down for an hour. What should happen to product writes, and why?
Show answer
Writes should continue against the relational database, which is the source of truth. The search index is a derived copy, so its outage should only make search results stale or unavailable. When the index returns, replay the missed changes from a change stream or rebuild the index from the primary store. Blocking writes on the index would let a secondary component take down the primary function.