Skip to content

Choosing a Data Model: Postgres, Key-Value, and Document Stores

11 min reading

Choose representations and atomic changes from the state that must remain true.

Page details

Data and asynchronous work · Lesson 03

Published · Sources · 11 min reading · Last edited:

Know first: Numbers Every Engineer Should Know; Reading Architecture Diagrams.

Editorial correction:

Earlier design notes used unsupported universal performance or reliability claims. This revision explains conditional mechanisms and explicitly hypothetical examples; no author-run benchmark or production incident is asserted.

More
20px

Northwind: Data models: identities, invariants, and transaction boundaries

Outcome. After this lesson, you can model the order before choosing its storage format.

Hypothetical scenario. At Northwind, Dev must keep orders, catalogue entries and policy revisions consistent with their access patterns.

In short. Choose storage from queries and transaction boundaries. Give orders an authoritative transactional representation.

Choose the state that must stay true

Hypothetical scenario. The catalogue now accepts reservations. A reader can browse a seller's item, reserve a quantity and later cancel. The service must avoid promising more units than remain available, and the reservation must identify which seller and item it concerns.

Choosing storage begins with those obligations and the operations that enforce them. It does not begin with a contest between a relational database and a document database. The useful questions are which facts belong together, which changes must be accepted together, and how each reader finds the state it needs.

The previous lessons supplied workload and network boundaries. This lesson turns those assumptions into a data model and a transaction boundary. The next lesson studies access paths: a correct model can still be expensive to search, while a fast index cannot repair an undefined invariant.

The format does not provide the contract

A table, document, key-value entry or graph edge describes a representation. It does not, by its name alone, establish transaction scope, query cost, durability, consistency or failure behavior. Those are properties of an implementation, configuration and operation.

Likewise, “schema flexible” does not mean “without a schema.” If an application expects an item identifier, a price and a seller reference, that expectation is a contract even when a database permits other shapes. Decide how missing fields, incompatible versions and invalid values are rejected or migrated.

Start with an explicit rule such as “a completed reservation cannot make available stock negative,” then locate the operation that enforces it. Checking a value in one application request and writing a new value later can introduce a race. An application-level check is not automatically an atomic database condition.

Separate identity, relationships and read views

Give durable entities stable identities: a seller, an item and a reservation. Their relationships describe ownership and the operation being requested. A rendered item page is a view assembled from those facts; it need not be the only stored representation.

Authoritative entities and a derived catalogue viewSeller identity is referenced by an item. A reservation refers to an item and quantity. A derived item view combines selected information for reading, but has a separate freshness and update contract.Sellerstable identityItemseller referenceReservationitem + quantityDerived viewfreshness policy

Normalized relationships keep shared facts in an authoritative location. Embedding or denormalizing can make a common read convenient, but a shared fact may then have multiple copies. That trade changes update and recovery work; it is not a moral preference for one representation.

PostgreSQL's constraint documentation illustrates concrete mechanisms for required values, uniqueness and relationships. Their exact semantics matter: a check that can accept a null expression is not equivalent to requiring a non-null value. Verify the mechanism used for each invariant rather than assuming a label covers it.

Model the order before choosing its storage format

Northwind's catalogue and checkout ask different questions of their data. A product description can tolerate a declared delay in a derived search view. A stock reservation must preserve a rule about how much inventory remains available. Postgres tables, document records and key-value entries are representations; the important decision is which component can enforce each rule while requests overlap.

Consider a hypothetical stock row with twelve units available. Two buyers each request seven units. Independent reads allow both buyers to observe twelve, even though 7 + 7 = 14 exceeds stock by two. The accepted transition must combine the availability condition and the decrement under an appropriate concurrency contract. Merely putting the same values in one JSON document does not establish that contract. Nor does distributing the order across several services improve the invariant by itself.

A relational model makes references and uniqueness rules visible, while a document model can keep frequently retrieved fields together. Both still need a declared authority for corrections. If the seller address appears in fifty derived product views, one address edit creates fifty projection updates in this toy example. Those updates are a propagation workload, not fifty independent authoritative addresses. Attach a source version and decide what the reader sees while updates are incomplete.

The access pattern then guides physical choices. List the writes that must commit together, the reads that can use an older view, and the operations that cross stores. A confirmed transaction abort permits a different recovery path from a lost response after an uncertain commit. Choosing a database family before writing those distinctions down hides the hardest part of the design behind a product label.

Derive duplication and a reservation race

Hypothetical scenario. Choose one million items and ten thousand sellers. Each seller profile has exactly 512 bytes of selected text. Embedding a full profile in every item stores 1,000,000 × 512 = 512,000,000 bytes = 512 decimal MB of that text.

Storing one profile per seller instead uses 10,000 × 512 = 5,120,000 bytes. A chosen eight-byte seller reference in each item adds 1,000,000 × 8 = 8,000,000 bytes. Together these payloads occupy 13,120,000 bytes = 13.12 MB. The difference is 512 − 13.12 = 498.88 MB of modeled payload, excluding row/document metadata, indexes, compression, replicas and other fields.

