Skip to content

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 forGo to
The families and their products on one screenEverything in one minute
Why NoSQL exists and where the word came fromWhy NoSQL exists, History
Aggregates, schema-on-read, denormalisation, access-pattern-firstData-model ideas
One block per family: key-value, document, wide-column, graph, time-series, search, vector, object storeThe families, one by one
Dynamo and Bigtable lineagesTwo papers behind the families
Consistency, transactions, queries, secondary indexes, scaling per productPer-product behaviour
CAP positioning per productCAP positioning
Sharding, quorums, hot partitions, error codesMechanics
When relational still wins; polyglot persistence and its costSolving the classic problems
Requirement to family table; hosted vs self-managed; migrationsChoosing a family
Multi-model databases (ArangoDB, Cosmos DB, Postgres)Multi-model
Monolith to distributed dataIn architecture
Model one domain in Postgres, MongoDB and RedisLab
Wrong beliefs, cheat sheet, glossaryMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The families. Every row is unpacked in the families section.

FamilyData modelNative questionScales byProducts
Key-valuekey 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
Documentkey 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-columnpartition 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
Graphnodes and edges with properties"walk the relationships from here"Mostly vertical; clustering for reads; sharding is hardNeo4j, Neptune, ArangoDB
Time-seriestimestamped points, tags and fields"aggregate this metric over a time range"Time partitioning (chunks, shards), columnar storageInfluxDB, TimescaleDB, ClickHouse
Searchinverted index over documents"rank documents by relevance to these terms"Index shards and replicasElasticsearch, OpenSearch
Vectorembeddings with an ANN index"nearest neighbours of this vector"Index shards, or one Postgres nodepgvector, Milvus, Pinecone
Object storeblob by key plus metadata"give me this file"Provider-managedS3, GCS, MinIO
Relational (the baseline)tables, rows, foreign keys"any question over related data"Vertical, replicas, then partitioningPostgreSQL, MySQL, SQL Server

Consistency and transactions per family. Details in per-product behaviour.

Family and productDefault consistencyTransactions
Redis (single node)Strong on the primary; replicas are asynchronousMULTI/EXEC and Lua are atomic, with no rollback
MemcachedNone to speak of: a cache, with a CAS tokenSingle operation only
DynamoDBEventually consistent reads by default; strongly consistent read optionalTransactWriteItems, up to 100 actions
MongoDBSingle-document atomic; read and write concerns tune itMulti-document ACID on replica sets and sharded clusters
Cassandra, ScyllaDBTunable per query (ONE, QUORUM, ALL)Lightweight transactions (compare-and-set) only
HBase, BigtableStrong per row within one clusterSingle-row atomic only
Neo4jACIDFull ACID transactions
Elasticsearch, OpenSearchNear real-time (refresh about every second)None across documents
Cosmos DBFive selectable levels, from Strong to EventualWithin one logical partition

The three things to do.

SituationDo this
You do not yet know your queriesStay relational; add jsonb, pgvector or full-text search to PostgreSQL before adding a second database
One access pattern dominates and is measuredPick the family built for it, list every query first, and design keys around them
You added a second storeDecide 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 factAggregates shaped like what the application reads together
Any query, planned at run timeA short list of queries the layout makes cheap
Multi-row ACID transactionsPer-key or per-partition atomicity; more only at a cost
Scale up first, partition laterPartitioning is part of the data model from day one
Schema enforced on writeSchema enforced by the reading code (schema-on-read), or not at all
Joins and constraints in the engineJoins 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 arrive

Data-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 3

Real 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.

QuestionRelationalAggregate store
Read one order with linesJoin of 2 tablesOne document or one key group
Atomic across two ordersOne transactionNot guaranteed (MongoDB offers it, at a cost)
Report across all ordersOne GROUP BYAggregation 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.

sql
-- 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.

StoreWhat is enforced on write
PostgreSQL, MySQLColumn types, NOT NULL, constraints, foreign keys
MongoDBNothing by default; optional $jsonSchema validation
DynamoDBKey attributes and their types only
CassandraDeclared columns and types (CQL schema), no foreign keys
RedisValue 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.

go
// 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.

