DatabasesVol. 4 · Part IV
0 / 0

Shelves / Databases

DB·62

NoSQL Data Models and Stores

The non-relational families and when they beat SQL. Covers key-value, document, wide-column and graph models (plus time-series and vector stores), with Redis, MongoDB (document modelling, indexes, the aggregation pipeline, transactions, replica sets and sharding), Cassandra and ScyllaDB (query-first modelling, partition and clustering keys, tunable consistency), DynamoDB (partition and sort keys, single-table design, GSIs, conditional writes, streams), Elasticsearch and OpenSearch as stores, and graph databases with Cypher. Ends with when SQL is the right default.

27 topics · ~26 min read · 30-question quiz
Updated Suggest a correction

Start here: other shapes for data

Why other models exist

Relational databases store each fact once and rebuild objects with joins. That's ideal when data is shared, related and queried in unpredictable ways, and it has costs: a screen showing one order may join five tables, a schema change on a billion-row table needs planning, and one server's write capacity is a ceiling. NoSQL ("not only SQL") databases each give up something the relational model offers in exchange for one of these: a data shape that matches how the application reads, flexible schemas, extreme speed for simple operations, or writes spread across many machines. The question for each is: what are your access patterns? Design for the questions you'll ask, not for the shape of the facts.

Documents: store what you read together

Python
orders.insert_one({"_id": 101, "customer": {"id": 1, "name": "Asha", "city": "Bengaluru"}, "status": "DELIVERED",
    "lines": [{"dish": "Masala dosa", "qty": 2, "unit_price_paise": 9000}, {"dish": "Filter coffee", "qty": 2, "unit_price_paise": 3000}],
    "delivery": {"address": "12 MG Road", "slot": "08:30"}})
orders.insert_one({"_id": 102, "customer": {"id": 2, "name": "Ravi", "city": "Chennai"}, "status": "DELIVERED",
    "lines": [{"dish": "Thali", "qty": 1, "unit_price_paise": 18000}], "coupon": "WELCOME50"})       # a different shape
Text
one read returns the whole order: {"_id": 101, "customer": {"name": "Asha"}, "lines": [{"dish": "Masala dosa", "qty": 2, …}, {"dish": "Filter coffee", …}]}
orders containing Filter coffee: [101]
dishes sold (aggregation pipeline): [('Masala dosa', 2), ('Filter coffee', 2), ('Thali', 1)]

A document database (MongoDB, Couchbase, Firestore, Cosmos DB) stores JSON-like documents, and the natural design embeds data that's read together: the order, its customer snapshot and its lines come back in one read with no joins. Documents in one collection needn't share a shape (order 102 has a coupon and no delivery block), which makes evolving the application easy. Queries can reach inside documents (lines.dish), and aggregation pipelines do grouping and joins. The trade-off is the one chapter 55 warned about: embedded copies are duplicates, so when Asha changes her phone number, every order embedding it must be updated too (lab experiment 1), and a schema that isn't enforced will drift (experiment 2). PostgreSQL's jsonb columns give you documents inside a relational database, often the best of both.

Key-value and data structures: Redis

Python
k.hset("cart:asha", mapping={"Masala dosa": 2, "Filter coffee": 1}); k.hincrby("cart:asha", "Filter coffee", 1); k.expire("cart:asha", 3600)
for dish, n in [("Masala dosa", 120), ("Idli", 95), ("Thali", 60), ("Filter coffee", 210)]: k.zincrby("popular:2026-10-29", n, dish)
allowed = k.incr("rate:asha:" + minute) <= 5; k.expire("rate:asha:" + minute, 60)
Text
cart as a hash: {'Masala dosa': '2', 'Filter coffee': '2'} | expires in 3600 s
top dishes today (sorted set): [('Filter coffee', 210.0), ('Masala dosa', 120.0), ('Idli', 95.0)]
7 requests in one minute against a limit of 5: last request allowed? False

A key-value store looks things up by key and nothing else, which makes it extremely fast and easy to distribute (DynamoDB, Riak, etcd, RocksDB). Redis goes further: values are data structures (hashes, lists, sets, sorted sets, streams, counters) with atomic operations, all in memory. A shopping cart with an expiry, a live leaderboard and a rate limiter each took one or two commands. Redis is usually a companion to a system-of-record database (caching, sessions, counters, queues), because keeping everything in RAM and its persistence options make it a poor place for data you can't lose.