This does not prove the normalized read is cheaper. It may need another lookup or a join. The model makes the duplication cost visible so that it can be weighed against actual read patterns, update frequency and resource behavior. Do not translate this payload comparison directly into a database bill.

Now choose an item with seven available units. Two requests each attempt to reserve five. If both first read seven and independently compute 7 − 5 = 2, both may write two and report success under an unsafe read-then-write design. Ten units were promised from seven: an excess of 10 − 7 = 3, even though the stored counter never became negative.

A suitable atomic operation must test sufficient remaining stock while applying the decrement, and the reservation record must share the appropriate acceptance boundary. In the chosen scenario, one five-unit reservation can succeed, leaving two; the other must fail or choose a different declared outcome. The exact transaction, conditional-write or concurrency-control mechanism depends on the datastore contract.

In the wild: Model the order before choosing its storage format

The primary reference establishes this concrete distinction: constraints have specific null/uniqueness/relationship semantics.

Transaction scope is a design decision

Transactions group state changes, but isolation behavior is not identical across systems or isolation levels. PostgreSQL's transaction-isolation documentation explains its snapshots and concurrency behavior. Use that concrete contract when evaluating a PostgreSQL design; do not generalize a product's default to every transactional store.

For the reservation, decide whether inventory decrement and reservation creation must succeed together. If a single database can enforce the needed boundary, separating the operation across services may add coordination work without solving a current problem. A business requirement, ownership boundary or scale constraint should justify that extra boundary.

Serialization conflicts, deadlocks or conditional-write rejection can be expected outcomes of contention rather than evidence of corrupt data. The application still needs a bounded response and retry policy. Repeating a completed reservation after a lost response is a different problem from retrying an aborted transaction; later lessons address identity and idempotency.

The profile change that never finished

Hypothetical scenario. A seller changes a support address. The application updates the seller record and begins rewriting every embedded copy. A worker stops partway through. Some item pages display the new address, others the old one, and the service has no record of which revision each copy represents.

The missing design is a propagation and reconciliation contract. Preserve source versions and define what readers can observe during incomplete updates. PostgreSQL constraints define enforceable local rules; a derived copy also needs a named authority and an update policy.

Denormalization may still be appropriate. The lesson is that the duplicated view carries obligations. A successful update to the authoritative record does not establish completion of every derived update, and a cached value does not become authoritative merely because it is convenient to read.

Database labels that hide the decision

“SQL means every operation is strongly consistent.” Describe the actual operation, isolation, replica choice and transaction boundary.

“Documents eliminate migrations.” Applications still depend on meanings and shapes. Old and new versions need compatible handling or a migration.

“A non-negative final counter proves there was no overselling.” The worked race demonstrates that successful outcomes and stored values can disagree under an unsafe update.

“Denormalized data is wrong by definition.” It can serve important access patterns. Its update, freshness and recovery rules need to be explicit.

Choose the simplest boundary that enforces the rule

Use shared authoritative records when relationships and invariants justify them. Consider embedded aggregates when information has compatible ownership and lifecycle and is commonly accessed together. Consider derived views when read needs differ from authoritative organization and their maintenance cost is acceptable.

Do not choose a data model from an audience-size threshold or a universal “joins are slow” claim. Model representative operations, inspect access paths and measure their costs. A flexible representation and useful constraints can coexist; the trade is more specific than relational versus non-relational.

Before moving to indexes, write down the identities, relationships, required atomic changes and acceptable freshness of each view. These become requirements for physical access paths, not assumptions for an index to invent later.

Limits of this model

This model does not prescribe one database family for every workload. Product-specific isolation, conditional writes, schema evolution and recovery behavior must be checked for the chosen system. Derived views need explicit propagation guarantees, and a storage format does not establish permission or business validity.

Check yourself: name the invariant

Both clients report success and the counter is two. Does the stored counter establish that seven initial units covered the two five-unit reservations?

No. The two successes promise ten units. The unsafe overwrite hides the three-unit shortfall. Inspect the atomic condition and all accepted reservation records, not only the final counter.

A seller's address is copied into item views. Must every read become a join?

No. The representation can remain duplicated if its freshness and propagation contract is acceptable. Identify authority, versions and reconciliation rather than declaring one representation universally correct.

A transaction aborts before acceptance. Is that equivalent to a request timing out after an unknown commit?

No. A confirmed abort and an uncertain result provide different evidence. Apply the transaction's retry contract in the first case; reconcile identity and outcome before risking duplication in the second.

Northwind decision log

Choose storage from queries and transaction boundaries.
Give orders an authoritative transactional representation.
Choose derived views independently from the source record.

Go deeper: Model the order before choosing its storage format

Related blog: Retrieval failures caused by stale source state.