StrategyReadWriteStaleness
Embed (copy)One fetchFan-out on changeUntil fan-out completes
Reference (id)Two fetches or a join-like lookupOne writeNone
Snapshot at event timeOne fetchOnce, at creationBy 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").

StoreCost of a new query
PostgreSQL, MySQLAdd an index or write a join
MongoDBAdd an index, or reshape documents
DynamoDBAdd a GSI (eventually consistent, extra cost) or redesign keys
CassandraNew table (or SAI/materialised view with caveats), duplicate writes
RedisWrite-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).

ProductSecondary index supportConsistency of the index
PostgreSQLMany index types, transactionalSame as the table
MongoDBSingle, compound, multikey, text, geospatial, TTLUpdated with the write
DynamoDBLSI (same partition key, strongly consistent reads possible) and GSIGSI is eventually consistent
CassandraSecondary indexes, SAI, materialised views, or a query tableLocal to node; tables you maintain are yours
RedisNone; build sets, sorted sets, or use RediSearchYou keep them consistent
ElasticsearchEverything is indexed by defaultNear 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
GoalLarge 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"
PartitioningRows sorted by key, split into tabletsConsistent hashing with virtual nodes
ConflictsAvoided: one tablet server per rangeAllowed: vector clocks, reconciled by the application
DescendantsHBase, Hypertable, Accumulo, Cassandra's data modelRiak, 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 storage

Cassandra'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 ​

RelationalPostgreSQL, MySQL, SQL Servertables, joins, constraintsKey-valueRedis, MemcachedDynamoDB, Riaklineage: Dynamo 2007DocumentMongoDB, CouchbaseCouchDB, FirestoreJSON / BSON aggregatesWide-columnCassandra, ScyllaDBHBase, Bigtablelineage: Bigtable 2006GraphNeo4j, NeptuneArangoDBnodes and edgesMulti-modelArangoDB, Cosmos DBPostgres jsonb + extensionsseveral models, one engineObject storeS3, GCS, MinIOblobs by key, no queriesfiles, backups, exportsTime-seriesInfluxDB, TimescaleDBClickHousetimestamped pointsSearchElasticsearch, OpenSearchinverted index, relevancederived, not the sourceVectorpgvector, Milvus, PineconeANN: HNSW, IVFembeddings, similarityCache tierRedis, Memcachedin front of any storedisposable copy

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 SCAN

Real scenario: sessions, rate limiters, leaderboards (sorted set), feature flags, shopping carts, idempotency keys, distributed locks (see Distributed Locking), job queues.

ProductNotes
RedisIn memory with optional persistence (RDB snapshots, AOF); data structures; Redis Cluster uses 16384 hash slots; deep dive Redis
MemcachedPure cache, multi-threaded, LRU eviction, no persistence, no structures
DynamoDBManaged, partitioned by hash of the partition key, optional sort key, single-digit-millisecond reads
Riak KVDynamo-style ring, vector clocks or CRDTs for conflicts, tunable N, R, W
etcd, ConsulSmall 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.

go
// Writing an order aggregate to Redis with hand-built indexes: see the
// redis-orders snippet below. Key design is the schema.
go
// 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 fails

Real scenario: product catalogues with varying attributes, content management, user profiles, event payloads from many app versions, mobile back ends (Firestore with offline sync).

ProductNotes
MongoDBBSON, rich query language and aggregation pipeline, multi-document transactions, replica sets and sharding; MongoDB in Depth
CouchbaseJSON, memory-first, N1QL (SQL for JSON), multi-document ACID transactions
CouchDBJSON over HTTP, MVCC with _rev, multi-master replication with conflict revisions
FirestoreManaged, hierarchical collections and documents, strongly consistent reads, real-time listeners
PostgreSQL jsonbA 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.

sql
-- 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.

ProductNotes
CassandraDynamo distribution plus Bigtable model, CQL, tunable consistency, multi-datacentre; Cassandra & ScyllaDB
ScyllaDBCassandra-compatible, C++, shard-per-core architecture
HBaseBigtable clone on HDFS, strong per-row consistency, row-key ranges
BigtableGoogle's managed service, HBase-compatible API
Amazon Keyspaces, Astra DBManaged 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 touch