Wide-column and graph

  • Wide-column stores (Cassandra, ScyllaDB, Bigtable, HBase) partition rows across many nodes by a partition key and sort them within the partition by a clustering key. You design one table per query ("orders by customer, newest first"), duplicating data freely, and in exchange get writes that scale nearly linearly across machines and stay available when nodes fail. DynamoDB follows similar principles as a managed service.
  • Graph databases (Neo4j, Neptune, Memgraph) store nodes and relationships and traverse them directly ("friends of friends who ordered biryani"), which is awkward in SQL beyond a couple of hops.

Analytical (column) stores

Everything above is about many small reads and writes (OLTP). Analytical databases (ClickHouse, DuckDB, BigQuery, Snowflake, Redshift) are built for few, huge queries that aggregate billions of rows. They store each column separately and compressed, and read only the columns a query uses: in the lab, DuckDB answered a revenue-by-city report over 10 million rows 15× faster than PostgreSQL, from a file 21× smaller.

How deep to go in NoSQL

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Describe document, key-value, wide-column, graph and column stores
L2 Model data for MongoDB, Redis, DynamoDB or Cassandra from access patterns
L3 Explain partitioning, replication and consistency models, storage engines and query capabilities of each
L4 Diagnose duplication drift, schema drift, hot partitions, stale replicas and misuse of a store
L5 Choose stores for a system and design data flows between them (CDC, events)
L6 Operate polyglot persistence with governance of models, retention and costs

Why NoSQL exists

What "NoSQL" means

