NoSQL: Families & Data Models
"There's no strong definition of the concept out there, no trademarks, no standard group, not even a manifesto." — Martin Fowler, Nosql Definition, martinfowler.com (9 January 2012)
Summary: NoSQL is not one technology but a set of families, each trading part of what a relational database promises for a data model shaped around one access pattern. Focus: The history of the word, the families (key-value, document, wide-column, graph, time-series, search, vector, object store), the Dynamo and Bigtable lineages, consistency and query support per product, and when relational still wins. Learning goal: Given a workload, name the access patterns, pick a family and a product (or decide to stay relational), and state what that choice costs in consistency, queries and operations.
This page is the map for non-relational stores. It shows what each family is, where it came from, what it can and cannot answer, how it scales, what consistency and transactions it offers, and how to choose, combine and migrate. It deliberately does not re-teach the deep dives: Redis, MongoDB, Wide-Column & Key-Value at Scale, Cassandra & ScyllaDB, Graph Databases, Full-Text Search and Vector Search. For the system-design view of the same choice read SQL vs NoSQL decision, CAP & PACELC and ACID vs BASE.
Page map
| If you are looking for | Go to |
|---|---|
| The families and their products on one screen | Everything in one minute |
| Why NoSQL exists and where the word came from | Why NoSQL exists, History |
| Aggregates, schema-on-read, denormalisation, access-pattern-first | Data-model ideas |
| One block per family: key-value, document, wide-column, graph, time-series, search, vector, object store | The families, one by one |
| Dynamo and Bigtable lineages | Two papers behind the families |
| Consistency, transactions, queries, secondary indexes, scaling per product | Per-product behaviour |
| CAP positioning per product | CAP positioning |
| Sharding, quorums, hot partitions, error codes | Mechanics |
| When relational still wins; polyglot persistence and its cost | Solving the classic problems |
| Requirement to family table; hosted vs self-managed; migrations | Choosing a family |
| Multi-model databases (ArangoDB, Cosmos DB, Postgres) | Multi-model |
| Monolith to distributed data | In architecture |
| Model one domain in Postgres, MongoDB and Redis | Lab |
| Wrong beliefs, cheat sheet, glossary | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The families. Every row is unpacked in the families section.
| Family | Data model | Native question | Scales by | Products |
|---|---|---|---|---|
| Key-value | key to opaque value (or a typed structure) | "give me the value for this key" | Hash partitioning (DynamoDB, Riak), hash slots (Redis Cluster), client-side (Memcached) | Redis, Memcached, DynamoDB, Riak |
| Document | key to JSON/BSON document with nested fields | "give me this aggregate, or documents matching a filter" | Sharding on a shard key (MongoDB), bucket partitions (Couchbase) | MongoDB, Couchbase, CouchDB, Firestore |
| Wide-column | partition key, then sorted clustering columns, sparse columns | "give me a slice of rows of one partition" | Consistent hashing of the partition key (Cassandra), row-key ranges (HBase, Bigtable) | Cassandra, ScyllaDB, HBase, Bigtable |
| Graph | nodes and edges with properties | "walk the relationships from here" | Mostly vertical; clustering for reads; sharding is hard | Neo4j, Neptune, ArangoDB |
| Time-series | timestamped points, tags and fields | "aggregate this metric over a time range" | Time partitioning (chunks, shards), columnar storage | InfluxDB, TimescaleDB, ClickHouse |
| Search | inverted index over documents | "rank documents by relevance to these terms" | Index shards and replicas | Elasticsearch, OpenSearch |
| Vector | embeddings with an ANN index | "nearest neighbours of this vector" | Index shards, or one Postgres node | pgvector, Milvus, Pinecone |
| Object store | blob by key plus metadata | "give me this file" | Provider-managed | S3, GCS, MinIO |
| Relational (the baseline) | tables, rows, foreign keys | "any question over related data" | Vertical, replicas, then partitioning | PostgreSQL, MySQL, SQL Server |
Consistency and transactions per family. Details in per-product behaviour.
| Family and product | Default consistency | Transactions |
|---|---|---|
| Redis (single node) | Strong on the primary; replicas are asynchronous | MULTI/EXEC and Lua are atomic, with no rollback |
| Memcached | None to speak of: a cache, with a CAS token | Single operation only |
| DynamoDB | Eventually consistent reads by default; strongly consistent read optional | TransactWriteItems, up to 100 actions |
| MongoDB | Single-document atomic; read and write concerns tune it | Multi-document ACID on replica sets and sharded clusters |
| Cassandra, ScyllaDB | Tunable per query (ONE, QUORUM, ALL) | Lightweight transactions (compare-and-set) only |
| HBase, Bigtable | Strong per row within one cluster | Single-row atomic only |
| Neo4j | ACID | Full ACID transactions |
| Elasticsearch, OpenSearch | Near real-time (refresh about every second) | None across documents |
| Cosmos DB | Five selectable levels, from Strong to Eventual | Within one logical partition |
The three things to do.
| Situation | Do this |
|---|---|
| You do not yet know your queries | Stay relational; add jsonb, pgvector or full-text search to PostgreSQL before adding a second database |
| One access pattern dominates and is measured | Pick the family built for it, list every query first, and design keys around them |
| You added a second store | Decide who is the system of record, then sync with an outbox or CDC, never with a hopeful dual write |
Why NoSQL exists
Relational databases were built to answer any question over normalised data, correctly, on one machine. Around 2005 to 2010 large web companies hit limits that this design handles badly: write volumes beyond one primary, data that does not fit tables (nested documents, graphs, time-stamped points), and availability targets that make a single primary an unacceptable point of failure. The answer was a set of systems that each give up something general in exchange for one thing done well and spread over many machines.
| Relational (the general tool) | NoSQL family (the specialised tool) |
|---|---|
| Normalised tables, one place per fact | Aggregates shaped like what the application reads together |
| Any query, planned at run time | A short list of queries the layout makes cheap |
| Multi-row ACID transactions | Per-key or per-partition atomicity; more only at a cost |
| Scale up first, partition later | Partitioning is part of the data model from day one |
| Schema enforced on write | Schema enforced by the reading code (schema-on-read), or not at all |
| Joins and constraints in the engine | Joins and integrity rules in the application |
The analogy we reuse on this page: a library. The relational catalogue is a card index: every book, author and loan has its own card, linked by numbers, and any question can be answered by cross-checking cards, at a cost. A document store is a binder per customer: everything about one customer ready to hand over, awkward for "how many copies of this title are out?". A key-value store is the coat-check counter: hand over a ticket, get exactly one thing. A wide-column store is a long shelf sorted by a label, where you can grab a run of neighbouring books but cannot ask for "all red books". A graph is the map of who recommended which book to whom. A search engine is the back-of-book index. Each is excellent for the question it was built for.
Three common misunderstandings, up front
- "NoSQL means no schema." There is always a schema; it moved from the database into the code that reads the data.
- "NoSQL is faster and scales better." Each family is fast for one access pattern and awkward for others; a measured need, not fashion, justifies it.
- "NoSQL means giving up consistency." Some stores are eventually consistent by default, some are strongly consistent, and several (DynamoDB, Cassandra, Cosmos DB, MongoDB) let you choose per request.
History: where the word comes from
The word "NoSQL" was first used in the late 1990s as the name of an open-source relational database led by Carlo Strozzi, which has no bearing on today's usage. The modern sense comes from an informal meetup on 11 June 2009 in San Francisco organised by Johan Oskarsson, where Voldemort, Cassandra, Dynomite, HBase, Hypertable, CouchDB and MongoDB were presented. (The date and the list are from Fowler's article, a secondary source; the meetup itself was not checked against a primary record.) Fowler also records the "Not Only SQL" reading and prefers to reserve it for the ecosystem, using the name PolyglotPersistence for that idea. He lists common characteristics, none of them definitional: not using the relational model nor SQL, open source, designed to run on large clusters, based on the needs of 21st century web properties, and no schema.
1998 Carlo Strozzi names a relational DB "NoSQL" (unrelated to today's meaning)
2004-2006 Google publishes GFS, MapReduce, Bigtable (OSDI 2006)
2007 Amazon publishes Dynamo (SOSP 2007)
2008-2009 Cassandra, HBase, CouchDB, MongoDB, Redis, Voldemort appear
2009-06-11 San Francisco meetup puts the label "NoSQL" on the movement
2010s Managed services: DynamoDB (2012), Firestore, Atlas; search and time-series grow
2020s Postgres absorbs jsonb, full-text, pgvector; "NewSQL" and distributed SQL arriveData-model ideas
Three ideas separate NoSQL design from relational design and matter more than the family names.
Aggregate-oriented model Must-know
In plain words: you store together what you read together: the order with its lines, the user with their settings.
Common misunderstanding: "an aggregate is just a denormalised table." It is also the unit of atomicity and distribution: most NoSQL stores guarantee atomic updates inside one aggregate and little across aggregates.
Definition: an aggregate (a term from Eric Evans' domain-driven design, picked up by the NoSQL community) is a cluster of related objects treated as one unit for storage, consistency and distribution; the aggregate boundary is the transaction boundary.
1 load order 1001 (one document, lines embedded) -> 1 read
2 change line 2 quantity in memory
3 write order 1001 back (single-document atomic write) -> 1 write
4 inventory for sku-9 lives in ANOTHER aggregate: no atomic link to step 3Real scenario: a shopping cart read on every page view (one fetch), a chat room with its last 50 messages, a product page with specs and variants; counter-case: stock shared by many orders must not live inside any order.
| Question | Relational | Aggregate store |
|---|---|---|
| Read one order with lines | Join of 2 tables | One document or one key group |
| Atomic across two orders | One transaction | Not guaranteed (MongoDB offers it, at a cost) |
| Report across all orders | One GROUP BY | Aggregation pipeline or a scan |
Fix / how to use it: draw the aggregate around the things that change together and are read together, reference everything else by id.
-- relational: the aggregate is rebuilt by a join on every read
SELECT o.id, o.total_cents, l.sku, l.qty
FROM orders o JOIN order_lines l ON l.order_id = o.id
WHERE o.id = 1001;The Go and Laravel versions of the three shapes are in Go and Laravel.
Schema-on-read Must-know
In plain words: the database lets you store whatever you like; the code that reads it decides what it means.
Common misunderstanding: "I can change the shape freely." Old documents stay old; every reader must cope with every shape ever written.
Definition: structure is applied at read time, not enforced at write time. MongoDB's documentation puts the design goal as "The flexible data model lets you store data according to your application's data access patterns." MongoDB can still enforce rules with schema validation ($jsonSchema validators); Cassandra and DynamoDB enforce key columns only.
1 v1 writer stores {name: "Ada Lovelace"}
2 v2 writer stores {first: "Ada", last: "Lovelace", schemaVersion: 2}
3 reader sees both shapes in one collection
4 reader upgrades v1 on read, writes back (lazy migration)Real scenario: adding a field to 200 million documents without a downtime window; a mobile client that must read documents written by older app versions.
| Store | What is enforced on write |
|---|---|
| PostgreSQL, MySQL | Column types, NOT NULL, constraints, foreign keys |
| MongoDB | Nothing by default; optional $jsonSchema validation |
| DynamoDB | Key attributes and their types only |
| Cassandra | Declared columns and types (CQL schema), no foreign keys |
| Redis | Value type of a key (WRONGTYPE error), nothing inside it |
Fix / how to use it: store a schemaVersion, write a reader that upgrades old shapes, and turn on validation where the shape is stable.
// Reader that upgrades old shapes lazily (see the Go snippet for the full model).
type Profile struct {
SchemaVersion int `json:"schemaVersion"`
Name string `json:"name,omitempty"` // v1
First string `json:"first,omitempty"` // v2
Last string `json:"last,omitempty"` // v2
}Denormalisation and duplication Important
In plain words: you copy data so that a read needs one fetch, and you accept that a change must touch every copy.
Common misunderstanding: "the database will keep the copies in sync." It will not; there are no foreign keys or cascades across documents or partitions.
Definition: denormalisation stores a fact in more than one place. Update cost and staleness risk rise; read cost falls. The same trade is covered for relational design in Schema Design, Normalization & Data Types.
1 customer 42 renames Ada -> Ada L.
2 orders embed customer name: 1,800 documents hold the old name
3 option A: update all 1,800 (fan-out write)
4 option B: accept the old name on historical orders (it was true then)Real scenario: invoices must keep the name and price at the time of sale (copy on purpose); a "followers count" shown on a profile is a counter copy that a background job reconciles.
| Strategy | Read | Write | Staleness |
|---|---|---|---|
| Embed (copy) | One fetch | Fan-out on change | Until fan-out completes |
| Reference (id) | Two fetches or a join-like lookup | One write | None |
| Snapshot at event time | One fetch | Once, at creation | By design |
Fix / how to use it: copy what is immutable or historical; reference what changes and must be current.
Access-pattern-first design Must-know
In plain words: in a relational database you model the facts and ask questions later; in most NoSQL stores you write down the questions first and model the data to answer them.
Common misunderstanding: "I can add the query later like adding an index." In Cassandra and DynamoDB a new query often means a new table or a new index with its own cost, and sometimes a backfill.
Definition: the AWS guidance for DynamoDB: "In DynamoDB, you design your schema specifically to make the most common and important queries as fast and as inexpensive as possible." The keys are chosen from the queries.
1 list queries: Q1 order by id, Q2 last 20 orders of a customer, Q3 orders by status
2 Q1 -> partition key order_id
3 Q2 -> table/index with partition key customer_id, sort key created_at
4 Q3 -> sparse index or a separate table by status (and its write cost)Real scenario: a DynamoDB single-table design with composite keys (PK = CUSTOMER#42, SK = ORDER#2026-11-24#1001); a Cassandra table per query ("query-first modelling").
| Store | Cost of a new query |
|---|---|
| PostgreSQL, MySQL | Add an index or write a join |
| MongoDB | Add an index, or reshape documents |
| DynamoDB | Add a GSI (eventually consistent, extra cost) or redesign keys |
| Cassandra | New table (or SAI/materialised view with caveats), duplicate writes |
| Redis | Write-time code that maintains a new set or sorted set |
Fix / how to use it: list queries with frequency and latency target before choosing keys; revisit when a new query arrives.
Secondary indexes Important
In plain words: an index on something other than the main key lets you search by another field, but each store pays for it differently.
Common misunderstanding: "every database has cheap secondary indexes." Redis has none (you maintain them by hand); Cassandra's classic secondary index scales poorly on high-cardinality or large clusters; DynamoDB GSIs are eventually consistent.
Definition: a secondary index is a second access path. It is either local (co-located with the data it indexes, so queried per partition) or global (a separate partitioned structure, so queried across the cluster, usually asynchronously updated).
1 write order 1001 to main table (partition by order_id)
2 the GSI on customer_id is updated asynchronously
3 query GSI right away -> order 1001 may be missing for a short time
4 query again -> present (eventually consistent)Real scenario: "orders of a customer" on a table keyed by order id; "users by email" on a table keyed by user id (the unique email check is a separate problem).
| Product | Secondary index support | Consistency of the index |
|---|---|---|
| PostgreSQL | Many index types, transactional | Same as the table |
| MongoDB | Single, compound, multikey, text, geospatial, TTL | Updated with the write |
| DynamoDB | LSI (same partition key, strongly consistent reads possible) and GSI | GSI is eventually consistent |
| Cassandra | Secondary indexes, SAI, materialised views, or a query table | Local to node; tables you maintain are yours |
| Redis | None; build sets, sorted sets, or use RediSearch | You keep them consistent |
| Elasticsearch | Everything is indexed by default | Near real-time |
Fix / how to use it: prefer a query table or an explicit index structure you control, and write it in the same transaction or batch where the store allows.
Two papers behind the families
The families trace back to two papers published before the name existed.
| Bigtable (OSDI 2006) | Dynamo (SOSP 2007) | |
|---|---|---|
| Model | "A Bigtable is a sparse, distributed, persistent multi-dimensional sorted map." | Key-value; values are opaque blobs |
| Goal | Large structured data with strong per-row consistency | "an 'always writeable' data store (i.e., a data store that is highly available for writes)" |
| Consistency | "every read or write of data under a single row key is atomic" | "an eventually consistent data store; that is all updates reach all replicas eventually" |
| Partitioning | Rows sorted by key, split into tablets | Consistent hashing with virtual nodes |
| Conflicts | Avoided: one tablet server per range | Allowed: vector clocks, reconciled by the application |
| Descendants | HBase, Hypertable, Accumulo, Cassandra's data model | Riak, Voldemort, Cassandra's distribution layer; DynamoDB is a managed service inspired by it, not the same system |
Bigtable lineage Bigtable -> HBase, Hypertable, Accumulo -> data model of Cassandra
Dynamo lineage Dynamo -> Riak, Voldemort, Dynomite -> distribution of Cassandra
Cassandra Dynamo's ring + gossip + quorum + Bigtable's data model + LSM storageCassandra's own documentation calls its ring a "Dynamo-style hash ring" and exposes Consistency Levels; the details live in Cassandra & ScyllaDB and the ring in Consistent Hashing. The storage side (LSM trees, SSTables) is in Storage Engines.
The families, one by one
Key-value Must-know
In plain words: a giant dictionary: give a key, get a value, fast.
Common misunderstanding: "key-value means only strings." Redis values can be hashes, lists, sets, sorted sets and streams; DynamoDB items are maps of typed attributes.
Definition: a store whose only primary access path is the key. The value is opaque (Memcached) or a typed structure (Redis, DynamoDB). Lookups are O(1) by key; anything else is a scan or a structure you build.
1 SET session:abc {...} EX 1800 -> stored with a 30-minute TTL
2 GET session:abc -> value, one round trip
3 GET session:xyz -> nil (missing or expired)
4 KEYS session:* -> full scan: never in production, use SCANReal scenario: sessions, rate limiters, leaderboards (sorted set), feature flags, shopping carts, idempotency keys, distributed locks (see Distributed Locking), job queues.
| Product | Notes |
|---|---|
| Redis | In memory with optional persistence (RDB snapshots, AOF); data structures; Redis Cluster uses 16384 hash slots; deep dive Redis |
| Memcached | Pure cache, multi-threaded, LRU eviction, no persistence, no structures |
| DynamoDB | Managed, partitioned by hash of the partition key, optional sort key, single-digit-millisecond reads |
| Riak KV | Dynamo-style ring, vector clocks or CRDTs for conflicts, tunable N, R, W |
| etcd, Consul | Small strongly consistent key-value stores for configuration, not data volume |
Fix / how to use it: pick keys that encode the access path (order:1001, customer:42:orders), set TTLs on cache keys, never scan.
// Writing an order aggregate to Redis with hand-built indexes: see the
// redis-orders snippet below. Key design is the schema.// Package main stores one order aggregate in Redis: a hash for the order,
// a list of its line items, and two index structures for the queries the
// application needs. Redis has no secondary indexes, so every index is code.
// Set REDIS_ADDR (for example localhost:6379) to run it; otherwise it exits.
package main
import (
"context"
"fmt"
"os"
"strconv"
"time"
"github.com/redis/go-redis/v9"
)
// Order is the aggregate the application reads as one unit.
type Order struct {
ID int64
CustomerID int64
TotalCents int64
CreatedAt time.Time
Lines []string
}
// Save writes the order and its indexes in one MULTI/EXEC transaction, so a
// reader never sees the hash without its index entries on a single node.
func Save(ctx context.Context, rdb *redis.Client, o Order) error {
id := strconv.FormatInt(o.ID, 10)
cust := strconv.FormatInt(o.CustomerID, 10)
_, err := rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HSet(ctx, "order:"+id, map[string]any{
"customer_id": o.CustomerID,
"total_cents": o.TotalCents,
"created_at": o.CreatedAt.Unix(),
})
for _, line := range o.Lines {
p.RPush(ctx, "order:"+id+":lines", line)
}
// Index 1: orders of one customer, newest first by score.
p.ZAdd(ctx, "customer:"+cust+":orders", redis.Z{Score: float64(o.CreatedAt.Unix()), Member: id})
// Index 2: revenue per customer, a running sorted-set score.
p.ZIncrBy(ctx, "revenue:by_customer", float64(o.TotalCents), cust)
return nil
})
return err
}
// RecentOrders answers "last N orders of a customer" with one ZREVRANGE.
func RecentOrders(ctx context.Context, rdb *redis.Client, customerID int64, n int64) ([]string, error) {
key := "customer:" + strconv.FormatInt(customerID, 10) + ":orders"
return rdb.ZRevRange(ctx, key, 0, n-1).Result()
}
func main() {
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
fmt.Println("REDIS_ADDR not set; skipping")
return
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr})
defer rdb.Close()
o := Order{ID: 1001, CustomerID: 42, TotalCents: 5700, CreatedAt: time.Now(), Lines: []string{"sku-1:2", "sku-9:1"}}
if err := Save(ctx, rdb, o); err != nil {
fmt.Println("save:", err)
os.Exit(1)
}
ids, err := RecentOrders(ctx, rdb, 42, 10)
if err != nil {
fmt.Println("recent:", err)
os.Exit(1)
}
fmt.Println("recent orders of customer 42:", ids)
}Document Must-know
In plain words: a folder of JSON files you can search inside.
Common misunderstanding: "document stores have no relations, so you embed everything." You embed what is read together and bounded; unbounded arrays (a user's lifetime orders) belong in another collection.
Definition: values are self-describing documents (JSON or BSON) with nested fields and arrays, addressable by _id and queryable by their fields through secondary indexes. MongoDB's data-modelling guide says "embedding data allows you to avoid complex joins across multiple collections, while improving performance and reducing your deployment's workload."
1 db.orders.insertOne({_id: 1001, customerId: 42, lines: [...]})
2 db.orders.find({customerId: 42}).sort({createdAt: -1}).limit(20) -> uses index
3 db.orders.updateOne({_id: 1001}, {$inc: {"lines.0.qty": 1}}) -> atomic on one document
4 16 MiB document limit: an ever-growing embedded array eventually failsReal scenario: product catalogues with varying attributes, content management, user profiles, event payloads from many app versions, mobile back ends (Firestore with offline sync).
| Product | Notes |
|---|---|
| MongoDB | BSON, rich query language and aggregation pipeline, multi-document transactions, replica sets and sharding; MongoDB in Depth |
| Couchbase | JSON, memory-first, N1QL (SQL for JSON), multi-document ACID transactions |
| CouchDB | JSON over HTTP, MVCC with _rev, multi-master replication with conflict revisions |
| Firestore | Managed, hierarchical collections and documents, strongly consistent reads, real-time listeners |
PostgreSQL jsonb | A document column inside a relational table, with GIN indexes |
Fix / how to use it: embed the bounded and co-read, reference the rest; index the filters you query; model the 16 MiB ceiling and growth.
-- the same idea inside PostgreSQL: a jsonb document with a GIN index
CREATE TABLE order_docs (id bigint PRIMARY KEY, doc jsonb NOT NULL);
CREATE INDEX order_docs_doc_gin ON order_docs USING gin (doc jsonb_path_ops);
SELECT doc FROM order_docs WHERE doc @> '{"customerId": 42}';Wide-column Must-know
In plain words: a table where each row can have a different set of columns, spread over many machines by a key, and sorted inside each partition.
Common misunderstanding: "wide-column means columnar like ClickHouse." It does not: wide-column stores keep rows together by partition; columnar analytics engines store each column together (see OLTP vs OLAP & Columnar Storage).
Definition: the Bigtable model: a sparse sorted map from (row key, column family:column, timestamp) to value. In Cassandra's CQL form: a partition key picks the node set, clustering columns sort rows inside the partition, and queries must name the partition key.
1 CREATE TABLE orders_by_customer (customer_id bigint, created_at timestamp,
2 order_id bigint, total_cents bigint,
3 PRIMARY KEY ((customer_id), created_at, order_id)) WITH CLUSTERING ORDER BY (created_at DESC);
4 SELECT * FROM orders_by_customer WHERE customer_id = 42 LIMIT 20; -> one partition, sorted
5 SELECT * FROM orders_by_customer WHERE total_cents > 1000; -> rejected (needs ALLOW FILTERING)Real scenario: messaging history per conversation, time-ordered event logs per device, IoT readings, user activity feeds, large write-heavy workloads across data centres.
| Product | Notes |
|---|---|
| Cassandra | Dynamo distribution plus Bigtable model, CQL, tunable consistency, multi-datacentre; Cassandra & ScyllaDB |
| ScyllaDB | Cassandra-compatible, C++, shard-per-core architecture |
| HBase | Bigtable clone on HDFS, strong per-row consistency, row-key ranges |
| Bigtable | Google's managed service, HBase-compatible API |
| Amazon Keyspaces, Astra DB | Managed Cassandra-compatible services |
Fix / how to use it: one table per query, partition key chosen for even spread (avoid hot partitions), bounded partition size, time-bucket keys for time series.
Graph Important
In plain words: a database whose main object is the relationship, not the row.
Common misunderstanding: "a graph database is for anything with relationships." Foreign keys are relationships too; a graph store pays off when queries walk many hops (friends of friends of friends).
Definition: a property graph: nodes with labels and properties, typed directed edges with properties; the engine follows edges without joins (index-free adjacency in Neo4j). Queried with Cypher (Neo4j), Gremlin (Neptune, Cosmos DB) or SPARQL (RDF stores).
1 MATCH (a:User {id: 42})-[:FOLLOWS*1..3]->(b:User) RETURN DISTINCT b -> hops 1 to 3
2 the SQL equivalent is a recursive CTE; cost grows with each join level
3 graph traversal cost grows with the part of the graph you actually touchReal scenario: recommendations, fraud rings, access-control graphs, knowledge graphs, network topology; deep dive Graph Databases.
| Product | Notes |
|---|---|
| Neo4j | Property graph, Cypher, ACID, clustering |
| Amazon Neptune | Managed; Gremlin, openCypher and SPARQL |
| ArangoDB | Multi-model: documents, graphs, key-value in one engine; AQL |
| PostgreSQL | Recursive CTEs, or the Apache AGE extension for openCypher |
Fix / how to use it: start with recursive CTEs in PostgreSQL for shallow graphs; move to a graph store when path queries dominate.
Time-series Important
In plain words: a table of measurements stamped with a time, optimised for "last hour", "per minute", "over the month".
Common misunderstanding: "a time-series database is just a table with a timestamp." The engine adds time partitioning, compression, downsampling, retention and fast range aggregates that a plain table does not.
Definition: an append-mostly store organised by time, with tags (indexed dimensions such as host) and fields (values).
1 INSERT 1,000,000 points/min -> append-only, batched
2 SELECT avg(cpu) ... GROUP BY time_bucket('5 minutes', ts) -> range aggregate
3 retention policy drops chunks older than 90 days -> cheap: drop a partitionReal scenario: infrastructure metrics, IoT sensors, financial ticks, application events.
| Product | Notes |
|---|---|
| InfluxDB | Purpose-built, line protocol, retention policies |
| TimescaleDB | PostgreSQL extension: hypertables, continuous aggregates, compression |
| ClickHouse | Columnar OLAP engine, excellent for event and metric analytics |
| Prometheus | Pull-based metrics store for monitoring (see Observability) |
Fix / how to use it: use partitions by time in PostgreSQL first (Partitioning & Sharding in PostgreSQL, Billion-Row Tables), then TimescaleDB, then a dedicated engine.
Search engine Important
In plain words: the index at the back of a book, extended with scoring.
Common misunderstanding: "Elasticsearch can be my main database." It is a derived index: no multi-document transactions, near real-time visibility, and rebuild from a source of truth is the safety net.
Definition: an inverted index maps terms to documents; scoring (BM25) ranks results; analyzers tokenise text. Elasticsearch's documentation says a stored document is "fully searchable in near real-time --within 1 second".
1 index doc 7 {title: "red running shoes"} -> in the transaction log
2 search "running" immediately -> may miss doc 7
3 refresh (default every 1 second) -> doc 7 visibleReal scenario: product search with facets, log search, autocomplete, "did you mean"; deep dive Full-Text Search and the system view Search Systems.
| Product | Notes |
|---|---|
| Elasticsearch | Lucene-based, REST/JSON, shards and replicas; licence changes since 2021 |
| OpenSearch | AWS-led fork of Elasticsearch 7.10 under Apache 2.0 |
PostgreSQL FTS, pg_trgm | tsvector, GIN indexes; trigram similarity for typos |
| Meilisearch, Typesense | Smaller search engines focused on developer experience |
Fix / how to use it: keep the system of record elsewhere and feed the index through CDC or an outbox.
Vector store Good to know
In plain words: a store for "things like this one", where "like" is distance between lists of numbers (embeddings).
Common misunderstanding: "a vector database replaces keyword search." Hybrid search (text plus vectors) usually wins; vectors capture meaning, keywords capture exact terms and identifiers.
Definition: an approximate nearest-neighbour (ANN) index (HNSW graphs, IVF lists) over embedding vectors, trading exact recall for speed. Deep dive: Vector Search & pgvector.
1 embed("waterproof hiking boots") -> [0.12, -0.80, ...]
2 ANN search top 10 by cosine distance -> approximate
3 filter by price and stock -> metadata filter (cost depends on product)Real scenario: semantic search, retrieval-augmented generation (RAG), recommendations, deduplication of images.
| Product | Notes |
|---|---|
| pgvector | PostgreSQL extension; HNSW and IVFFlat; transactions and joins with the rest of your data |
| Milvus | Open-source distributed vector database |
| Pinecone | Fully managed vector database |
| Qdrant, Weaviate | Other open-source vector stores |
| Elasticsearch, OpenSearch, MongoDB Atlas, Redis | Vector fields added to existing engines |
Fix / how to use it: start with pgvector if you already run PostgreSQL and have under a few million vectors.
Object store Good to know
In plain words: a bottomless folder for files, addressed by name.
Common misunderstanding: "an object store is a file system." There are no directories or atomic renames in the S3 model, and listing is an API call, not a cheap local operation (see Object Storage & File Systems).
Definition: flat namespace of buckets and objects (blob plus metadata) accessed over HTTP; durable and cheap; no queries on content.
1 PUT /exports/2026-11/orders.parquet -> object stored
2 GET /exports/2026-11/orders.parquet -> bytes
3 LIST prefix exports/2026-11/ -> keys only, no content queryReal scenario: images, uploads, backups and WAL archives (Backup, PITR & Disaster Recovery), data lake files, export bundles.
| Product | Notes |
|---|---|
| Amazon S3 | The reference API; strong read-after-write consistency |
| Google Cloud Storage, Azure Blob Storage | Equivalent managed services |
| MinIO, Ceph | S3-compatible self-managed |
Fix / how to use it: store a reference (key and checksum) in the database, never the blob.
Per-product behaviour
The diagram shows the same order stored four ways. The next tables put the products side by side. Behaviour changes between versions; the cells state the documented model, so verify the details in each product's current documentation.
Consistency and transactions
| Product | Single-item / row atomicity | Multi-item transactions | Reads |
|---|---|---|---|
| PostgreSQL | Yes | Full ACID, up to Serializable | Strong on the primary; replicas lag |
| Redis | Each command is atomic | MULTI/EXEC, Lua scripts; no rollback; cluster limited to one slot | Strong on primary; async replicas |
| Memcached | Per operation | None | Not a store of record |
| DynamoDB | Yes; conditional writes | TransactWriteItems/TransactGetItems, up to 100 actions | Eventually consistent by default; strongly consistent optional; GSI eventually consistent |
| Riak KV | Per key | None | Eventual; siblings resolved by application or CRDT |
| MongoDB | Single document always atomic | Multi-document ACID (replica sets since 4.0, sharded since 4.2); docs recommend embedding to avoid needing it | Read concern local, majority, linearizable |
| Couchbase | Single document | Multi-document ACID transactions | Tunable durability |
| CouchDB | Single document with _rev MVCC | None | Eventually consistent replication, conflicts kept |
| Firestore | Single document | Transactions and batched writes | Strongly consistent |
| Cassandra, ScyllaDB | Row-level, last-write-wins by timestamp | Lightweight transactions (Paxos) for compare-and-set; logged batches are not isolated | Per-query level ONE, QUORUM, LOCAL_QUORUM, ALL |
| HBase, Bigtable | Single row | None across rows | Strong within one cluster (Bigtable replication across clusters is eventual) |
| Neo4j | Yes | Full ACID | Causal consistency across a cluster |
| Neptune | Yes | ACID on the primary | Read replicas are eventually consistent |
| InfluxDB | Per point write | None | Eventual across replicas in clustered editions |
| TimescaleDB | Yes | Full PostgreSQL ACID | As PostgreSQL |
| ClickHouse | Per insert block | No general transactions | Replicas converge via replication log |
| Elasticsearch, OpenSearch | Per document (versioned) | None | Near real-time; realtime GET by id |
| pgvector | Yes | Full PostgreSQL ACID | As PostgreSQL |
| Pinecone, Milvus | Per upsert | None | Eventual freshness; Milvus offers consistency levels |
| Cosmos DB | Yes | Transactions inside one logical partition | Strong, Bounded staleness, Session, Consistent prefix, Eventual |
Query capabilities
| Product | Query language | Joins | Aggregation | Ad-hoc filters |
|---|---|---|---|---|
| PostgreSQL, MySQL | SQL | Yes | Yes | Yes, with indexes |
| Redis | Commands, plus RediSearch module | No | Limited (ZCOUNT, scripts) | Only on structures you built |
| DynamoDB | PutItem/GetItem/Query/Scan, PartiQL | No | No (use Streams, Athena, export) | Query by key; filter after read |
| MongoDB | MQL, aggregation pipeline | $lookup (limited) | Strong | Yes, with indexes |
| Cassandra | CQL | No | Basic | Only on partition and clustering keys |
| Neo4j | Cypher | Relationship traversal | Yes | Yes |
| InfluxDB, TimescaleDB | InfluxQL/Flux, SQL | TimescaleDB: yes | Time-bucketed | Tags and time |
| ClickHouse | SQL dialect | Yes (costly) | Excellent | Yes |
| Elasticsearch | Query DSL, ES|QL | Limited | Aggregations | Yes, text and filters |
| Pinecone, Milvus | Vector search API | No | No | Metadata filters |
Scaling model
| Product | Sharding | Replication | Rebalancing |
|---|---|---|---|
| PostgreSQL, MySQL | Not built in (Citus, Vitess, manual) | Streaming/logical replicas | Manual |
| Redis | Redis Cluster (16384 slots); otherwise client-side | Primary/replica, async | CLUSTER slot migration |
| Memcached | Client-side consistent hashing | None | Client decides |
| DynamoDB | Built in, automatic partitions | Three AZs, transparent | Automatic |
| MongoDB | Built in (sharded cluster, shard key) | Replica sets, elections | Balancer moves chunks |
| Cassandra, ScyllaDB | Built in (token ring, vnodes) | Replication factor per keyspace | Streaming on node add |
| HBase, Bigtable | Built in (regions/tablets by row-key range) | HDFS or managed | Automatic splits |
| Neo4j | Hard; read replicas, composite databases and fabric | Raft-based cluster | Manual |
| Elasticsearch | Index shards | Replica shards | Automatic reallocation |
| Pinecone | Managed | Managed | Managed |
CAP positioning
CAP says that when a network partition happens a replicated store must choose between consistency (C) and availability (A); PACELC adds the latency-versus-consistency trade when there is no partition. The labels below are tendencies of the default configuration, not guarantees: nearly every product can be moved along the line with settings. For definitions and the proof sketch read CAP & PACELC, Consistency models and Eventual Consistency in Database Systems.
| Product | Leans | Why (default behaviour) |
|---|---|---|
Dynamo-style: Riak, Cassandra (ONE/QUORUM), DynamoDB default reads | AP | Writes accepted on a minority partition; conflicts resolved later |
Cassandra at ALL or QUORUM both sides | CP-ish | Unavailable when the quorum cannot be reached |
MongoDB (w: majority, primary election) | CP | A partition without a majority cannot accept writes |
| HBase, Bigtable (single cluster) | CP | One server owns each row range |
| Redis (Sentinel/Cluster) | Neither cleanly | Async replication can lose acknowledged writes after failover |
| Neo4j cluster (Raft) | CP | Writes need a quorum of core members |
| Elasticsearch | Leans A for search | Replicas may serve stale reads; split-brain avoided by master election |
| Cosmos DB | Selectable | Five levels move you along the line per request |
| etcd, Consul, Spanner, CockroachDB | CP | Consensus (Raft, Paxos) on the write path; see Distributed SQL, Consensus & 2PC |
Mechanics
How a key finds its node
| Technique | Used by | Resharding cost | Range scans |
|---|---|---|---|
| Hash of partition key, token ring (consistent hashing, vnodes) | Cassandra, ScyllaDB, DynamoDB, Riak | Low: only neighbours move | Only inside a partition |
| Fixed hash slots (16384) | Redis Cluster | Move slots between nodes | Only inside a slot or via hash tags |
| Key ranges (tablets, regions, chunks) | Bigtable, HBase, MongoDB ranged shard key | Split and move ranges | Natural |
| Hashed shard key | MongoDB hashed | Chunk moves | Not for ranges |
1 token = hash(partition_key) -> position on the ring
2 coordinator finds replicas for token -> RF = 3 nodes
3 write sent to 3, acknowledged by CL nodes -> QUORUM = 2
4 read asks CL nodes, returns newest by timestamp, repairs stale replicasQuorums, in one line
With N replicas, a read of R and a write of W, the read overlaps the latest successful write when R + W > N (for example N=3, R=2, W=2). It does not give linearizability on its own (sloppy quorums, clock skew and concurrent writes still apply).
Hot partitions
A key with too much traffic (a celebrity user, today's date as a partition key, a counter) overloads one partition while others idle. Fixes: add a suffix to spread the key (counter:7:shard3), bucket time (day + hash), cache the hot item, or batch writes.
Verbatim errors you will see
| Product | Error or signal | Meaning |
|---|---|---|
| DynamoDB | ProvisionedThroughputExceededException | Partition or table throughput exceeded; back off with jitter |
| DynamoDB | ConditionalCheckFailedException | A conditional write lost the race (your optimistic lock) |
| DynamoDB | TransactionCanceledException | A transaction conflict or condition failed |
| MongoDB | E11000 duplicate key error | Unique index violated |
| MongoDB | TransientTransactionError label | Retry the whole transaction |
| MongoDB | WriteConflict | Two writers changed the same document in a transaction |
| Cassandra | UnavailableException | Not enough replicas alive for the requested level |
| Cassandra | ReadTimeoutException, WriteTimeoutException | Replicas did not answer in time |
| Redis | CROSSSLOT Keys in request don't hash to the same slot | A multi-key command across slots in Cluster |
| Redis | MOVED, ASK | The slot lives on another node; follow the redirect |
| Redis | WRONGTYPE Operation against a key holding the wrong kind of value | Treated a hash as a string |
| Redis | OOM command not allowed when used memory > 'maxmemory' | Memory limit reached with no eviction policy |
| Elasticsearch | HTTP 429 es_rejected_execution_exception | Thread pool queue full; slow down |
| Elasticsearch | HTTP 409 version_conflict_engine_exception | Optimistic concurrency conflict |
Solving the classic problems
When relational still wins Must-know
In plain words: if your data is related and your questions keep changing, a relational database is still the safest default.
Common misunderstanding: "relational does not scale." One PostgreSQL primary with replicas and partitioning serves most products; see Storage & Data Scaling: The Scale Ladder.
Definition: Fowler writes "I'm confident to say that if you starting a new strategic enterprise application you should no longer be assuming that your persistence should be relational", and then "The relational option might be the right one": the claim is that relational should be a decision, not a default.
1 need: orders joined to customers, filtered by 5 changing fields
2 relational: one query, add an index if slow
3 document/key-value: each new filter needs an index or a rewrite of keys
4 finance report asks for last-quarter revenue by region and product
5 relational: GROUP BY; others: pipeline job or exportReal scenario: billing, inventory, bookings, permissions, back-office reports, anything with money.
| Need | Relational | Typical NoSQL |
|---|---|---|
| Joins across entities | Native | Application code or $lookup |
Constraints (UNIQUE, FOREIGN KEY, CHECK) | Declared in schema | Application code (unique indexes in MongoDB, conditional writes in DynamoDB) |
| Ad-hoc queries | Add WHERE, maybe an index | Often impossible without a new index or table |
| Multi-row transactions | Standard | Limited, costly or absent |
| Mature tooling and skills | Decades | Varies |
Fix / how to use it: put the consistency-critical core in PostgreSQL and borrow NoSQL features inside it first.
-- PostgreSQL absorbs several NoSQL jobs in one engine
CREATE EXTENSION IF NOT EXISTS pg_trgm; -- fuzzy text
CREATE EXTENSION IF NOT EXISTS vector; -- pgvector
CREATE TABLE products (id bigint PRIMARY KEY, name text, attrs jsonb, embedding vector(3));
CREATE INDEX ON products USING gin (attrs jsonb_path_ops);
CREATE INDEX ON products USING gin (name gin_trgm_ops);
SELECT id FROM products WHERE attrs @> '{"color":"red"}' ORDER BY embedding <-> '[1,0,0]' LIMIT 5;Polyglot persistence and its cost Must-know
In plain words: use more than one kind of database, each for what it does best, and pay for the glue.
Common misunderstanding: "polyglot means picking the best store for each feature." Each new store adds backups, monitoring, upgrades, access control, a failure mode and a skill set. Fowler: "Each data storage mechanism introduces a new interface to be learned."
Definition: Fowler's PolyglotPersistence: "increasingly we'll be first asking how we want to manipulate the data and only then figuring out what technology is the best bet for it."
1 user places an order
2 write order to PostgreSQL (system of record) -> committed
3 write order to Elasticsearch for search -> network call, can fail
4 write to Redis cache -> network call, can fail
5 crash after step 2: search and cache never see the order -> divergenceReal scenario: an e-commerce platform with PostgreSQL (orders), Redis (carts, sessions), Elasticsearch (catalogue search), S3 (images), ClickHouse (analytics).
| Cost | What it means | Mitigation |
|---|---|---|
| Dual writes | No transaction across stores | Outbox pattern, CDC |
| Operations | One more thing to patch, back up, monitor | Managed service for non-core stores |
| Consistency | Derived stores lag | Define freshness per read path |
| Skills | Each store has its own failure modes | Limit the number of families |
| Security | One more access surface | Central secrets and audit |
Fix / how to use it: one system of record; every other store is derived and rebuildable. Use the transactional outbox (Messaging: Outbox) or change data capture (CDC).
// A Go function that names the stores a workload needs; more than one family
// means a sync plan. Full code in the family-chooser snippet.// Package main turns the "requirement -> family" decision table into code.
// Stdlib only. Run it from the go/ directory with: go run ./family-chooser
package main
import (
"fmt"
"sort"
)
// Requirement is one thing the workload needs from its store.
type Requirement string
const (
ByKeyLowLatency Requirement = "lookup by key in under a millisecond"
NestedAggregate Requirement = "read a nested aggregate in one fetch"
WriteHeavyScale Requirement = "very high write rate across many nodes"
RelationshipWalk Requirement = "walk relationships several hops deep"
TimestampedPoints Requirement = "append timestamped points and query ranges"
TextRelevance Requirement = "rank documents by text relevance"
Similarity Requirement = "nearest neighbours of an embedding"
AdHocJoins Requirement = "ad-hoc joins and multi-row transactions"
)
// Candidate is a family plus example products. Relational is the default
// answer, not a fallback: it wins when nothing else is demanded.
type Candidate struct {
Family string
Products []string
}
var table = map[Requirement]Candidate{
ByKeyLowLatency: {"key-value", []string{"Redis", "Memcached", "DynamoDB"}},
NestedAggregate: {"document", []string{"MongoDB", "Couchbase", "Firestore"}},
WriteHeavyScale: {"wide-column", []string{"Cassandra", "ScyllaDB", "Bigtable"}},
RelationshipWalk: {"graph", []string{"Neo4j", "Neptune"}},
TimestampedPoints: {"time-series", []string{"InfluxDB", "TimescaleDB", "ClickHouse"}},
TextRelevance: {"search engine", []string{"Elasticsearch", "OpenSearch"}},
Similarity: {"vector", []string{"pgvector", "Milvus", "Pinecone"}},
AdHocJoins: {"relational", []string{"PostgreSQL", "MySQL"}},
}
// Choose returns the distinct families a workload needs. More than one entry
// means polyglot persistence, and with it the cost of keeping stores in sync.
func Choose(reqs ...Requirement) []Candidate {
seen := map[string]Candidate{}
for _, r := range reqs {
if c, ok := table[r]; ok {
seen[c.Family] = c
}
}
out := make([]Candidate, 0, len(seen))
for _, c := range seen {
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Family < out[j].Family })
return out
}
func main() {
shop := Choose(AdHocJoins, ByKeyLowLatency, TextRelevance)
for _, c := range shop {
fmt.Printf("%-14s %v\n", c.Family, c.Products)
}
if len(shop) > 1 {
fmt.Printf("%d stores: plan for sync, backups and failure modes of each\n", len(shop))
}
}Referential integrity without foreign keys
In plain words: there is no FOREIGN KEY, so something else must stop orders pointing at deleted customers.
Common misunderstanding: "orphans will not happen." They will, from retries, partial failures and deletes done by another service.
Definition: enforce integrity in application code, with unique indexes, conditional writes, background reconciliation, soft deletes and tombstones.
1 delete customer 42 -> customer document removed
2 order 1001 still holds customerId: 42 -> orphan
3 nightly job finds orders without customer -> report or repairReal scenario: a user deleted in the identity service while their documents live in another service's database.
| Store | Helper |
|---|---|
| MongoDB | Unique indexes, transactions, change streams |
| DynamoDB | ConditionExpression, transactions, TTL |
| Cassandra | IF NOT EXISTS (LWT) |
| Redis | Lua scripts, SETNX |
Fix / how to use it: keep the reference one-directional where possible and run a reconciliation job.
Choosing a family
Requirement to family
| Requirement | Family | Products | Reason | Watch out for |
|---|---|---|---|---|
| Joins, constraints, ad-hoc reports, money | Relational | PostgreSQL, MySQL | The engine does the work | Single-primary writes |
| Sub-millisecond lookups, sessions, counters | Key-value | Redis, Memcached | In memory, O(1) | Memory cost, durability settings |
| Serverless key access at any scale | Key-value (managed) | DynamoDB, Firestore | No servers, automatic partitions | Query limits, hot keys, cost model |
| Nested aggregate read in one fetch | Document | MongoDB, Couchbase | Embedding avoids joins | 16 MiB limit, duplication |
| Offline-first mobile sync | Document | Firestore, CouchDB/PouchDB | Built-in sync and conflict handling | Query limits |
| Very high write rate, multi-datacentre | Wide-column | Cassandra, ScyllaDB, Bigtable | Linear write scale, tunable consistency | Query-first modelling, tombstones |
| Multi-hop relationships | Graph | Neo4j, Neptune | Traversal without joins | Sharding, fewer experts |
| Metrics, sensors, ticks | Time-series | InfluxDB, TimescaleDB, ClickHouse | Time partitioning, compression | Cardinality explosion |
| Relevance-ranked text, facets | Search | Elasticsearch, OpenSearch | Inverted index, BM25 | Derived store, near real-time |
| Semantic similarity, RAG | Vector | pgvector, Milvus, Pinecone | ANN index | Recall tuning, hybrid search |
| Files and backups | Object store | S3, GCS, MinIO | Cheap, durable | No queries |
| Analytics over billions of rows | Columnar OLAP | ClickHouse, BigQuery, Snowflake | Column scans | Not for point updates |
Hosted vs self-managed
| Option | Examples | You get | You give up |
|---|---|---|---|
| Fully managed, proprietary | DynamoDB, Firestore, Cosmos DB, Bigtable | No servers, SLAs, automatic scaling | Portability, bill surprises, vendor limits |
| Managed open source | MongoDB Atlas, Amazon ElastiCache, Amazon MemoryDB, Elastic Cloud, Astra DB, Timescale Cloud, ClickHouse Cloud, Neo4j Aura, Aiven, Upstash | Open API, backups, upgrades | Some tuning, cost at scale |
| Self-managed | Cassandra, Redis, MongoDB Community, Elasticsearch on Kubernetes or VMs | Control, lower raw cost | On-call, upgrades, capacity, security |
| Embedded in PostgreSQL | jsonb, pgvector, TimescaleDB, FTS | One system to run | Ceiling at very large scale |
Migration paths
| From to | Approach | Steps | Risk |
|---|---|---|---|
| Add cache (any to Redis) | Cache-aside | Read-through in code; TTL; invalidate on write | Stale reads |
| Add search (Postgres to Elasticsearch) | Derived index via CDC or outbox | Initial bulk load, then stream changes | Lag, reindexing |
| Postgres to MongoDB | Strangler fig (Strangler Fig Migration) | Dual-read, backfill, switch writes by aggregate | Joins disappear; transactions change |
| MongoDB to Postgres | jsonb first, then columns | Load documents into jsonb, promote hot fields | Schema discovery |
| MySQL/Postgres to DynamoDB or Cassandra | Access-pattern inventory first | List queries, design keys, backfill, dual-write via outbox | Query rewrite, hot keys |
| Any to Cosmos DB | Choose API (NoSQL, MongoDB, Cassandra, Gremlin, Table) | Match existing client API | Request-unit costing |
Schema changes in relational databases follow Zero-Downtime Schema Migrations; the same expand-and-contract idea applies to documents with a schemaVersion.
Multi-model databases
In plain words: one engine that speaks several data models, so you run one system instead of three.
Common misunderstanding: "multi-model is the best of all worlds." Each model usually gets less depth than a specialist offers.
| Product | Models | Notes |
|---|---|---|
| ArangoDB | Document, graph, key-value | AQL query language; joins and traversals in one query |
| Azure Cosmos DB | Document (NoSQL API), MongoDB API, Cassandra API, Gremlin (graph), Table | Five consistency levels; request units; global distribution |
| PostgreSQL | Relational, jsonb documents, hstore key-value, ltree, PostGIS, pgvector, pg_trgm, FTS | Extensions give breadth; one transaction domain |
| Redis with modules | Key-value, JSON, search, time series | RedisJSON, RediSearch, RedisTimeSeries |
| SurrealDB, OrientDB | Document, graph, relational | Smaller ecosystems |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
One PostgreSQL covers orders, users, search (FTS), documents (jsonb) and vectors (pgvector). Add Redis only for sessions and cache when a measurement demands it. Example: a Laravel app on PostgreSQL with Cache::remember backed by Redis; the cache is disposable and rebuilt from the database.
Modular monolith / multiple databases
Each module owns its tables; a module may choose another store behind its interface. Example: the catalogue module indexes into Elasticsearch through an internal interface, the orders module stays on PostgreSQL. The boundary hides the store, so a family can be replaced without touching callers. Cross-module foreign keys are avoided so a module can move.
Microservices
Each service owns its data and picks the family that fits (Microservices Data Ownership). No distributed transaction spans stores, so cross-service work uses sagas and the outbox.
1 orders service commits order + outbox row in PostgreSQL
2 relay publishes OrderPlaced to the broker
3 search service consumes, updates Elasticsearch (idempotent upsert)
4 cart service consumes, deletes the cart key in Redis
5 analytics consumes, appends to ClickHouseDistributed data (replicas, caches, sharded stores, multi-region)
Replica lag, stale caches and eventual consistency now apply to every store. DynamoDB global tables and Cassandra multi-datacentre accept writes in several regions and resolve conflicts (last-writer-wins or application rules); Cosmos DB lets you pick a consistency level per request. A cache in front of a store is another copy to invalidate (Caching); use TTLs and write-through only where staleness is acceptable. For the full treatment see Eventual Consistency in Database Systems and Replication, Read Replicas & Failover.
Scaling path
| Scale | Typical design |
|---|---|
| 1x (a few hundred requests/s) | One PostgreSQL; Redis for sessions |
| 10x | Read replicas, cache-aside, Elasticsearch for search, partitioned tables |
| 100x | Shard or move the hot aggregate (Cassandra/DynamoDB for event logs, ClickHouse for analytics), keep PostgreSQL for the transactional core |
| Multi-region | Active-passive for relational; DynamoDB global tables, Cassandra multi-DC, or distributed SQL |
Go
Example
The program models one aggregate, "user with orders", in three shapes with only the standard library: two row sets that emulate a join, one marshalled struct, and two keys that must be read back separately.
// Package main models the same "user with orders" aggregate three ways.
// Stdlib only. Run it from the go/ directory with: go run ./three-models
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Order is the child entity. Its meaning is the same in every model;
// only the place where it is stored changes.
type Order struct {
ID int64 `json:"id"`
Total int64 `json:"total_cents"`
}
// ---------------------------------------------------------------------------
// Model 1: relational. Two tables linked by a foreign key, joined at read time.
// ---------------------------------------------------------------------------
type UserRow struct {
ID int64
Name string
Email string
}
type OrderRow struct {
ID int64
// Foreign key: the link between the two tables is data, resolved by a JOIN.
UserID int64
Total int64
}
// relationalRead mimics:
//
// SELECT u.*, o.* FROM users u JOIN orders o ON o.user_id = u.id WHERE u.id = $1
func relationalRead(users []UserRow, orders []OrderRow, userID int64) (UserRow, []Order, bool) {
var user UserRow
found := false
for _, u := range users {
if u.ID == userID {
user, found = u, true
break
}
}
if !found {
return UserRow{}, nil, false
}
var out []Order
for _, o := range orders {
if o.UserID == userID {
out = append(out, Order{ID: o.ID, Total: o.Total})
}
}
return user, out, true
}
// ---------------------------------------------------------------------------
// Model 2: document. One aggregate, orders embedded, read and written together.
// ---------------------------------------------------------------------------
type UserDocument struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Orders []Order `json:"orders"`
}
// ---------------------------------------------------------------------------
// Model 3: key-value. Opaque bytes under a key; the application owns the layout.
// ---------------------------------------------------------------------------
type KeyValue struct {
m map[string][]byte
}
func NewKeyValue() *KeyValue {
return &KeyValue{m: make(map[string][]byte)}
}
func (kv *KeyValue) Set(key string, value []byte) {
kv.m[key] = value
}
func (kv *KeyValue) Get(key string) ([]byte, bool) {
v, ok := kv.m[key]
return v, ok
}
// keyValueWrite splits the aggregate across two keys: the profile and the order list.
func keyValueWrite(kv *KeyValue, doc UserDocument) error {
id := strconv.FormatInt(doc.ID, 10)
profile, err := json.Marshal(map[string]any{"id": doc.ID, "name": doc.Name, "email": doc.Email})
if err != nil {
return err
}
orders, err := json.Marshal(doc.Orders)
if err != nil {
return err
}
kv.Set("user:"+id, profile)
kv.Set("user:"+id+":orders", orders)
return nil
}
// keyValueRead needs one Get per key, and the caller must know the key names.
func keyValueRead(kv *KeyValue, userID int64) (map[string]any, []Order, error) {
id := strconv.FormatInt(userID, 10)
raw, ok := kv.Get("user:" + id)
if !ok {
return nil, nil, fmt.Errorf("user %d: not found", userID)
}
var profile map[string]any
if err := json.Unmarshal(raw, &profile); err != nil {
return nil, nil, err
}
rawOrders, ok := kv.Get("user:" + id + ":orders")
if !ok {
return profile, nil, nil
}
var orders []Order
if err := json.Unmarshal(rawOrders, &orders); err != nil {
return nil, nil, err
}
return profile, orders, nil
}
func main() {
users := []UserRow{{ID: 42, Name: "Ada", Email: "ada@example.com"}}
orderRows := []OrderRow{{ID: 7, UserID: 42, Total: 1500}, {ID: 8, UserID: 42, Total: 4200}}
u, orders, ok := relationalRead(users, orderRows, 42)
fmt.Printf("relational: %s has %d orders (found=%v)\n", u.Name, len(orders), ok)
doc := UserDocument{
ID: 42,
Name: "Ada",
Email: "ada@example.com",
Orders: []Order{{ID: 7, Total: 1500}, {ID: 8, Total: 4200}},
}
b, err := json.Marshal(doc)
if err != nil {
panic(err)
}
fmt.Printf("document: %s\n", b)
kv := NewKeyValue()
if err := keyValueWrite(kv, doc); err != nil {
panic(err)
}
profile, kvOrders, err := keyValueRead(kv, 42)
if err != nil {
panic(err)
}
fmt.Printf("key-value: %v with %d orders, stored under 2 keys\n", profile["name"], len(kvOrders))
}The Go angle
The standard library has no common abstraction across these families: database/sql speaks SQL to a driver, and every NoSQL store has its own client (go-redis at github.com/redis/go-redis/v9, mongo-go-driver, the AWS SDK for DynamoDB, gocql for Cassandra). The encoding/json struct tags are the storage contract: renaming a field is a data migration with no ALTER TABLE. The model is a plain struct, so the choice of family shows up as the shape of the struct and the names of the keys.
Laravel
Example
Three models: User and Order (relational Eloquent), UserDocument (the aggregate in one JSON column with the AsArrayObject cast) and UserKeyValueStore (two keys through the Cache facade). A second file runs the lab questions against PostgreSQL and Redis.
<?php
// Three ways to store "user with orders" in a Laravel 13 application.
// Read it as a map of shapes, not as code to deploy: a real app picks one
// shape per aggregate. Braced namespaces let several classes share one file.
// The migration for the JSON-column variant, for reference:
//
// Schema::create('user_documents', function (Blueprint $table) {
// $table->id();
// $table->string('name');
// $table->string('email')->unique();
// $table->json('orders');
// $table->timestamps();
// });
namespace App\Models {
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
// Model 1: relational. Two tables, a foreign key, and a join when you read.
class User extends Model
{
public function orders(): HasMany
{
return $this->hasMany(Order::class);
}
}
class Order extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
// Model 2: document-style. The aggregate's orders live inside one JSON column,
// so the user and its orders are read and written as one row.
class UserDocument extends Model
{
protected $table = 'user_documents';
protected $fillable = ['name', 'email', 'orders'];
protected function casts(): array
{
// AsArrayObject lets you mutate offsets safely: $doc->orders[] = [...].
return [
'orders' => AsArrayObject::class,
];
}
public function addOrder(int $id, int $totalCents): void
{
$this->orders[] = ['id' => $id, 'total_cents' => $totalCents];
$this->save();
}
}
}
namespace App\Services {
use Illuminate\Support\Facades\Cache;
// Model 3: key-value. The store sees only strings under keys; the application
// invents the key layout and must read two keys to rebuild the aggregate.
final class UserKeyValueStore
{
public function __construct(private int $ttlSeconds = 3600) {}
public function profileKey(int $userId): string
{
return "user:{$userId}";
}
public function ordersKey(int $userId): string
{
return "user:{$userId}:orders";
}
/**
* @param array{id: int, name: string, email: string} $profile
* @param list<array{id: int, total_cents: int}> $orders
*/
public function save(int $userId, array $profile, array $orders): void
{
Cache::put($this->profileKey($userId), json_encode($profile, JSON_THROW_ON_ERROR), $this->ttlSeconds);
Cache::put($this->ordersKey($userId), json_encode($orders, JSON_THROW_ON_ERROR), $this->ttlSeconds);
}
/**
* @return array{profile: array<string, mixed>, orders: list<array<string, mixed>>}|null
*/
public function find(int $userId): ?array
{
$profile = Cache::get($this->profileKey($userId));
if ($profile === null) {
return null;
}
$orders = Cache::get($this->ordersKey($userId), '[]');
return [
'profile' => json_decode($profile, true, 512, JSON_THROW_ON_ERROR),
'orders' => json_decode($orders, true, 512, JSON_THROW_ON_ERROR),
];
}
}
}<?php
// The same "customer revenue and recent orders" questions asked of PostgreSQL
// and Redis from Laravel 13. MongoDB is not built in: it needs the official
// mongodb/laravel-mongodb package, whose models then use the same Eloquent API.
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
final class OrdersThreeStores
{
// Relational: one query, the join and the aggregation are the database's job.
public function revenuePerCustomerSql(int $days): array
{
return DB::table('orders as o')
->join('customers as c', 'c.id', '=', 'o.customer_id')
->where('o.created_at', '>=', now()->subDays($days))
->groupBy('c.id', 'c.name')
->orderByRaw('SUM(o.total_cents) DESC')
->limit(10)
->get(['c.id', 'c.name', DB::raw('SUM(o.total_cents) AS revenue_cents')])
->all();
}
// Key-value: the write path maintains the "index" the read path needs.
// MULTI/EXEC keeps the hash and both indexes consistent on one node.
public function saveOrderRedis(int $orderId, int $customerId, int $totalCents): void
{
Redis::transaction(function ($tx) use ($orderId, $customerId, $totalCents) {
$tx->hmset("order:{$orderId}", [
'customer_id' => $customerId,
'total_cents' => $totalCents,
'created_at' => time(),
]);
$tx->zadd("customer:{$customerId}:orders", time(), (string) $orderId);
$tx->zincrby('revenue:by_customer', $totalCents, (string) $customerId);
});
}
// Top customers by revenue: one ZREVRANGE, but only the all-time total.
// "Last 30 days" would need a time-bucketed key per day, built by the writer.
public function topCustomersRedis(int $n): array
{
return Redis::zrevrange('revenue:by_customer', 0, $n - 1, ['withscores' => true]);
}
}The Laravel angle
Eloquent makes the relational variant the default (hasMany, belongsTo, User::with('orders') against N+1; see ORM Pitfalls). The Eloquent mutators documentation describes AsArrayObject as the cast for a JSON attribute you modify in place, which gives a document variant that stays inside a relational database, so you keep transactions but need expression or GIN indexes to query inside it. Cache::put takes a TTL and Cache::get returns null when missing; use the Cache facade when the store is disposable and the Redis facade (Redis::transaction, zadd, zrevrange) when Redis is a real store. MongoDB is not a built-in Laravel driver: use the official mongodb/laravel-mongodb package.
In production systems
- Redis documents its data types as the building blocks of the store. Hashes, sorted sets and streams sit on the same level as strings; choosing one is a choice about access pattern. (Redis data types)
- MongoDB documents embedding as the way to avoid joins, and its transactions page notes that the document model "reduces the need for multi-document transactions". (Data Modeling, Transactions)
- Bigtable's row key is the primary access path. "Every read or write of data under a single row key is atomic", and data is kept in lexicographic row-key order. (Bigtable paper)
- DynamoDB transactions group up to 100 write actions in one all-or-nothing operation, and the Cosmos DB documentation describes five consistency levels. (DynamoDB transactions, Cosmos DB consistency)
Lab
Goal: model one domain (orders) in PostgreSQL, MongoDB and Redis, run the same questions, and see what each store makes easy or hard.
# docker-compose.yml
services:
pg:
image: postgres:17
environment: { POSTGRES_PASSWORD: lab }
ports: ["5432:5432"]
mongo:
image: mongo:8
ports: ["27017:27017"]
redis:
image: redis:7
ports: ["6379:6379"]Start with docker compose up -d. The questions: Q1 fetch order 1001 with its lines; Q2 last 3 orders of customer 42; Q3 revenue per customer; Q4 rename the customer; Q5 orders with a total over 3000.
1. PostgreSQL: three tables
-- docker compose exec pg psql -U postgres
CREATE TABLE customers (id bigint PRIMARY KEY, name text NOT NULL);
CREATE TABLE orders (id bigint PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers(id),
total_cents bigint NOT NULL, created_at timestamptz NOT NULL);
CREATE TABLE order_lines (order_id bigint REFERENCES orders(id), sku text, qty int, PRIMARY KEY (order_id, sku));
INSERT INTO customers VALUES (42, 'Ada'), (43, 'Linus');
INSERT INTO orders VALUES (1001, 42, 5700, now()), (1002, 42, 1200, now()), (1003, 43, 3500, now());
INSERT INTO order_lines VALUES (1001, 'sku-1', 2), (1001, 'sku-9', 1), (1002, 'sku-1', 1), (1003, 'sku-2', 4);
-- Q1
SELECT o.id, o.total_cents, l.sku, l.qty FROM orders o JOIN order_lines l ON l.order_id = o.id WHERE o.id = 1001;
-- Q2
SELECT id, total_cents FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 3;
-- Q3
SELECT c.name, SUM(o.total_cents) FROM orders o JOIN customers c ON c.id = o.customer_id GROUP BY c.name;
-- Q4: one row changes, every join sees it
UPDATE customers SET name = 'Ada L.' WHERE id = 42;
-- Q5
SELECT id FROM orders WHERE total_cents > 3000; -- any column, any time2. MongoDB: one document per order
// docker compose exec mongo mongosh
use lab
db.orders.insertMany([
{_id: 1001, customer: {id: 42, name: "Ada"}, total: 5700, createdAt: new Date(), lines: [{sku: "sku-1", qty: 2}, {sku: "sku-9", qty: 1}]},
{_id: 1002, customer: {id: 42, name: "Ada"}, total: 1200, createdAt: new Date(), lines: [{sku: "sku-1", qty: 1}]},
{_id: 1003, customer: {id: 43, name: "Linus"}, total: 3500, createdAt: new Date(), lines: [{sku: "sku-2", qty: 4}]}
])
db.orders.createIndex({"customer.id": 1, createdAt: -1})
// Q1: one read, no join
db.orders.findOne({_id: 1001})
// Q2
db.orders.find({"customer.id": 42}).sort({createdAt: -1}).limit(3)
// Q3: aggregation pipeline
db.orders.aggregate([{$group: {_id: "$customer.name", revenue: {$sum: "$total"}}}])
// Q4: the name is copied into every order; update them all
db.orders.updateMany({"customer.id": 42}, {$set: {"customer.name": "Ada L."}})
// Q5: any field, but an index makes it cheap
db.orders.find({total: {$gt: 3000}})3. Redis: keys and hand-made indexes
# docker compose exec redis redis-cli
HSET order:1001 customer_id 42 total_cents 5700
RPUSH order:1001:lines sku-1:2 sku-9:1
ZADD customer:42:orders 1763990000 1001
ZINCRBY revenue:by_customer 5700 42
# Q1: two reads (hash + list)
HGETALL order:1001
LRANGE order:1001:lines 0 -1
# Q2: sorted set is the index
ZREVRANGE customer:42:orders 0 2
# Q3: all-time total only, because the writer maintained it
ZREVRANGE revenue:by_customer 0 -1 WITHSCORES
# Q4: the name is not stored in the order, nothing to update
# Q5: not answerable without a scan; you would need another sorted set, written at order time4. Compare
| Question | PostgreSQL | MongoDB | Redis |
|---|---|---|---|
| Q1 order with lines | 1 join query | 1 findOne | 2 commands |
| Q2 last 3 orders | ORDER BY + index | find().sort() + compound index | ZREVRANGE on a structure you built |
| Q3 revenue per customer | GROUP BY | Aggregation pipeline | Only the totals the writer kept |
| Q4 rename customer | 1 row | updateMany across orders | Not stored in the order |
| Q5 any new filter | WHERE | Add an index | Write a new index at write time |
5. Failure experiment
Run docker compose stop redis, place an order in PostgreSQL, start Redis again, and look for the order in customer:42:orders. It is missing: this is the dual-write gap. The fix is an outbox or a rebuild job that reads PostgreSQL and rewrites the keys.
6. Clean up
docker compose down -vCommon misconceptions
| Belief | Reality |
|---|---|
| NoSQL means "no SQL" | Fowler records the "Not Only SQL" reading and reserves it for the polyglot ecosystem; several NoSQL stores have SQL-like languages (CQL, N1QL, PartiQL) |
| NoSQL has no schema | The schema lives in the reading code (schema-on-read); validators can enforce part of it |
| NoSQL is always faster | Fast for the access pattern it was built for; a scan in any store is slow |
| NoSQL cannot do transactions | MongoDB, Couchbase, DynamoDB, Firestore, Neo4j all offer ACID transactions within limits |
| NoSQL is always eventually consistent | Bigtable, HBase, Firestore, Neo4j and single-primary MongoDB default to strong reads |
| Relational does not scale | One tuned PostgreSQL with replicas and partitions covers most products |
| Document stores need no modelling | Embedding vs referencing is the central design decision |
| Redis is only a cache | It is a data-structure server and can be a primary store with persistence configured |
| A search engine can be the system of record | It is a derived, near real-time index |
| Polyglot persistence is free | Each store adds operations, sync logic and a new failure mode |
| DynamoDB is the Dynamo paper | DynamoDB is a managed service inspired by it, not the same system |
| Wide-column equals columnar | Wide-column keeps rows by partition; columnar stores keep columns together |
Cheat sheet
| Topic | Remember |
|---|---|
| Origin | 2009 San Francisco meetup; "Not Only SQL" is the ecosystem reading |
| Lineages | Bigtable (2006) leads to HBase and Cassandra's model; Dynamo (2007) leads to Riak and Cassandra's ring |
| Design rule | Access patterns first; keys encode queries |
| Aggregate | Unit of atomicity and distribution |
| Key-value | Redis, Memcached, DynamoDB, Riak; O(1) by key; build indexes yourself |
| Document | MongoDB, Couchbase, CouchDB, Firestore; embed what is co-read; 16 MiB limit |
| Wide-column | Cassandra, ScyllaDB, HBase, Bigtable; one table per query; mind hot partitions |
| Graph | Neo4j, Neptune; multi-hop traversals |
| Time-series | InfluxDB, TimescaleDB, ClickHouse; retention and downsampling |
| Search and vector | Elasticsearch, OpenSearch; pgvector, Milvus, Pinecone; derived stores |
| Consistency | Many products tunable (Cassandra levels, Cosmos DB five levels, MongoDB concerns, DynamoDB strong reads) |
| Relational wins | Joins, constraints, ad-hoc queries, multi-row transactions |
| Polyglot | One system of record; sync with outbox or CDC |
| Multi-model | ArangoDB, Cosmos DB, PostgreSQL with jsonb, pgvector, pg_trgm |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is "Not Only SQL" a better description of the ecosystem than of a single database? Must-know
Answer
Answer: Fowler argues that calling one store "not only SQL" would make SQL Server NoSQL; the phrase fits the polyglot ecosystem where several kinds of store coexist.
2 — What is the difference between the Bigtable and Dynamo lineages? Good to know
Answer
Answer: Bigtable is a sorted map with strong per-row consistency (HBase, Cassandra's model); Dynamo is an always-writeable, eventually consistent key-value ring with vector clocks (Riak, Cassandra's distribution).
3 — What does "access-pattern-first" mean, and why does it hurt a later query? Must-know
Answer
Answer: You pick keys and structures from the list of queries; a new query that the keys do not serve needs a new index, table or backfill.
4 — Why is the aggregate also the transaction boundary in many NoSQL stores? Important
Answer
Answer: Single-document or single-row writes are atomic while cross-aggregate operations are not, so changes that must be atomic belong in one aggregate.
5 — Name three things relational databases give you that most NoSQL families do not. Must-know
Answer
Answer: Joins, declared constraints (foreign keys), ad-hoc queries, and multi-row ACID transactions.
6 — A DynamoDB read right after a write returns old data. Why, and what are your options? Important
Answer
Answer: Reads are eventually consistent by default; request a strongly consistent read on the base table (a GSI cannot be read strongly consistently).
7 — Why is a dual write to PostgreSQL and Elasticsearch dangerous? Must-know
Answer
Answer: No transaction spans both; a crash between writes leaves them different. Use an outbox or CDC with PostgreSQL as the system of record.
8 — How does a Cassandra table design differ from a relational one? Important
Answer
Answer: You design one table per query, with a partition key that picks the node set and clustering columns that sort within it; there are no joins.
9 — Which family fits "friends of friends who bought this", and what is the PostgreSQL alternative? Good to know
Answer
Answer: A graph store (Neo4j, Neptune); recursive CTEs or Apache AGE inside PostgreSQL for shallow traversals.
10 — Give two reasons to stay on PostgreSQL before adding a NoSQL store. Must-know
Answer
Answer: It already offers jsonb, full-text search, pg_trgm, pgvector and partitioning, and a second store adds sync, operations and failure modes.
Glossary
| Term | Meaning |
|---|---|
| NoSQL | Umbrella label for non-relational stores; coined at the June 2009 San Francisco meetup |
| Polyglot persistence | Using several store types, each for the data it fits best |
| Aggregate | A cluster of related objects stored, changed and distributed as one unit |
| Schema-on-read | Structure applied by the reader, not enforced at write time |
| Denormalisation | Storing a fact in more than one place to speed reads |
| Access pattern | A query shape the application needs, with frequency and latency target |
| Key-value store | Store with the key as primary access path |
| Document store | Store of JSON/BSON documents queryable by field |
| Wide-column store | Sparse sorted map partitioned by row or partition key |
| Partition key | The part of the key that decides which node holds the data |
| Clustering key | Columns that sort rows inside a partition (Cassandra) |
| Hot partition | A partition receiving disproportionate traffic |
| Consistent hashing | Mapping keys to nodes on a ring so few keys move when nodes change |
| Quorum | A majority of replicas; with R + W > N reads overlap the latest write |
| Tunable consistency | Choosing the consistency level per request (Cassandra, Cosmos DB) |
| Eventual consistency | Replicas converge if updates stop; reads may be stale meanwhile |
| Vector clock | Version vector used in Dynamo to detect concurrent updates |
| CRDT | Data type whose replicas merge without conflicts |
| LSM tree | Log-structured merge tree: memtable plus SSTables on disk |
| Secondary index | An extra access path on a non-key attribute |
| GSI / LSI | DynamoDB global and local secondary indexes |
| Inverted index | Map from terms to documents; basis of search engines |
| ANN | Approximate nearest neighbour search over vectors (HNSW, IVF) |
| Multi-model database | One engine offering several data models |
| Outbox pattern | Write the change and an event row in one transaction, relay later |
| CDC | Change data capture: stream a database's changes to other systems |
| Object store | Flat blob storage addressed by key (S3, GCS, MinIO) |
| System of record | The store that is the authority; others are derived |
References
- Martin Fowler, "NosqlDefinition", bliki, 9 January 2012 (meetup, Strozzi, "Not Only SQL", characteristics). martinfowler.com
- Martin Fowler, "PolyglotPersistence", bliki. martinfowler.com
- Fay Chang et al., "Bigtable: A Distributed Storage System for Structured Data", OSDI 2006. research.google and PDF
- Giuseppe DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007. PDF
- Redis documentation, "Redis data types". redis.io
- MongoDB documentation: Data Modeling, Transactions
- AWS documentation: NoSQL design for DynamoDB, DynamoDB transactions
- Microsoft documentation, Consistency levels in Azure Cosmos DB
- Apache Cassandra documentation, Dynamo
- Elastic documentation, Near real-time search
- Laravel 13 documentation: Eloquent mutators, Cache, Redis