Real scenario: recommendations, fraud rings, access-control graphs, knowledge graphs, network topology; deep dive Graph Databases.

ProductNotes
Neo4jProperty graph, Cypher, ACID, clustering
Amazon NeptuneManaged; Gremlin, openCypher and SPARQL
ArangoDBMulti-model: documents, graphs, key-value in one engine; AQL
PostgreSQLRecursive 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 partition

Real scenario: infrastructure metrics, IoT sensors, financial ticks, application events.

ProductNotes
InfluxDBPurpose-built, line protocol, retention policies
TimescaleDBPostgreSQL extension: hypertables, continuous aggregates, compression
ClickHouseColumnar OLAP engine, excellent for event and metric analytics
PrometheusPull-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 visible

Real scenario: product search with facets, log search, autocomplete, "did you mean"; deep dive Full-Text Search and the system view Search Systems.

ProductNotes
ElasticsearchLucene-based, REST/JSON, shards and replicas; licence changes since 2021
OpenSearchAWS-led fork of Elasticsearch 7.10 under Apache 2.0
PostgreSQL FTS, pg_trgmtsvector, GIN indexes; trigram similarity for typos
Meilisearch, TypesenseSmaller 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.

ProductNotes
pgvectorPostgreSQL extension; HNSW and IVFFlat; transactions and joins with the rest of your data
MilvusOpen-source distributed vector database
PineconeFully managed vector database
Qdrant, WeaviateOther open-source vector stores
Elasticsearch, OpenSearch, MongoDB Atlas, RedisVector 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 query

Real scenario: images, uploads, backups and WAL archives (Backup, PITR & Disaster Recovery), data lake files, export bundles.

ProductNotes
Amazon S3The reference API; strong read-after-write consistency
Google Cloud Storage, Azure Blob StorageEquivalent managed services
MinIO, CephS3-compatible self-managed

Fix / how to use it: store a reference (key and checksum) in the database, never the blob.

Per-product behaviour ​

Relational3 tables, FK, JOINcustomersid, nameordersid, customer_id, totalcreated_atorder_linesorder_id, sku, qtyread = 3 tables joinedwrite = 1 transactionDocumentone aggregate, embedded{ _id: 1001,customer: {42, Ada},total: 5700,lines: [{sku-1, 2},{sku-9, 1} ] }index on customer.idread = 1 documentname copy can go staleKey-valueopaque values, your keysorder:1001 (hash)total, created_atorder:1001:lines (list)sku-1:2, sku-9:1customer:42:orderssorted set, hand-made indexrevenue:by_customersorted set, running totalread = key by keyindexes are write-time codeWide-columnpartition + clustering keyPARTITION KEYcustomer_id = 42CLUSTERING (sorted)created_at DESC, order_id2026-11-24, 1001, 57002026-11-20, 0998, 12002026-11-02, 0970, 800one partition = one node setread = range on a partitionone table per query shape

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 ​

ProductSingle-item / row atomicityMulti-item transactionsReads
PostgreSQLYesFull ACID, up to SerializableStrong on the primary; replicas lag
RedisEach command is atomicMULTI/EXEC, Lua scripts; no rollback; cluster limited to one slotStrong on primary; async replicas
MemcachedPer operationNoneNot a store of record
DynamoDBYes; conditional writesTransactWriteItems/TransactGetItems, up to 100 actionsEventually consistent by default; strongly consistent optional; GSI eventually consistent
Riak KVPer keyNoneEventual; siblings resolved by application or CRDT
MongoDBSingle document always atomicMulti-document ACID (replica sets since 4.0, sharded since 4.2); docs recommend embedding to avoid needing itRead concern local, majority, linearizable
CouchbaseSingle documentMulti-document ACID transactionsTunable durability
CouchDBSingle document with _rev MVCCNoneEventually consistent replication, conflicts kept
FirestoreSingle documentTransactions and batched writesStrongly consistent
Cassandra, ScyllaDBRow-level, last-write-wins by timestampLightweight transactions (Paxos) for compare-and-set; logged batches are not isolatedPer-query level ONE, QUORUM, LOCAL_QUORUM, ALL
HBase, BigtableSingle rowNone across rowsStrong within one cluster (Bigtable replication across clusters is eventual)
Neo4jYesFull ACIDCausal consistency across a cluster
NeptuneYesACID on the primaryRead replicas are eventually consistent
InfluxDBPer point writeNoneEventual across replicas in clustered editions
TimescaleDBYesFull PostgreSQL ACIDAs PostgreSQL
ClickHousePer insert blockNo general transactionsReplicas converge via replication log
Elasticsearch, OpenSearchPer document (versioned)NoneNear real-time; realtime GET by id
pgvectorYesFull PostgreSQL ACIDAs PostgreSQL
Pinecone, MilvusPer upsertNoneEventual freshness; Milvus offers consistency levels
Cosmos DBYesTransactions inside one logical partitionStrong, Bounded staleness, Session, Consistent prefix, Eventual