"NoSQL" (originally "not only SQL") names a family of databases that gave up some relational features (joins, schemas, multi-row ACID transactions, SQL itself) to gain one or more of:

  • Horizontal scalability built in: data partitioned across many nodes from day one.
  • Availability under partitions: Dynamo-style systems keep accepting writes when nodes or links fail (Vol. 5's CAP and PACELC trade-offs).
  • Data models matching specific access patterns: documents, wide rows, graphs, time series.
  • Very low latency for simple operations (in-memory key-value).
  • Flexible schemas for heterogeneous or evolving data.

The movement took off around 2007–2010, with Amazon's Dynamo paper, Google's Bigtable paper, MongoDB, Cassandra (from Facebook) and Redis. Since then the lines have blurred: PostgreSQL has jsonb and scales further than many assumed, MongoDB has multi-document ACID transactions, DynamoDB has transactions, and distributed SQL gives horizontal scale with SQL (chapter 61). The useful question isn't "SQL or NoSQL?" but which data model and which consistency and scaling properties fit this workload.

The data models

key-value "session:abc" → 0x8fa2…"cart:42" → {…}get/put by key: Redis, DynamoDB document { _id: "o-981", status: "PAID", customer: { id: 7, name: "Ada" }, lines: [ {sku: "A1", qty: 2} ] }MongoDB, Couchbase, Firestore wide-column partition user=42ts=10:02 | event=login | ip=…ts=10:05 | event=view | sku=…Cassandra, Scylla, HBase, Bigtable graph Ada Linus Chair FOLLOWS BOUGHT Neo4j, Neptune, Memgraph
The four main NoSQL data models. Key-value maps opaque values by key; documents are nested, self-describing records; wide-column stores keep sorted rows of columns per partition; graphs store nodes and relationships as first-class data.
Model Data shape Access Strengths Weaknesses
Key-value key → value (an opaque blob, or simple typed structures in Redis) Get, put and delete by key; sometimes ranges Fastest, simplest, scales trivially by hashing keys No queries by value (unless you build indexes yourself)
Document Self-describing, nested records (JSON/BSON) grouped in collections By ID, by indexed fields, aggregation pipelines Aggregates map naturally to documents (one read loads an order with its lines); flexible schema Many-to-many relationships and joins are awkward; denormalised data must be kept in sync
Wide-column (column-family) Rows grouped by partition key and sorted by clustering key; sparse columns By partition key (plus a range on the clustering key) Massive write throughput, linear horizontal scaling, multi-datacentre replication, time-ordered data You must model per query; no joins, limited secondary indexing, ad hoc queries are poor
Graph Nodes and relationships, both with properties Traversals: "friends of friends who bought X" Multi-hop relationship queries that would be many self-joins in SQL Scaling and sharding graphs is hard; not for bulk tabular analytics
Time-series Timestamped measurements with tags Range by time and series; downsampling Compression, retention, aggregates over windows Narrow purpose (InfluxDB, TimescaleDB, Prometheus TSDB, VictoriaMetrics, QuestDB)
Vector High-dimensional embeddings Approximate nearest neighbour Semantic search, recommendations, retrieval-augmented generation (RAG, chapter 63) Narrow purpose (pgvector, Qdrant, Milvus, Weaviate, Pinecone; also in Elasticsearch/OpenSearch, MongoDB, Redis)
Search Inverted indexes over documents Relevance-ranked full-text queries, facets Text search (chapter 63) Not a system of record (near-real-time, weaker durability semantics)

The main stores

Key-value: Redis and friends

Vol. 3 ch. 53 covered Redis as a cache and data-structure server. As a primary database it fits ephemeral or derivable data: sessions, rate-limit counters, leaderboards, presence, queues and locks with expiry. Its persistence (RDB snapshots and AOF) and asynchronous replication mean recent writes can be lost on failover, so be careful making it the system of record for important data. Durable KV options include DynamoDB (below), etcd (Raft-replicated and strongly consistent, used for Kubernetes and coordination: small data, not a general database), FoundationDB (an ordered, transactional, distributed KV underneath Apple's and Snowflake's systems), RocksDB embedded (chapter 58), and Redis-compatible durable stores such as Amazon MemoryDB.

Document databases: MongoDB

MongoDB stores BSON documents (binary JSON with extra types: ObjectId, Date, Decimal128, binary) in collections. Documents in a collection needn't share a schema, though production systems use schema validation ($jsonSchema).

Modelling: embed or reference? The central design decision. Model the aggregate (Vol. 3 ch. 34) as one document when the data is read together, owned together and bounded in size:

JavaScript
// Embedded: an order owns its lines and shipping address → one read, one atomic write
{
  _id: ObjectId("…"),
  orderNo: "o-981",
  customer: { id: 7, name: "Ada", email: "ada@x.io" },   // a snapshot copy (denormalised on purpose)
  status: "PAID",
  lines: [ { sku: "A1", qty: 2, unitCents: 1999 }, { sku: "B7", qty: 1, unitCents: 4999 } ],
  totals: { cents: 8997, currency: "EUR" },
  createdAt: ISODate("2026-10-24T10:08:00Z")
}

// Referenced: unbounded or shared relationships stay separate
// customers: { _id: 7, name: "Ada", … }   orders: { customerId: 7, … }   (an order count per customer is unbounded)
Embed when Reference when
One-to-few, owned by the parent (order lines, addresses) One-to-many with unbounded growth (comments on a viral post, events per device)
Always read together Accessed independently
Updated together (single-document writes are atomic) Shared by many parents (products referenced by orders)
Bounded size (the document limit is 16 MB, but aim far lower) Frequently updated independently by many writers

Patterns from MongoDB practice: extended reference (copy a few fields of the referenced entity), subset (embed the latest 10 reviews, reference the rest), bucket (group time-series readings per hour into one document), computed (maintain totals on write), and outlier (overflow documents for the rare huge case).

JavaScript
// Indexes: single-field, compound (ESR rule: Equality, Sort, Range order), multikey (arrays), text, geo, TTL, partial, wildcard
db.orders.createIndex({ "customer.id": 1, createdAt: -1 });              // a customer's latest orders
db.orders.createIndex({ status: 1 }, { partialFilterExpression: { status: { $in: ["PAYMENT_FAILED", "DISPUTED"] } } });
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });   // TTL: auto-delete expired documents

// Queries
db.orders.find({ "customer.id": 7, status: "PAID" }).sort({ createdAt: -1 }).limit(20);

