Part 4 of the eight-part How Backend Systems Scale series. Keep the separate powers-of-ten estimation reference nearby for the calculations.
The first version of a photo app keeps metadata in a dictionary. Given a photo ID, it returns a caption and an owner. The lookup is fast, and the code is small.
Then the process restarts. The dictionary is empty.
We need to keep the records somewhere durable. Moving them to disk solves that particular problem, but now we have more questions: how do we find a record, update it, list a user’s photos, or change two related records together?
Let’s follow those questions. They lead to storage models and indexes for different reasons.
On this page
- Choose storage from access patterns
- Build a tiny persistent key-value model
- A document is a structured value
- Give relational terms a concrete meaning
- Why an ordered tree helps
- Protect a purchase with transactions
- Big data does not force one database family
Choose storage from access patterns
Write the questions first
“Store photos” combines several jobs. The application actually needs to:
- Fetch a photo’s metadata by ID.
- List one user’s newest uploads.
- Find a session by token.
- Store and retrieve image bytes.
- Change a caption without losing its owner.
These are access patterns: the reads and changes the application performs. They give us a more useful starting point than a database product name.
Match the data to its job
| Storage model | Natural example | Important trade-off |
|---|---|---|
| Relational tables | Users, ownership, captions | Relationships, constraints, and flexible queries; indexes and query plans still matter |
| Key-value | Session token to session data | Simple key lookups; other queries may need additional structures |
| Object storage | Image bytes addressed by an object key | Large durable objects; usually not a replacement for relational queries |
A reasonable initial design uses object storage for image bytes and one relational database for metadata and sessions. Different shapes don’t automatically require different database products.
Uploading an object and saving a database row are separate operations. A partial failure can leave an unfinished upload or an orphaned file. An explicit upload status and cleanup work can handle that boundary without pretending the two systems share one transaction.
Estimate the two sizes separately
At 10^6 uploads per day:
- Metadata at
10^3bytes each adds10^9bytes, about 1 GB per day. - Originals at
2 × 10^6bytes each add2 × 10^12bytes, about 2 TB per day.
These rounded assumptions exclude indexes, derived images, and extra copies. The image bytes dominate storage size even if metadata queries dominate application complexity.
Build a tiny persistent key-value model
Return to our dictionary. We could write each key and value to an append-only file, then keep a smaller dictionary in RAM telling us where the latest record lives.
A file offset is a position in the file. Here’s a teaching layout:
| File offset | Appended record |
|---|---|
| 0 | photo:42 → caption version 1 |
| 100 | photo:73 → another caption |
| 200 | photo:42 → caption version 2 |
The latest caption for photo 42 is at offset 200, so the RAM index becomes:
photo:42 → offset 200
photo:73 → offset 100
The offsets are invented. Real records need encoding, lengths, and validation. The useful idea is that the index points to the latest stored record rather than holding every value in memory.
Under typical hash-table assumptions, finding the offset takes expected O(1) work. Reading the value still involves the storage path; a constant-time in-memory lookup doesn’t establish a fixed request duration.
Follow each CRUD operation
- Create appends a record and adds its index entry.
- Read looks up the current offset and reads there.
- Update appends a newer version and changes the offset.
- Delete appends a deletion marker and removes or marks the index entry.
That deletion marker is often called a tombstone. It records that an older value must stay deleted during recovery or merging.
Restart and compaction
The file survives a restart. The RAM index doesn’t, so we need a recovery procedure. Scanning the records and keeping the latest applicable entry for each key can rebuild it. Real designs may use checkpoints or hint files to reduce startup work.
Updates keep appending, which leaves obsolete versions behind. Compaction reclaims that space:
- Read old segments.
- Retain live records and deletion information still needed for safety.
- Write replacement segments.
- Switch to the new files and index safely.
- Retire old segments after active readers no longer need them.
Dropping a tombstone too early can let an older segment bring the deleted value back.
This model favors sequential writes, but it has limits:
- The key-to-offset index still consumes RAM.
- Compaction competes for disk and CPU.
- Ordered range queries need a different access strategy from point lookups.
- Completing a file write doesn’t automatically make it durable against power loss; flush and acknowledgment rules matter.
The Bitcask paper describes this family of design. It isn’t the physical format of every database, but it gives us a concrete way to reason about persistence.
A document is a structured value
So far, a value could be uninterpreted bytes. Suppose a profile’s value has fields we want to query:
{
"user_id": 42,
"name": "Maya",
"preferences": {"language": "en"},
"photo_ids": [73, 74]
}
A document store can understand and index fields within a structured value, often in a JSON-like format. That changes which queries it can support directly:
| Model | Useful operation | Design question |
|---|---|---|
| Key-value | Get the value for session:abc | Which other lookups would need another structure? |
| Document | Query indexed fields in a profile | Which fields and nested arrays grow or change together? |
| Relational | Join users, photos, and purchases | Which relationships and constraints must be enforced? |
There is still structure to manage. Applications depend on expected types, validation, and compatibility between old and new records.
Distributing a key-value store adds another set of responsibilities: partitioning or replicating keys, routing requests, and handling partial failure. An in-process hash table doesn’t do those things merely because it also stores keys and values. The later chapters will build those mechanisms separately.
Give relational terms a concrete meaning
Our photo records refer to owners. A store’s order items refer to products. These relationships can be represented explicitly in tables with declared rules.
- A table, or relation, is a collection of records with named columns.
- A row, or record, is one item.
- A column, or attribute, is one field.
- A schema states structure and rules.
- A primary key is the chosen non-null unique row identifier.
- A foreign key constrains a reference to an existing row.
A PostgreSQL example makes the relationship visible:
CREATE TABLE users (
id BIGINT PRIMARY KEY,
display_name TEXT NOT NULL
);
CREATE TABLE photos (
id BIGINT PRIMARY KEY,
owner_id BIGINT NOT NULL REFERENCES users(id),
caption TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
INSERT INTO users (id, display_name) VALUES (42, 'Maya');
INSERT INTO photos (id, owner_id, caption) VALUES (73, 42, 'At the park');
SELECT id, caption FROM photos WHERE owner_id = 42;
UPDATE photos SET caption = 'A rainy day at the park' WHERE id = 73;
DELETE FROM photos WHERE id = 73;
The examples create tables and perform SQL CRUD. Whether removing a user is allowed while photos reference that user depends on the foreign-key rule. Referenced records don’t automatically disappear.
Normalize repeated facts
Suppose every photo also stores its owner’s current display name. A name change now needs many updates. If only some succeed, different photos show different “current” names.
We can change the model:
- Store the user’s current name once in
users. - Store the
owner_idon each photo. - Read through that relationship when current information is needed.
This is the motivation for normalization: repeated facts can drift apart. The normalization guide explains the formal normal forms.
Sometimes a historical snapshot is a different fact. An order’s price at purchase should survive later catalog changes. Store that historical value deliberately rather than recalculate yesterday’s receipt from today’s price.
Why an ordered tree helps
Finding photo 73 is one query. Listing a user’s latest twenty photos is another:
SELECT id, caption, created_at
FROM photos
WHERE user_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 20;
An index beginning with user_id, followed by the ordering columns, can support it:
CREATE INDEX photos_user_recent
ON photos (user_id, created_at DESC, id DESC);
The final id breaks ties between equal timestamps. Whether the index is worthwhile depends on the data, workload, and query plan.
Walk a small tree before looking at database pages
Imagine a binary-search tree rooted at 10. Its left child is 6, with children 4 and 8. Its right child is 18, with children 15 and 21.
To find 15:
- At 10, go right because 15 is larger.
- At 18, go left because 15 is smaller.
- Reach 15 and follow its record reference.
An ordered traversal can also find the range from 8 through 18: 8, 10, 15, 18. Hash buckets don’t directly provide that navigation.
| Structure | Basic idea | Good fit | Limitation |
|---|---|---|---|
| Hash index | Hash a key to locate candidates | Equality lookup | Does not preserve useful key order |
| B-tree family | Keep keys in an ordered, balanced structure | Equality, ranges, ordering | Extra storage and maintenance on writes |
A balanced search tree’s height grows logarithmically with the key count. Range-query work also includes visiting the matching entries. Database B-tree-family indexes use wider nodes designed around storage pages, reducing page visits compared with a narrow tree. The B-tree walkthrough explains the mechanics of searches, splits, and linked leaves.
An index usually stores enough information to locate the record; it isn’t automatically a full duplicate of every column. Formats differ between databases.
PostgreSQL’s index documentation distinguishes hash equality lookups from B-tree equality, ranges, and ordering. Algorithmic complexity doesn’t establish wall-clock query duration: page caching, row lookups, result size, and concurrency still matter. The storage guide follows those physical details further.
Protect a purchase with transactions
The photo app led us to relationships and queries. Checkout adds another requirement: changing related records must preserve a business rule while requests overlap.
Imagine one ticket remains. Alice and Bob both try to buy it.
The unsafe sequence
| Step | Alice | Bob |
|---|---|---|
| 1 | Reads quantity: 1 | |
| 2 | Reads quantity: 1 | |
| 3 | Creates order | |
| 4 | Creates order | |
| 5 | Sets quantity to 0 | Sets quantity to 0 |
The quantity ends at zero, which looks plausible. Two successful orders reveal the mistake. The read and change were separate steps, and their timing allowed both purchases through.
This is a race condition: correctness depends on how concurrent operations interleave.
Let the database check and change together
For one PostgreSQL inventory row:
UPDATE inventory
SET quantity = quantity - 1
WHERE product_id = 42 AND quantity > 0
RETURNING quantity;
The condition and decrement are part of one update:
- One returned row means this update reserved a unit.
- No returned row means it didn’t. Distinguish a missing product separately if needed.
- Concurrent updates to that row coordinate through database locks.
- At Read Committed isolation, PostgreSQL rechecks the condition after waiting for a concurrent updater.
The isolation documentation specifies that behavior. Stronger isolation can instead require retrying a transaction after a concurrency error.
Save the order in the same transaction
Reservation alone isn’t the complete purchase. The order insert could fail afterward. We need both changes to commit together:
- Begin a transaction.
- Run the conditional update.
- Roll back and report unavailable if no unit was reserved.
- Insert the order after successful reservation.
- Commit when both changes succeed.
Application code performs the branching. Don’t insert an order unconditionally after an update that affected zero rows.
ACID in checkout language
These needs explain the transaction properties:
| Property | What it means here |
|---|---|
| Atomicity | Inventory change and order creation commit together or neither does |
| Consistency | Declared rules, such as nonnegative quantity, remain satisfied |
| Isolation | Concurrent transactions interact according to the selected isolation level |
| Durability | A committed result survives failures covered by the configured storage guarantees |
The consistency in ACID concerns database rules. Whether replicas show the same recent value is another question.
A constraint provides an additional guard:
ALTER TABLE inventory
ADD CONSTRAINT inventory_nonnegative CHECK (quantity >= 0);
It rejects negative quantity. It can’t detect every business bug, including two order inserts without corresponding decrements.
A small store might keep products, inventory, orders, and order items in related tables. Foreign keys express references. Order items retain quantities and prices at purchase, including historical facts that must outlive changes to the catalog.
Payment crosses a boundary
An external payment provider doesn’t automatically participate in our local database transaction.
For this introductory model, reserve stock and create a pending order transactionally. Then manage payment as a separate workflow:
- Give the order an explicit payment status.
- Use repeat-safe payment requests where supported.
- Record enough state to reconcile uncertain outcomes.
- Expire or compensate failed reservations according to the product’s rules.
- Avoid holding database locks while waiting indefinitely for an external call.
If the local order insert fails before commit, roll back the reservation. If reservation already committed independently, recovery needs explicit work. That difference is the reason for choosing the transaction boundary.
The ACID and isolation and concurrency articles cover those mechanisms in more detail.
Big data does not force one database family
A growing app can outgrow a storage budget, an ingestion rate, a processing window, or a convenient data model. Those are different problems:
- Volume: many retained bytes.
- Velocity: fast arrival or processing requirements.
- Variety: different or changing data shapes.
Online processing answers incoming requests. Batch processing handles collected work. A store can keep purchases in relational tables while exporting historical events for separate analysis.
NoSQL groups several models rather than specifying one set of guarantees. Distributed SQL combines relational capabilities with distribution; it is sometimes discussed under the older NewSQL label. Some non-relational systems also support transactions.
If the next feature asks for all beach-tagged photos from last month, a simple photo_id → record lookup won’t answer efficiently by that key alone. We need an index, a maintained view, another query path, or a scan with a cost we’re willing to accept.
That is the habit to keep: start with the operation and its required guarantee. The label on a database doesn’t decide them for us.
Previous: Unique IDs: Counters, Base62, Hashes, and Key Pools. Next: Route and Deliver Requests: Load Balancers, DNS, and CDNs.