Query capabilities ​

ProductQuery languageJoinsAggregationAd-hoc filters
PostgreSQL, MySQLSQLYesYesYes, with indexes
RedisCommands, plus RediSearch moduleNoLimited (ZCOUNT, scripts)Only on structures you built
DynamoDBPutItem/GetItem/Query/Scan, PartiQLNoNo (use Streams, Athena, export)Query by key; filter after read
MongoDBMQL, aggregation pipeline$lookup (limited)StrongYes, with indexes
CassandraCQLNoBasicOnly on partition and clustering keys
Neo4jCypherRelationship traversalYesYes
InfluxDB, TimescaleDBInfluxQL/Flux, SQLTimescaleDB: yesTime-bucketedTags and time
ClickHouseSQL dialectYes (costly)ExcellentYes
ElasticsearchQuery DSL, ES|QLLimitedAggregationsYes, text and filters
Pinecone, MilvusVector search APINoNoMetadata filters

Scaling model ​

ProductShardingReplicationRebalancing
PostgreSQL, MySQLNot built in (Citus, Vitess, manual)Streaming/logical replicasManual
RedisRedis Cluster (16384 slots); otherwise client-sidePrimary/replica, asyncCLUSTER slot migration
MemcachedClient-side consistent hashingNoneClient decides
DynamoDBBuilt in, automatic partitionsThree AZs, transparentAutomatic
MongoDBBuilt in (sharded cluster, shard key)Replica sets, electionsBalancer moves chunks
Cassandra, ScyllaDBBuilt in (token ring, vnodes)Replication factor per keyspaceStreaming on node add
HBase, BigtableBuilt in (regions/tablets by row-key range)HDFS or managedAutomatic splits
Neo4jHard; read replicas, composite databases and fabricRaft-based clusterManual
ElasticsearchIndex shardsReplica shardsAutomatic reallocation
PineconeManagedManagedManaged

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.

ProductLeansWhy (default behaviour)
Dynamo-style: Riak, Cassandra (ONE/QUORUM), DynamoDB default readsAPWrites accepted on a minority partition; conflicts resolved later
Cassandra at ALL or QUORUM both sidesCP-ishUnavailable when the quorum cannot be reached
MongoDB (w: majority, primary election)CPA partition without a majority cannot accept writes
HBase, Bigtable (single cluster)CPOne server owns each row range
Redis (Sentinel/Cluster)Neither cleanlyAsync replication can lose acknowledged writes after failover
Neo4j cluster (Raft)CPWrites need a quorum of core members
ElasticsearchLeans A for searchReplicas may serve stale reads; split-brain avoided by master election
Cosmos DBSelectableFive levels move you along the line per request
etcd, Consul, Spanner, CockroachDBCPConsensus (Raft, Paxos) on the write path; see Distributed SQL, Consensus & 2PC

Mechanics ​

How a key finds its node ​

TechniqueUsed byResharding costRange scans
Hash of partition key, token ring (consistent hashing, vnodes)Cassandra, ScyllaDB, DynamoDB, RiakLow: only neighbours moveOnly inside a partition
Fixed hash slots (16384)Redis ClusterMove slots between nodesOnly inside a slot or via hash tags
Key ranges (tablets, regions, chunks)Bigtable, HBase, MongoDB ranged shard keySplit and move rangesNatural
Hashed shard keyMongoDB hashedChunk movesNot 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 replicas

Quorums, 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 ​