// Aggregation pipeline: stages transform a stream of documents (≈ SQL's WHERE/GROUP BY/JOIN as a pipeline)
db.orders.aggregate([
  { $match: { status: "PAID", createdAt: { $gte: ISODate("2026-10-01") } } },
  { $unwind: "$lines" },
  { $group: { _id: "$lines.sku", units: { $sum: "$lines.qty" }, revenue: { $sum: { $multiply: ["$lines.qty", "$lines.unitCents"] } } } },
  { $sort: { revenue: -1 } },
  { $limit: 10 },
  { $lookup: { from: "products", localField: "_id", foreignField: "sku", as: "product" } }   // a left outer join
]);

// Atomic single-document update operators: no read-modify-write race
db.orders.updateOne({ _id: id, status: "PENDING" }, { $set: { status: "PAID", paidAt: new Date() }, $inc: { version: 1 } });

Consistency and distribution:

  • Replica sets: a primary plus secondaries, with Raft-like elections and automatic failover.
  • Write concern (w: "majority" waits for replication to a majority, so writes survive failover; w: 1 is faster but can roll back) and read concern (majority, linearizable, snapshot) plus read preference (primary, or secondaries with staleness). Since MongoDB 5.0 the default write concern is majority.
  • Multi-document ACID transactions (4.0 on replica sets, 4.2 across shards) are available, but designs that need many of them may fit SQL better.
  • Sharding by a shard key (hashed or ranged) into chunks, balanced across shards automatically, with mongos routers. Shard keys can be refined and resharded online in recent versions.
  • Change streams (built on the oplog) give CDC.

Other document stores: Couchbase (KV + documents + N1QL/SQL++), Firestore (mobile and web sync), Azure Cosmos DB (multi-model, five consistency levels), Amazon DocumentDB (MongoDB API-compatible), and PostgreSQL jsonb (documents with SQL and ACID: often enough).

Java
// Java (MongoDB driver / Spring Data MongoDB)
@Document("orders")
record OrderDoc(@Id ObjectId id, String orderNo, CustomerRef customer, String status, List<Line> lines, Instant createdAt) {}
interface OrderRepository extends MongoRepository<OrderDoc, ObjectId> {
    List<OrderDoc> findByCustomerIdAndStatusOrderByCreatedAtDesc(long customerId, String status, Pageable p);
}

Wide-column stores: Cassandra and ScyllaDB

Apache Cassandra (and ScyllaDB, a C++ reimplementation with a shard-per-core architecture) combines Dynamo-style distribution (a consistent-hashing ring, leaderless replication, tunable consistency) with a Bigtable-style data model (partitions of sorted rows on an LSM storage engine, chapter 58).

Query-first modelling: you design one table per query pattern, because a query must specify the partition key, and can only range over the clustering columns in their defined order:

SQL
-- CQL: "the latest events of a user", and "events of a type by day"
CREATE TABLE events_by_user (
    user_id    uuid,
    event_time timeuuid,
    type       text,
    payload    text,
    PRIMARY KEY ((user_id), event_time)          -- partition key: user_id; clustering column: event_time
) WITH CLUSTERING ORDER BY (event_time DESC)
  AND default_time_to_live = 7776000;            -- 90 days

CREATE TABLE events_by_type_day (
    type text, day date, event_time timeuuid, user_id uuid, payload text,
    PRIMARY KEY ((type, day), event_time, user_id)   -- composite partition key bounds partition size (bucketing)
);

-- The same event is written to BOTH tables (denormalisation is the norm; a logged batch makes the writes atomic, not isolated)
SELECT * FROM events_by_user WHERE user_id = ? LIMIT 50;                         -- efficient: one partition
SELECT * FROM events_by_user WHERE type = 'login' ALLOW FILTERING;                -- scans the cluster: don't

