API & Data Design
Data Modeling and Storage: Choosing Relational, Document, and Hybrid Designs
A PostgreSQL table and a document store can both represent an order. The consequential difference is not the label on the database; it is the cost of keeping customer data, line items, inventory, and fulfillment state correct as they change independently.
Start with the operations the system must perform and the invariants it must preserve. Then choose a representation that makes those operations safe, explainable, and affordable under the workload you actually expect.
Model the work before modeling the records
Database selection often begins with a category: “relational” for structured data, “NoSQL” for scale, or “document” for flexible schemas. Those labels hide the engineering questions that determine whether a design will hold up: Which queries must be fast? Which changes must succeed or fail together? How fresh must a read be? What happens when two requests update the same entity at once?
Write down the important reads and writes before choosing tables or documents. For an order service, the list might include:
- Load an order with its lines for a customer’s history page.
- Change an order’s fulfillment state without altering its purchased items.
- Reserve inventory without allowing concurrent requests to oversell stock.
- Show the product name and price as they were when the order was placed.
- Find all unshipped orders for a warehouse, ordered by creation time.
- Reconcile payment events that may be delivered more than once.
These are not equivalent access patterns. A customer history page favors loading a bounded aggregate efficiently. Inventory reservation requires coordination around a scarce quantity. A warehouse queue needs a selective, ordered lookup. One database can support all three, but each query has consequences for its schema, indexes, transaction boundaries, and contention profile.
Estimate volume as well as shape. Ten thousand orders and ten billion orders do not impose the same operational constraints. Neither does a workload that reads each order once and rarely changes it compared with one that repeatedly updates a small number of hot inventory rows. Useful design inputs include peak request rate, data retention, the largest expected record, read-to-write ratio, latency target, and the number of concurrent writers.
Relational design: explicit relationships and enforceable invariants
A relational schema is useful when important entities have clear relationships and correctness depends on rules spanning those relationships. In PostgreSQL, an order can have an orders row and a set of order_items rows. A foreign key ensures that each item references an order; a transaction can insert the order and its lines as one unit. Constraints can reject invalid values close to where they enter the system.
Normalization separates facts that have different lifecycles. A product’s current description belongs to a product record; a customer’s contact details belong to a customer record; an order item records what was purchased. This reduces accidental duplication and makes it easier to update a fact once. It also means a read that needs several facts may require joins, and an overly normalized write path can become difficult to reason about when it spans many tables.
Relational integrity is especially valuable for inventory. Suppose a stock row has available = 1 and two checkout requests arrive together. A read-then-write sequence—read one, then subtract one—can let both requests observe the same value and both claim success. Instead, update conditionally in the database:
UPDATE inventory
SET available = available - 1
WHERE sku = $1
AND available > 0
RETURNING available;
The application treats a returned row as a successful reservation and no returned row as unavailable stock. PostgreSQL executes the update with concurrency control, so competing transactions cannot both consume the same final unit. For multi-item orders, the reservation logic still needs a deliberate transaction strategy: lock rows in a consistent order, handle partial failure, and avoid holding locks while making network calls.
Transactions do not eliminate design choices. Under PostgreSQL’s default READ COMMITTED isolation, each statement sees a snapshot taken when that statement begins. Some multi-statement decisions need explicit locking, a conditional write, or a stronger isolation level. SERIALIZABLE can prevent anomalies by aborting transactions that cannot be serialized, but applications must be prepared to retry serialization failures. Stronger guarantees can therefore mean more retries and more work under contention.
Foreign keys and constraints provide durable protection even when several services or maintenance jobs write to the same database. Their cost is not zero: deletes and updates must respect the relationships, migrations must account for existing data, and some bulk-loading workflows need special care. The trade-off is often worthwhile when a broken relationship would create financial, inventory, or customer-support consequences.
Document stores: aggregate reads, bounded duplication
A document model stores related fields together, often as JSON-like structures. This can fit an aggregate that is normally fetched and updated as a unit: a configuration document, a shopping cart, or an order snapshot. A single read can retrieve the parent and its embedded lines without joining separate tables, and fields can evolve at different speeds across document versions.
That convenience has boundaries. Embedding is strongest when the child collection is naturally bounded, owned by the parent, and commonly read with it. A handful of order lines is a plausible embedded collection. An unbounded event history or all reviews for a popular product is not: the parent can grow without limit, become expensive to rewrite, and turn into a contention hotspot.
References are a better fit when records have independent lifecycles, are shared by many parents, or must be queried on their own. But references do not automatically provide the same cross-document integrity as a relational foreign key. The application may need to enforce existence, coordinate updates, tolerate partial failure, or run repair jobs. Whether the chosen document database supports multi-document transactions—and their practical performance and limits—must be checked for the specific product and deployment configuration.
Flexibility is also not a substitute for schema governance. If every application version writes a different shape, reads accumulate defensive branches and data cleanup becomes a permanent tax. Define a versioning policy, validate writes at the boundary, and measure how many historical shapes remain in storage. A document database can store evolving records without a conventional table migration, but the system still has a schema: it is simply enforced through a different combination of application code, validation, and operational discipline.
Document storage is not inherently faster. A document read may be efficient when it retrieves exactly the aggregate needed, but broad scans, large documents, unselective indexes, and frequent rewrites can be costly. Compare the actual query plan, document size, index footprint, and update frequency rather than assuming that fewer joins guarantee lower latency.
PostgreSQL JSONB: a useful middle ground, not a free pass
PostgreSQL’s JSONB type can keep a relational core while accommodating fields whose shape varies. It is useful for provider-specific metadata, optional product attributes, or a captured request payload that must be retained for audit. A row can combine typed columns—such as order_id, customer_id, and created_at—with a JSONB field for less stable details.
Keep fields that drive joins, constraints, sorting, authorization, or frequently filtered queries in ordinary columns. Putting everything in JSONB may defer schema decisions, but it can make essential rules harder to express and query behavior harder to inspect. For instance, a typed status column can have a check constraint and a conventional index. A status buried inside arbitrary JSON requires careful expression indexing and consistent path conventions.
PostgreSQL offers multiple index choices. A B-tree index suits equality and range comparisons on scalar columns, including timestamps used for ordered pagination. A GIN index can accelerate containment queries on JSONB, such as whether a document contains a particular key-value structure. GIN indexes can be larger and make writes more expensive; they are not a universal answer to JSON query performance. Measure index size, write amplification, and the selectivity of the exact operators used.
JSONB updates can also contend on the containing row. If a large document is frequently modified in small, independent parts, storing it as one field may create unnecessary write work and serialize competing updates. Splitting independently updated data into rows can improve concurrency and make constraints clearer. Conversely, splitting a small, stable aggregate into many tables can make a common read needlessly complex.
Use JSONB when flexibility solves a real integration or evolution problem. Do not use it merely to avoid deciding what the application’s data means. The best hybrid schema has clear boundaries: relational columns for durable invariants and access paths, JSONB for bounded variability that does not deserve its own relational model yet.
Normalization and denormalization follow lifecycle boundaries
Normalization is often described as avoiding duplication. In operational systems, a more useful question is whether duplicated values represent the same changing fact or separate historical facts. A product’s current title and the title displayed on a receipt may look identical at checkout, but they have different lifecycles. The current title can change; the receipt should usually describe what the customer bought at that time.
A practical order model can reference the current product while also storing a purchase-time snapshot:
order_items(
order_id,
product_id,
product_name_at_purchase,
unit_price_at_purchase,
quantity
)
The snapshot is intentional denormalization. It protects historical display and accounting from later catalog edits. It does not mean every product attribute should be copied onto every order line. Record the fields whose historical meaning matters, and define how currency, discounts, tax, and rounding are represented. Store money in a suitable exact representation—commonly integer minor units or a fixed-precision decimal—not binary floating point.
Denormalization shifts work rather than removing it. If an application copies a customer’s current address into many records, address changes may require fan-out updates or the copied values may become stale. If the copy is an immutable shipping address as entered for an order, staleness is not a defect; it is the intended record of the transaction. Naming fields to expose this distinction, such as shipping_address_at_purchase, helps future maintainers understand the contract.
Read models are another deliberate form of denormalization. A reporting table or materialized view can precompute a costly join or aggregation for a high-volume read path. PostgreSQL materialized views store query results and can be refreshed, but a refresh strategy introduces a freshness window and operational work. A continuously maintained projection may be fresher, but it must handle duplicate events, out-of-order delivery, and replay. Choose the consistency contract first: “accurate within five minutes” is a different requirement from “reflect every committed write immediately.”
Indexes are workload commitments
An index is not merely a speed setting. It consumes storage, adds work to writes, and encodes an assumption about which queries matter. Start from observed or specified queries, then create indexes that support their filters, joins, and ordering. A query that filters by status and sorts by creation time might benefit from a composite index on (status, created_at); a different ordering of columns can produce a different plan and may not serve the same workload.
PostgreSQL’s multicolumn B-tree indexes are generally most effective when conditions constrain the leading columns. If a query filters by customer_id and orders by created_at DESC, an index on (customer_id, created_at DESC) is a more direct candidate than unrelated single-column indexes. Confirm with EXPLAIN (ANALYZE, BUFFERS) against representative data. A plan from a tiny development database may mislead because table size, value distribution, and cache state affect the optimizer’s choices.
Indexes can be redundant, too broad, or poor matches for low-selectivity fields. A boolean index often does little if nearly every row has the same value. A partial index can be more useful for a stable, selective subset, such as pending jobs: WHERE state = 'pending'. But if the subset changes rapidly or the query predicate does not match the index condition, the benefit may disappear.
For text search, use a method suited to the query rather than a generic B-tree. PostgreSQL’s full-text search uses a tsvector representation and typically a GIN index for token-based matching; substring search may call for a trigram index. These solve different problems. Measure both the index’s build cost and its impact on inserts, updates, and vacuuming.
Pagination illustrates how query design and indexes interact. Large OFFSET values can require the database to walk past many rows before returning a page. Keyset pagination uses the last seen ordering values—often a timestamp plus a unique identifier—to request the next slice. It is efficient when the ordering is indexed, but it does not provide arbitrary page-number access and requires careful handling if sort keys change.
Consistency is a property of the workflow
“Strong consistency” and “eventual consistency” are not just database marketing categories. They describe what a user can observe across a particular workflow. A customer may need an order confirmation immediately after checkout, while an analytics dashboard can accept a short delay. Inventory availability, payment capture, and shipment status may each have different correctness and latency requirements.
When one database transaction can protect the needed invariant, keep the invariant inside that transaction. When work crosses systems—such as saving an order and sending a payment request—there is no ordinary local transaction that makes both systems commit atomically. A common approach is the transactional outbox: write the order change and an outbox event in the same database transaction, then publish the event asynchronously. Consumers should be idempotent because delivery can be repeated, and the outbox needs monitoring, retention, and retry policies.
This separation allows the order database to remain authoritative while downstream projections update later. It also creates a visible consistency window. If a customer checks a status immediately, the service should know whether to read the authoritative row, wait for a projection, or show a clearly defined pending state. A hidden delay is a reliability problem, not simply a database implementation detail.
For updates that must not be lost, optimistic concurrency can use a version column. An update succeeds only if the version still matches what the caller read; on success the version increments. A zero-row update signals that another writer changed the record. This avoids long-held locks in many workflows, but callers need a conflict policy: retry with fresh data, reject the request, or merge changes where safe.
A worked design: ordering and inventory
Consider an online retailer with a relational PostgreSQL database for orders and stock. The customer history query needs each order’s date and a bounded list of line items. The warehouse queue needs unshipped orders for a facility, ordered oldest first. Inventory reservations must not oversell. Product descriptions can change after purchase, but receipts must remain historically accurate.
A reasonable first design uses normalized products, inventory, orders, and order_items tables. Each item references its product and stores purchase-time name and price. The inventory reservation is a conditional update, and order creation plus line insertion occurs in a transaction. The warehouse query receives an index that reflects its actual filter and ordering, perhaps a partial index for the subset of open orders if that predicate is stable and selective.
Suppose customer history becomes a hot path and repeatedly joins the same bounded set of lines. Before migrating databases, test whether a targeted read model or an API-level query change solves the problem. If line counts are small and the order aggregate is usually loaded together, a document representation may reduce read complexity. But moving the entire system to a document store does not remove the need to coordinate stock reservations, preserve immutable purchase details, or prevent duplicate payment processing.
Now suppose product metadata varies widely because the retailer imports catalogs from several suppliers. Keep shared, operational fields—such as product identifier and active status—in columns, and consider JSONB for supplier-specific attributes that are rarely queried. If a particular attribute becomes central to filtering or reporting, promote it into a typed column or a dedicated table, add an appropriate index, and migrate deliberately. This lets observed workload shape the schema instead of making every speculative field permanent.
At each stage, capture the reason for the design: the access pattern, correctness requirement, expected volume, and failure behavior. Revisit it when those inputs change. A design that is efficient at one order per second may need different indexes or partitioning at several thousand; a design that assumes bounded order lines may fail if the product evolves into a bulk-order workflow.
Hybrid storage without accidental dual authority
Many production systems use more than one storage technology: PostgreSQL for transactional records, object storage for large immutable files, Redis for short-lived cache entries, and a search engine for relevance-ranked queries. This can be a sound architecture when each store has a distinct responsibility. It becomes dangerous when two databases are treated as equally authoritative for the same mutable fact.
Define a source of truth for each entity and describe how copies are produced. If PostgreSQL is authoritative for orders and a search index provides order lookup, document how the index is updated, how quickly it should converge, and how it can be rebuilt. Avoid relying on an undocumented sequence of writes to two systems: if the first succeeds and the second fails, the records diverge. An outbox or change-data-capture pipeline can make propagation more reliable, but it still needs idempotent consumers, lag monitoring, and a recovery procedure.
Caching adds a related consistency decision. Cache-aside is straightforward: the application reads from the cache, loads from the database on a miss, then populates the cache. Invalidation on writes is more difficult than lookup. Time-to-live expiration bounds staleness but does not guarantee immediate freshness; explicit invalidation can fail or race with an in-flight read. Choose a policy based on the consequences of stale data, and do not use a cache as the only protection for an invariant such as stock availability.
Storage diversity also increases operational surface area: backup policies, access control, schema evolution, capacity planning, and incident response must cover every system. A second database is justified when it provides a measurable capability the primary store cannot meet economically—not simply because a team expects it to be faster.
Decision checklist for a new model
Before committing to relational, document, or hybrid storage, answer these questions with a representative workload:
- What are the top reads and writes? Include filters, sort order, pagination, and expected result size.
- Which facts change independently? Separate shared current state from immutable historical snapshots.
- Which invariants must be enforced atomically? Identify the transaction boundary and concurrent-writer behavior.
- Are aggregates bounded? Avoid embedding collections whose size or update rate can grow without limit.
- What freshness can users tolerate? State the acceptable delay for search, analytics, and other projections.
- What does the index cost? Test query plans and account for storage, write amplification, and maintenance.
- How will the model evolve? Plan schema migrations, document versioning, backfills, and rollback behavior.
- How will failure be repaired? Specify retries, idempotency, reconciliation, backup restoration, and projection rebuilds.
Then test with production-shaped data and realistic concurrency. A benchmark using a few hundred uniform rows cannot reveal a skewed hot key, a large document, a growing index, or lock contention. Use representative distributions, inspect database statistics and execution plans, and run the write path with concurrent clients. Record both median and tail latency; a design that has a low median but occasional lock waits may fail the service’s real objective.
Choose the cost you can explain
Relational, document, and hybrid designs are not competing answers to a single question. They place costs in different parts of the system. Relational modeling makes relationships and transactional constraints explicit, while joins and schema changes require care. Document modeling can make aggregate reads and evolving records natural, while duplicated data and cross-document coordination need deliberate control. Hybrid designs let each store serve a focused role, at the price of replication, operational complexity, and consistency windows.
For the order example, the decisive choices are concrete: reserve stock with a concurrency-safe operation, preserve purchase-time details as snapshots, index the warehouse query that operators actually run, and define whether downstream views may lag. Starting from those requirements produces a database design that can be tested. Starting from a label produces a migration plan without a reason.