ProductError or signalMeaning
DynamoDBProvisionedThroughputExceededExceptionPartition or table throughput exceeded; back off with jitter
DynamoDBConditionalCheckFailedExceptionA conditional write lost the race (your optimistic lock)
DynamoDBTransactionCanceledExceptionA transaction conflict or condition failed
MongoDBE11000 duplicate key errorUnique index violated
MongoDBTransientTransactionError labelRetry the whole transaction
MongoDBWriteConflictTwo writers changed the same document in a transaction
CassandraUnavailableExceptionNot enough replicas alive for the requested level
CassandraReadTimeoutException, WriteTimeoutExceptionReplicas did not answer in time
RedisCROSSSLOT Keys in request don't hash to the same slotA multi-key command across slots in Cluster
RedisMOVED, ASKThe slot lives on another node; follow the redirect
RedisWRONGTYPE Operation against a key holding the wrong kind of valueTreated a hash as a string
RedisOOM command not allowed when used memory > 'maxmemory'Memory limit reached with no eviction policy
ElasticsearchHTTP 429 es_rejected_execution_exceptionThread pool queue full; slow down
ElasticsearchHTTP 409 version_conflict_engine_exceptionOptimistic 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 export

Real scenario: billing, inventory, bookings, permissions, back-office reports, anything with money.

NeedRelationalTypical NoSQL
Joins across entitiesNativeApplication code or $lookup
Constraints (UNIQUE, FOREIGN KEY, CHECK)Declared in schemaApplication code (unique indexes in MongoDB, conditional writes in DynamoDB)
Ad-hoc queriesAdd WHERE, maybe an indexOften impossible without a new index or table
Multi-row transactionsStandardLimited, costly or absent
Mature tooling and skillsDecadesVaries

Fix / how to use it: put the consistency-critical core in PostgreSQL and borrow NoSQL features inside it first.

sql
-- 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  -> divergence

Real scenario: an e-commerce platform with PostgreSQL (orders), Redis (carts, sessions), Elasticsearch (catalogue search), S3 (images), ClickHouse (analytics).

CostWhat it meansMitigation
Dual writesNo transaction across storesOutbox pattern, CDC
OperationsOne more thing to patch, back up, monitorManaged service for non-core stores
ConsistencyDerived stores lagDefine freshness per read path
SkillsEach store has its own failure modesLimit the number of families
SecurityOne more access surfaceCentral 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).

go
// 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.
go
// 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 repair

Real scenario: a user deleted in the identity service while their documents live in another service's database.

StoreHelper
MongoDBUnique indexes, transactions, change streams
DynamoDBConditionExpression, transactions, TTL
CassandraIF NOT EXISTS (LWT)
RedisLua scripts, SETNX

Fix / how to use it: keep the reference one-directional where possible and run a reconciliation job.

Choosing a family ​

Start: PostgreSQL / MySQLJoins, constraints, ad-hocqueries, multi-row transactions?Yes: stay relationaladd jsonb, pgvector, FTSSingle key, ms latency?Nested aggregate read?Writes beyond one node?Multi-hop relationships?Key-value: Redis, DynamoDBDocument: MongoDB, FirestoreWide-column: CassandraGraph: Neo4j, NeptuneTime-series: TimescaleSearch: ElasticsearchVector: pgvector, MilvusBlobs: object store (S3)Pick: name the access pattern, pick the family, then ask what it costs you(sync, backups, consistency, a second skill set). Every extra store is a decision.No: the query shape picks the familySpecialised needs: timestamps, text relevance, similarity, files (often a derived store beside the main one)

Requirement to family ​