Key concepts:

  • Partitions are the unit of distribution and should stay bounded (tens to hundreds of MB at most). Bucket unbounded ones (by day or hour). Hot partitions overload replicas.
  • Replication factor (RF = 3 typical) per datacentre. Any node can coordinate a request.
  • Tunable consistency per query: ONE, QUORUM, LOCAL_QUORUM, ALL. If R + W > RF (for example QUORUM reads and writes with RF = 3: 2 + 2 > 3), reads overlap the latest acknowledged write. Lower levels trade consistency for latency and availability.
  • Conflict resolution is last-write-wins by timestamp (cell-level), so clock skew matters, and concurrent writes to the same cell silently lose one.
  • Repairs (anti-entropy with Merkle trees), hinted handoff and read repair converge replicas. Tombstones (deletes) have costs: reading over many tombstones is slow, and they're purged only after gc_grace_seconds.
  • Lightweight transactions (INSERT … IF NOT EXISTS, UPDATE … IF col = ?) use Paxos for compare-and-set per partition. They're slower (several round trips), so use them sparingly. General multi-partition transactions (the Accord protocol) are being added in a future Cassandra release.
  • Fits: write-heavy time series, messaging and inboxes, IoT, activity feeds, multi-datacentre always-on workloads (Apple, Netflix and Discord ran huge Cassandra fleets, and Discord later moved to ScyllaDB). Doesn't fit: ad hoc queries, joins, strongly consistent multi-row transactions.

DynamoDB

Amazon DynamoDB is a fully managed key-value and document store, derived from Dynamo's ideas but with a single-leader-per-partition design, synchronous replication across three AZs, and predictable single-digit-millisecond latency at any scale.

  • Primary key: a partition key (PK), optionally plus a sort key (SK). Items with the same PK form an item collection, sorted by SK, so Query can read ranges within it.
  • Secondary indexes: GSIs (global: a different PK and SK, asynchronously maintained, so eventually consistent) and LSIs (local: the same PK, an alternative SK, defined at table creation).
  • Operations: GetItem, PutItem, UpdateItem (with update expressions and condition expressions for atomic compare-and-set), Query (one partition, a range on SK), Scan (everything: avoid), BatchWriteItem, and TransactWriteItems/TransactGetItems (ACID across up to 100 items).
  • Capacity: on-demand (pay per request) or provisioned (RCU/WCU with auto-scaling). Throughput is per partition, with adaptive capacity for hot keys.
  • Reads: eventually consistent by default, or strongly consistent at double the cost (not available on GSIs).
  • DynamoDB Streams (CDC) feed Lambda and Kinesis. TTL expires items. Global tables replicate across regions (multi-active with last-writer-wins, plus a multi-region strong consistency option introduced in 2025).

Single-table design (Rick Houlihan, Alex DeBrie): store several entity types in one table with generic PK/SK attributes, so that each access pattern is one Query that returns related items together (pre-joined):

Text
PK             SK                       attributes
CUST#7         PROFILE                  name=Ada, email=…
CUST#7         ORDER#2026-10-24#o-981   status=PAID, total=8997
CUST#7         ORDER#2026-10-20#o-955   status=SHIPPED, …
ORDER#o-981    LINE#001                 sku=A1, qty=2
ORDER#o-981    LINE#002                 sku=B7, qty=1
GSI1PK=STATUS#PAID   GSI1SK=2026-10-24#o-981   (sparse GSI: only items with these attributes appear)

Query(PK = "CUST#7", SK begins_with "ORDER#")           → a customer's orders, newest via ScanIndexForward=false
Query(PK = "CUST#7")                                     → profile + orders in one request
Query(GSI1, PK = "STATUS#PAID")                          → paid orders across customers
# Python (boto3): a conditional write as an atomic compare-and-set (optimistic concurrency)
table.update_item(
    Key={"PK": "ORDER#o-981", "SK": "META"},
    UpdateExpression="SET #s = :paid, version = version + :one",
    ConditionExpression="#s = :pending AND version = :v",
    ExpressionAttributeNames={"#s": "status"},
    ExpressionAttributeValues={":paid": "PAID", ":pending": "PENDING", ":v": 3, ":one": 1},
)   # raises ConditionalCheckFailedException if someone else changed it

The trade-off: single-table design requires knowing your access patterns up front, and new patterns may need new GSIs or a data migration. In return you get flat, predictable performance and cost at any scale. Teams that value flexibility often use one table per entity, or use DynamoDB for specific high-scale paths only.

Elasticsearch and OpenSearch as data stores

Elasticsearch (Elastic) and OpenSearch (its Apache-licensed fork, now under the Linux Foundation) are distributed search engines built on Apache Lucene (chapter 63). They're often used for logs (the ELK/OpenSearch stack), observability and analytics over semi-structured data. As primary databases they're risky:

  • Indexing is near-real-time (refresh about every second).
  • There are no multi-document transactions.
  • Mapping changes often require reindexing.
  • Historically there were durability surprises under some failure modes.