RequirementFamilyProductsReasonWatch out for
Joins, constraints, ad-hoc reports, moneyRelationalPostgreSQL, MySQLThe engine does the workSingle-primary writes
Sub-millisecond lookups, sessions, countersKey-valueRedis, MemcachedIn memory, O(1)Memory cost, durability settings
Serverless key access at any scaleKey-value (managed)DynamoDB, FirestoreNo servers, automatic partitionsQuery limits, hot keys, cost model
Nested aggregate read in one fetchDocumentMongoDB, CouchbaseEmbedding avoids joins16 MiB limit, duplication
Offline-first mobile syncDocumentFirestore, CouchDB/PouchDBBuilt-in sync and conflict handlingQuery limits
Very high write rate, multi-datacentreWide-columnCassandra, ScyllaDB, BigtableLinear write scale, tunable consistencyQuery-first modelling, tombstones
Multi-hop relationshipsGraphNeo4j, NeptuneTraversal without joinsSharding, fewer experts
Metrics, sensors, ticksTime-seriesInfluxDB, TimescaleDB, ClickHouseTime partitioning, compressionCardinality explosion
Relevance-ranked text, facetsSearchElasticsearch, OpenSearchInverted index, BM25Derived store, near real-time
Semantic similarity, RAGVectorpgvector, Milvus, PineconeANN indexRecall tuning, hybrid search
Files and backupsObject storeS3, GCS, MinIOCheap, durableNo queries
Analytics over billions of rowsColumnar OLAPClickHouse, BigQuery, SnowflakeColumn scansNot for point updates

Hosted vs self-managed ​

OptionExamplesYou getYou give up
Fully managed, proprietaryDynamoDB, Firestore, Cosmos DB, BigtableNo servers, SLAs, automatic scalingPortability, bill surprises, vendor limits
Managed open sourceMongoDB Atlas, Amazon ElastiCache, Amazon MemoryDB, Elastic Cloud, Astra DB, Timescale Cloud, ClickHouse Cloud, Neo4j Aura, Aiven, UpstashOpen API, backups, upgradesSome tuning, cost at scale
Self-managedCassandra, Redis, MongoDB Community, Elasticsearch on Kubernetes or VMsControl, lower raw costOn-call, upgrades, capacity, security
Embedded in PostgreSQLjsonb, pgvector, TimescaleDB, FTSOne system to runCeiling at very large scale

Migration paths ​

From toApproachStepsRisk
Add cache (any to Redis)Cache-asideRead-through in code; TTL; invalidate on writeStale reads
Add search (Postgres to Elasticsearch)Derived index via CDC or outboxInitial bulk load, then stream changesLag, reindexing
Postgres to MongoDBStrangler fig (Strangler Fig Migration)Dual-read, backfill, switch writes by aggregateJoins disappear; transactions change
MongoDB to Postgresjsonb first, then columnsLoad documents into jsonb, promote hot fieldsSchema discovery
MySQL/Postgres to DynamoDB or CassandraAccess-pattern inventory firstList queries, design keys, backfill, dual-write via outboxQuery rewrite, hot keys
Any to Cosmos DBChoose API (NoSQL, MongoDB, Cassandra, Gremlin, Table)Match existing client APIRequest-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.

ProductModelsNotes
ArangoDBDocument, graph, key-valueAQL query language; joins and traversals in one query
Azure Cosmos DBDocument (NoSQL API), MongoDB API, Cassandra API, Gremlin (graph), TableFive consistency levels; request units; global distribution
PostgreSQLRelational, jsonb documents, hstore key-value, ltree, PostGIS, pgvector, pg_trgm, FTSExtensions give breadth; one transaction domain
Redis with modulesKey-value, JSON, search, time seriesRedisJSON, RediSearch, RedisTimeSeries
SurrealDB, OrientDBDocument, graph, relationalSmaller 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 ClickHouse

Distributed 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 ​

ScaleTypical design
1x (a few hundred requests/s)One PostgreSQL; Redis for sessions
10xRead replicas, cache-aside, Elasticsearch for search, partitioned tables
100xShard or move the hot aggregate (Cassandra/DynamoDB for event logs, ClickHouse for analytics), keep PostgreSQL for the transactional core
Multi-regionActive-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.

go
// 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
<?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
<?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.

yaml
# 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 ​

sql
-- 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 time

2. MongoDB: one document per order ​

javascript
// 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 time

4. Compare ​

QuestionPostgreSQLMongoDBRedis
Q1 order with lines1 join query1 findOne2 commands
Q2 last 3 ordersORDER BY + indexfind().sort() + compound indexZREVRANGE on a structure you built
Q3 revenue per customerGROUP BYAggregation pipelineOnly the totals the writer kept
Q4 rename customer1 rowupdateMany across ordersNot stored in the order
Q5 any new filterWHEREAdd an indexWrite 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 -v