The standard architecture is the system of record in a database, with the search index derived from it via CDC or events and rebuildable at any time (chapter 61's CQRS).

Graph databases

Property graphs store nodes and relationships with properties. The data is index-free adjacency: each node directly references its neighbours, so traversals cost per hop, not per table size:

Cypher
// Neo4j Cypher: products bought by people Ada follows, which Ada hasn't bought, ranked by popularity
MATCH (ada:Person {name: 'Ada'})-[:FOLLOWS]->(friend:Person)-[:BOUGHT]->(p:Product)
WHERE NOT (ada)-[:BOUGHT]->(p)
RETURN p.name, count(DISTINCT friend) AS friends
ORDER BY friends DESC
LIMIT 10;

// Variable-length paths: who's within 3 hops?
MATCH path = shortestPath((a:Person {name:'Ada'})-[:KNOWS*..3]-(b:Person {name:'Grace'})) RETURN path;

The SQL equivalent needs self-joins per hop, or recursive CTEs (chapter 56), and gets harder as hops vary. ISO GQL (2024) standardises a graph query language derived from Cypher, and SQL/PGQ (SQL:2023) adds property-graph queries to SQL itself (Oracle 23ai supports it, and implementations are emerging elsewhere). Other approaches: RDF triple stores with SPARQL (knowledge graphs, linked data), and graph extensions for PostgreSQL (Apache AGE).

Fits: fraud rings, recommendation, identity and access graphs, network and IT topology, knowledge graphs, supply chains. Many "graph" needs are actually small and served well by recursive CTEs or adjacency tables in PostgreSQL.

Choosing

Column stores and analytical databases

Every store above is optimised for OLTP: many small reads and writes of individual records. Analytics is the opposite workload (OLAP): a few queries that scan and aggregate millions or billions of rows, usually touching a handful of columns of very wide tables. Row stores read entire rows (all columns) page by page, so a query summing one column of a 50-column table reads 50 times more data than it needs.

Column stores keep each column in its own file or segment. A query reads only the columns it references; values of one column are similar, so they compress extremely well (run-length, dictionary and delta encodings, often 5–20×); and execution is vectorised, processing batches of a few thousand values per operation with tight CPU loops and SIMD instead of one row at a time. Many keep min/max metadata per block (zone maps, like BRIN) so filters skip whole blocks.

System Shape Notes
DuckDB Embedded, in-process (like SQLite for analytics) Queries Parquet, CSV and PostgreSQL directly; ideal for notebooks, ETL and small-to-medium analytics
ClickHouse Server, open source, shared-nothing cluster Very fast ingestion and aggregation; MergeTree engine (an LSM of sorted column parts); popular for logs, events and observability
BigQuery, Snowflake, Redshift, Databricks SQL Managed cloud warehouses Storage separated from compute; pay per query or per warehouse size; lakehouse formats (Iceberg, Delta)
Apache Parquet / ORC Columnar file formats The storage layer of data lakes; read by all of the above
PostgreSQL extensions Columnar access methods (Citus columnar, Hydra), pg_duckdb Analytics close to the operational database

Column stores are poor at single-row updates and point lookups (a row is spread across many files), so the usual architecture keeps OLTP in a row store and copies data into the column store with batch ETL or change-data capture. The lab compares PostgreSQL and DuckDB on the same 10 million rows.

Consistency in NoSQL systems

System Replication Default read consistency Conflict handling
MongoDB Leader per replica set (Raft-like) Primary reads are strongly consistent; secondaries are eventual Single leader; majority write concern prevents rollbacks
Cassandra / Scylla Leaderless (Dynamo style) Tunable (ONE … ALL) Last write wins per cell (timestamps)
DynamoDB Leader per partition, synchronous across 3 AZs Eventually consistent (strong optional) Conditional writes; global tables: last writer wins (or multi-region strong option)
Redis Async primary/replica Primary reads are consistent; replicas lag Failover can lose acknowledged writes
Cosmos DB Configurable Five levels: strong, bounded staleness, session, consistent prefix, eventual Last write wins or custom merge
Riak (historical), CRDT-based stores Leaderless Eventual CRDTs / sibling resolution (Vol. 5)

When SQL is the right default

The roadmap's instruction is to know when SQL is the right default. In practice, that's most of the time:

  • Your data is relational: entities with relationships, queried in many different ways, some not known yet. SQL's ad hoc querying is a huge long-term asset.
  • You need integrity: constraints, foreign keys, multi-row transactions with real isolation. Money, inventory, bookings and permissions all need this.
  • Your scale fits a single primary plus replicas, which covers the large majority of systems, including many large businesses.
  • PostgreSQL covers many "NoSQL" needs: jsonb documents, arrays, full-text search, geospatial (PostGIS), time series (TimescaleDB, partitioning), vectors (pgvector), queues (SKIP LOCKED), and key-value (hstore, plain tables with good indexes).
  • Operational simplicity: one well-understood database beats three specialised ones that each need expertise, backups, monitoring and security.

Reach for NoSQL when a specific requirement clearly needs it:

  • Massive write throughput or data size with simple access patterns (Cassandra, Scylla, Bigtable, DynamoDB).
  • Always-on multi-region writes with tolerance for eventual consistency.
  • Serverless, managed, effectively unlimited key-value access with predictable latency (DynamoDB).
  • Ephemeral, ultra-low-latency data structures (Redis).
  • Deep relationship traversal as the core workload (graph databases).
  • Relevance-ranked search (search engines, as a derived store).
  • Document-shaped aggregates with modest relational needs, if the team prefers the document model (MongoDB; or PostgreSQL jsonb).

Polyglot persistence (each service or workload uses the store that fits) is sound, but every additional database is another system to operate, secure, back up and understand. Default to one relational database, and add specialised stores deliberately, usually as derived read models fed by CDC, so the relational database remains the source of truth.

Lab: the trade-offs of non-relational stores

FerretDB 1.24 (a MongoDB wire-protocol server, here backed by PostgreSQL) accessed with pymongo; Redis 7.0 with a replica; PostgreSQL 16; DuckDB, all on one 2-core machine. Experiments 1 and 2 are about the document model and behave the same on MongoDB itself.

Experiment 1: embedded copies drift

500 orders each embed the customer's name and phone. The customer changes their number in the customers collection:

Text
customer changes phone: customers collection updated (1 doc); 500 embedded copies in orders still show the old number
until a second update rewrote 500 documents

Embedding made reading an order one operation, and turned one fact into 501 copies. Every write to the shared fact now needs an updateMany (and, for atomicity across both collections, a multi-document transaction), plus code that knows about every place the data was copied. The modelling rule: embed what belongs to the document and is read with it (order lines, delivery address as of the order), reference what's shared and changes independently (the customer's current contact details), and decide deliberately which embedded fields are snapshots that should never change.