Common misconceptions ​

BeliefReality
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 schemaThe schema lives in the reading code (schema-on-read); validators can enforce part of it
NoSQL is always fasterFast for the access pattern it was built for; a scan in any store is slow
NoSQL cannot do transactionsMongoDB, Couchbase, DynamoDB, Firestore, Neo4j all offer ACID transactions within limits
NoSQL is always eventually consistentBigtable, HBase, Firestore, Neo4j and single-primary MongoDB default to strong reads
Relational does not scaleOne tuned PostgreSQL with replicas and partitions covers most products
Document stores need no modellingEmbedding vs referencing is the central design decision
Redis is only a cacheIt is a data-structure server and can be a primary store with persistence configured
A search engine can be the system of recordIt is a derived, near real-time index
Polyglot persistence is freeEach store adds operations, sync logic and a new failure mode
DynamoDB is the Dynamo paperDynamoDB is a managed service inspired by it, not the same system
Wide-column equals columnarWide-column keeps rows by partition; columnar stores keep columns together

Cheat sheet ​

TopicRemember
Origin2009 San Francisco meetup; "Not Only SQL" is the ecosystem reading
LineagesBigtable (2006) leads to HBase and Cassandra's model; Dynamo (2007) leads to Riak and Cassandra's ring
Design ruleAccess patterns first; keys encode queries
AggregateUnit of atomicity and distribution
Key-valueRedis, Memcached, DynamoDB, Riak; O(1) by key; build indexes yourself
DocumentMongoDB, Couchbase, CouchDB, Firestore; embed what is co-read; 16 MiB limit
Wide-columnCassandra, ScyllaDB, HBase, Bigtable; one table per query; mind hot partitions
GraphNeo4j, Neptune; multi-hop traversals
Time-seriesInfluxDB, TimescaleDB, ClickHouse; retention and downsampling
Search and vectorElasticsearch, OpenSearch; pgvector, Milvus, Pinecone; derived stores
ConsistencyMany products tunable (Cassandra levels, Cosmos DB five levels, MongoDB concerns, DynamoDB strong reads)
Relational winsJoins, constraints, ad-hoc queries, multi-row transactions
PolyglotOne system of record; sync with outbox or CDC
Multi-modelArangoDB, Cosmos DB, PostgreSQL with jsonb, pgvector, pg_trgm

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
NoSQLUmbrella label for non-relational stores; coined at the June 2009 San Francisco meetup
Polyglot persistenceUsing several store types, each for the data it fits best
AggregateA cluster of related objects stored, changed and distributed as one unit
Schema-on-readStructure applied by the reader, not enforced at write time
DenormalisationStoring a fact in more than one place to speed reads
Access patternA query shape the application needs, with frequency and latency target
Key-value storeStore with the key as primary access path
Document storeStore of JSON/BSON documents queryable by field
Wide-column storeSparse sorted map partitioned by row or partition key
Partition keyThe part of the key that decides which node holds the data
Clustering keyColumns that sort rows inside a partition (Cassandra)
Hot partitionA partition receiving disproportionate traffic
Consistent hashingMapping keys to nodes on a ring so few keys move when nodes change
QuorumA majority of replicas; with R + W > N reads overlap the latest write
Tunable consistencyChoosing the consistency level per request (Cassandra, Cosmos DB)
Eventual consistencyReplicas converge if updates stop; reads may be stale meanwhile
Vector clockVersion vector used in Dynamo to detect concurrent updates
CRDTData type whose replicas merge without conflicts
LSM treeLog-structured merge tree: memtable plus SSTables on disk
Secondary indexAn extra access path on a non-key attribute
GSI / LSIDynamoDB global and local secondary indexes
Inverted indexMap from terms to documents; basis of search engines
ANNApproximate nearest neighbour search over vectors (HNSW, IVF)
Multi-model databaseOne engine offering several data models
Outbox patternWrite the change and an event row in one transaction, relay later
CDCChange data capture: stream a database's changes to other systems
Object storeFlat blob storage addressed by key (S3, GCS, MinIO)
System of recordThe store that is the authority; others are derived

References ​

Built by Morteza Negahi