Experiment 2: schema drift

1,000 order lines for Idli with qty: 2, of which 100 were written by an older app version with qty: "2" (a string):

Text
$sum reports 1800 sold (expected 2000), no error

$sum silently ignores non-numeric values, so the report was 10% low and nothing complained. Without a schema, the database accepts whatever each version of each application writes, and every reader must cope with every historical shape. Use schema validation (MongoDB's $jsonSchema validators, PostgreSQL CHECK constraints on jsonb), migrate old documents rather than accumulating shapes, and version documents (schemaVersion field) when shapes must change.

Experiment 3: when a data structure beats SQL

One million players with scores, in a Redis sorted set and in an indexed PostgreSQL table:

Text
top 10:                 Redis ZREVRANGE 0.09 ms | PostgreSQL ORDER BY s DESC LIMIT 10 (indexed) 0.07 ms
rank of one player:     Redis ZREVRANK  0.07 ms | PostgreSQL count(*) WHERE s > mine           38.21 ms

The top 10 was equally fast both ways: a B-tree index delivers rows in order. But "what's my rank?" needs a count of everyone above you; a B-tree doesn't store subtree counts, so PostgreSQL counted about half a million index entries, while Redis's sorted set (a skip list with span counts) answers rank queries in O(log n): 550× faster. Pick specialised stores for operations their structures make cheap, and keep the system of record where integrity lives.

Experiment 4: eventual consistency in Redis

A write to the Redis primary followed immediately by a read from its replica, 1,000 times:

Text
1 stale reads | WAIT 1 100 after a write → acknowledged by 1 replica(s)

Redis replication is asynchronous, like PostgreSQL's: on localhost the replica was almost always current, but not always, and across a network it's far more often behind. WAIT numreplicas timeout blocks until the given number of replicas have the write, which narrows (but doesn't close; Redis can still lose acknowledged writes on failover) the window. Most NoSQL systems let you choose per operation: MongoDB write concerns (w: "majority") and read concerns, Cassandra's consistency levels (QUORUM reads and writes overlap so reads see the latest write), DynamoDB's strongly consistent reads at twice the cost.

Experiment 5: row store versus column store

10 million sales rows (7 columns, including a 40-character note), query: revenue and average quantity by city for the second half of the year:

Text
PostgreSQL (row store, parallel query): 563 ms, 1123 MB
DuckDB (column store):                    38 ms,   52 MB on disk
same answers: True

PostgreSQL read every page of the table (all seven columns, every row) with three processes; DuckDB read three compressed columns, skipped blocks outside the date range using min/max metadata, and aggregated in vectorised batches: 15× faster from a file 21× smaller. The reverse holds for OLTP: updating one order's status is one page write in PostgreSQL but a rewrite of column segments in an analytical store. Keep transactions in the row store and send data to the column store for analytics.

Try it yourself

  1. Redesign experiment 1 so orders reference the customer by id and store only a snapshot of the delivery address. Write the "show order 101" query with $lookup.
  2. Add a $jsonSchema validator to the lines collection requiring qty to be an integer, and retry experiment 2's insert.
  3. Model the café's "orders by customer, newest first" and "orders by day for the kitchen" queries as two Cassandra-style tables, and write the duplicated insert.
  4. Point DuckDB directly at the PostgreSQL table with its postgres extension and compare the time with copying the data first.

Revision sheet: NoSQL data models and stores

Key ideas

  • Why NoSQL: access-pattern-shaped data, flexible schemas, horizontal write scaling, specialised operations; each gives up some of joins, cross-entity transactions, enforced schemas or immediate consistency.
  • Key-value: Redis (data structures, TTLs, Lua, streams; persistence via RDB/AOF; replication and cluster with hash slots), Memcached, etcd, RocksDB as an embedded engine.
  • Document: MongoDB (BSON, embedding vs referencing, indexes including multikey, aggregation pipeline, transactions, replica sets, sharding), Couchbase, Firestore; PostgreSQL jsonb.
  • Wide-column: Cassandra/ScyllaDB (partition and clustering keys, query-first tables, tunable consistency, LSM storage, tombstones), Bigtable/HBase.
  • DynamoDB: partition and sort keys, single-table design, GSIs, capacity modes, conditional writes.
  • Search engines as stores: Elasticsearch/OpenSearch (chapter 63), with caution as a system of record.
  • Graph: property graphs (Cypher, GQL), traversals; SQL/PGQ arriving in relational databases.
  • Analytical: column stores (DuckDB, ClickHouse, warehouses), compression, vectorised execution, Parquet and lakehouse formats.
  • Consistency: replication modes, quorum reads/writes, read/write concerns, eventual consistency and its anomalies.

Numbers to remember

  • Lab: one phone change left 500 stale embedded copies; 10% of documents with a string quantity made a report 10% low silently; Redis rank queries 550× faster than SQL count(*); DuckDB 15× faster and 21× smaller than PostgreSQL for an aggregate over 10M rows.

Pitfalls

  • Choosing NoSQL for scale you don't have; losing integrity you needed.
  • Embedding shared, mutable data; unbounded arrays inside documents (16 MB MongoDB limit).
  • No schema validation; silent type drift.
  • Redis as a durable primary store; cache and durable data in one Redis.
  • Cassandra queries without the partition key; large partitions; tombstone build-up.
  • Running analytics on the OLTP row store at scale; point updates in column stores.

Glossary

  • Access pattern: a specific query or write the application performs.
  • Embedding / referencing: storing related data inside a document / by id.
  • Partition key / clustering key: decides the node / the order within a partition.
  • Quorum: a majority of replicas; overlapping read and write quorums give strong reads.
  • OLTP / OLAP: transactional vs analytical workloads.
  • Vectorised execution: processing batches of column values per operation.