Skip to content

Choosing a Database: Model the Queries, SQL vs NoSQL, Redis vs DynamoDB, Polyglot Persistence ​

"You shouldn't start designing your schema for DynamoDB until you know the questions it will need to answer." — Amazon Web Services, NoSQL design for DynamoDB, Amazon DynamoDB Developer Guide

Summary: Choosing a database is a decision about queries, not about brands. Write down every access pattern with its rate and shape, add the consistency and transaction needs, the scale ceiling, the latency SLO and what your team can operate, and the store mostly picks itself; most systems end up with PostgreSQL as the system of record plus one or two specialised stores fed by change data capture. Focus: Access patterns and query shapes (point lookup, range scan, full-text search, aggregation, graph traversal), read/write ratio, consistency and transaction requirements, schema volatility, scale ceiling, latency SLO, operational maturity, managed services, cost and lock-in; relational strengths and where they strain; MongoDB embedding vs referencing; DynamoDB and Cassandra single-table design; Redis as a primary store vs a cache; search, time-series, graph, vector, distributed SQL and serverless databases; polyglot persistence per bounded context; migrating between stores with dual write, backfill and shadow reads. Learning goal: For a new system, produce an access-pattern table, choose a store per bounded context with a one-line reason per choice, show the key or schema design that serves every pattern, and plan how to move to another store later without a big-bang cutover.

This chapter sits in the Consistency & Distributed Data group of the system-design path. It owns the decision: the inputs, the trade-off tables, the worked designs. The families themselves are mapped in NoSQL: Families & Data Models, and each engine has its deep dive: PostgreSQL, MongoDB, Redis, Cassandra & DynamoDB, Graph Databases, Full-Text Search, Vector Search & pgvector, Distributed SQL and OLTP vs OLAP. The data-level method (requirements to schema) is in Database System Design; partition keys and hot partitions at system level are in Sharding at System Level; the delivery mechanics of keeping stores in sync are in Transactional Outbox and Change Data Capture.

Page map ​

If you are looking forGo to
The whole decision in three tablesEverything in one minute
Why "SQL vs NoSQL" is the wrong first questionWhy it exists
Fowler's polyglot persistence, Dynamo, single-table designWhere it comes from
The inputs: access patterns, consistency, schema, scale, operationsAccess patterns, Consistency and transactions, Schema volatility, Scale ceiling and latency, Operations, cost, lock-in
The store families, one block eachRelational, Document, Key-value and wide-column, Redis, Search, Time series, Graph, Vector, Distributed SQL, Serverless
One store per bounded contextPolyglot persistence
Moving from one store to anotherMigration
Units, limits, knobs, error codesMechanics
CodeGo, Laravel
Classic mistakes and their fixesSolving the classic problems
Decision tables and three worked designsChoosing
Monolith to distributed systemIn architecture
Sizing and contract tests you can runLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Query shape decides the family.

Query shapeIn plain wordsTiny exampleNatural fitStrains on
Point lookupFetch one thing by its keyGET order 01J9AAny store; key-value is cheapest at scaleNothing, until one key is hot
Range scan on one keyThe latest N things of one ownerLast 20 orders of customer 42B-tree index (PostgreSQL), sort key (DynamoDB, Cassandra)Ranges across owners in key-value stores
Multi-entity transactionChange several things or noneOrder + stock + payment rowRelational, distributed SQLKey-value (limited transactions), document across documents
Ad-hoc query and joinA question nobody planned"Revenue per region for customers who returned twice"Relational, then a warehouseKey-value and wide-column (no joins)
Full-text searchFind by words, rank by relevance"red running shoes size 42"Elasticsearch, OpenSearch; PostgreSQL FTS for smallEvery OLTP store at scale
Aggregation over many rowsSum, count, percentile over timeRequests per minute per endpointClickHouse, TimescaleDB, InfluxDB (columnar or time-partitioned)Row stores on the primary
Graph traversalFollow relationships several hopsFriends of friends who like XNeo4j; recursive SQL for shallow casesJoins beyond 2 to 3 hops
SimilarityNearest neighbours of a vector"products like this photo"pgvector, then a dedicated vector databaseExact-match stores

Each family's promise and its price.

FamilyStrengthPriceProducts
RelationalJoins, constraints, foreign keys, transactions, ad-hoc SQL, mature toolingWrite scaling beyond one primary needs sharding workPostgreSQL, MySQL, SQL Server, Oracle, SQLite
DocumentAggregate stored and read whole; flexible fieldsCross-document invariants and joins are weakerMongoDB, Couchbase, Firestore
Key-value / wide-columnPredictable latency at any size, horizontal by designOnly the queries you designed for; no joinsDynamoDB, Cassandra, ScyllaDB, Bigtable
In-memory data structuresMicrosecond reads, counters, sets, streamsRAM cost; durability is a setting, not a givenRedis, Valkey, Memcached (cache only)
Search engineRelevance, facets, typeaheadDerived copy; eventual; not a system of recordElasticsearch, OpenSearch, Solr
Time series / columnarFast aggregations, compressionPoint updates and transactions are weakTimescaleDB, InfluxDB, ClickHouse
GraphDeep, variable-length traversalsNiche skills; poor at bulk aggregationNeo4j, Amazon Neptune
VectorApproximate nearest-neighbour searchRecall vs latency tuning, memorypgvector, Qdrant, Milvus, Pinecone
Distributed SQL (NewSQL)SQL and transactions across nodes and regionsLatency per write, cost, fewer extensionsSpanner, CockroachDB, YugabyteDB, Vitess (sharded MySQL)

The inputs you write down before naming a product.

InputQuestionExample answer
Access patternsWhich queries, how many per second, which shape?AP1 place order 200/s, AP2 get order 1,500/s, AP3 latest orders 400/s
Read/write ratioMostly reads, mostly writes, or both?10:1 for orders; 1:50 for telemetry
Consistency requirementCan a reader see a stale value? For how long?Order status: read-your-writes; recommendations: minutes
Transaction requirementWhich invariants span more than one entity?Stock never below zero while orders are placed
Schema volatilityHow often do fields change, and who controls them?Product attributes differ per category and change weekly
Scale ceilingSize and write rate in 3 years; how many regions?140 GB/year orders, one region
Latency SLOTarget p99 per patternAP2 p99 under 20 ms
Operational maturityWho runs it at 3 a.m.? Managed service available?Two backend devs, no DBA: managed only
Cost and lock-inPrice per request, per GB, per node; exit path?DynamoDB on-demand vs Aurora; export via S3
1. Write the access patternsQPS, read:write, point/range/search/agg/graph2. Invariants across entities?transactions, foreign keys, ad-hoc queries3. Fits one primary + replicas?storage, write QPS, regions, latency SLOyesno, fewknownyesnoKey-value / wide-columnDynamoDB, Cassandra: single tableDocument storeMongoDB: aggregate read wholePostgreSQL by defaultrelational + JSONB + pgvectorDistributed SQLSpanner, CockroachDB, YugabyteDB, VitessAdd per patternonly when the main store strainsfull-text, facets:Elasticsearch / OpenSearchtime series, analytics:TimescaleDB, InfluxDB, ClickHousedeep traversals:Neo4jsimilarity:pgvector, then a vector DBcache, sessions, counters:Redisfed by CDC / outboxnever by dual writesplus

The picture is the method of this chapter. Start from the access patterns, ask whether invariants span several entities, ask whether one primary with replicas can carry the load. Most answers land on PostgreSQL. Specialised stores are added per pattern on the right, fed by CDC or an outbox, and never by the application writing to two stores at once.

Why it exists ​

Every database is a set of trade-offs frozen into a storage layout. A B-tree on a single primary gives you any query you can write in SQL and strong transactions, but its write capacity is one machine. A hash-partitioned key-value store gives you any scale, but only the queries its keys were designed for. AWS states the difference in its own design guide: in an RDBMS "data can be queried flexibly, but queries are relatively expensive and don't scale well in high-traffic situations", while in DynamoDB "data can be queried efficiently in a limited number of ways, outside of which queries can be expensive and slow". The decision is which of those two sentences you can live with, per workload.

Flexible-query stores (relational)Designed-query stores (key-value, wide-column)
Normalise first, add indexes when questions appearKnow the questions first, shape keys to answer them
Joins, constraints and transactions in the engineDuplication and invariants in the application
New question = new SQL, maybe a new indexNew question = new index or a backfill of new items
Scales up, then out with replicas and sharding workScales out by adding partitions, automatically on managed services
Latency depends on the plan the optimiser picksLatency is flat because every query is a key lookup or a range on one key
Mistakes are cheap to fix laterMistakes in key design are expensive to fix later

The analogy we reuse on this page: the library, the vending machine and the filing cabinet. A library with a librarian (relational) can answer any question: "books by authors born in Tabriz, published after 1990, that are not on loan". It takes the librarian a while, and there is only one front desk. A vending machine (key-value) gives you exactly what is behind button B4 in a second, at any queue length if you add machines, but it cannot answer "what is the cheapest snack without nuts" unless someone stocked a row for that question. A filing cabinet with one folder per customer (document) gives you everything about one customer at once, but "every invoice above 1,000 across all folders" means opening every folder. Most companies need a library and some vending machines; the skill is putting each question in front of the right one.

Three common misunderstandings, up front ​

  1. "NoSQL scales and SQL does not." A single PostgreSQL primary with replicas carries a large share of real workloads, and distributed SQL scales SQL out. What key-value stores really give you is predictable performance at any size for the queries you designed, plus managed horizontal scaling. If you do not have those queries yet, you cannot design the keys.
  2. "Schemaless means no schema work." The schema moves from the database into every reader. PostgreSQL's own JSON docs recommend that even flexible documents "have a somewhat fixed structure". MongoDB's modelling docs are entirely about schema design.
  3. "One database for everything is simpler" or its opposite "use the best tool for every job". Fowler, who popularised polyglot persistence, warned in the same article that it "will come at a cost in complexity". Each extra store is another backup, upgrade, security review and on-call skill. Add one when a measured pattern needs it.

Where it comes from ​

Polyglot persistence, 2011. Martin Fowler's bliki entry PolyglotPersistence (16 November 2011) borrowed Neal Ford's 2006 term polyglot programming and argued that "if you starting a new strategic enterprise application you should no longer be assuming that your persistence should be relational", adding "The relational option might be the right one - but you should seriously look at other alternatives." He credits Scott Leberknight as the first to use the term, and the key move of this chapter comes from his text: "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". He also gave the boundary: "A component boundary is a good way to wrap a particular storage technology chosen for the way its data in manipulated."

Dynamo, 2007. Werner Vogels announced the Dynamo paper for SOSP 2007 on his blog, describing Dynamo as "internal technology developed at Amazon" for a highly available key-value store. Its descendants (Cassandra, Riak, and the managed DynamoDB service, which uses a different internal design) shaped the key-value family. The family-level history is in NoSQL: Families & Data Models.

Spanner, 2012. Google's OSDI 2012 paper showed SQL-style transactions across data centres, using a clock service (TrueTime) to order commits. CockroachDB and YugabyteDB followed with open-source designs; see Distributed SQL, Consensus & 2PC.

Single-table design, 2018. Rick Houlihan's AWS re:Invent 2018 session Amazon DynamoDB Deep Dive: Advanced Design Patterns for DynamoDB (DAT401) made "model the access patterns, then the keys" the standard DynamoDB method; the DynamoDB Developer Guide now says "You should maintain as few tables as possible in a DynamoDB application."

Postgres as the default, 2020s. JSONB, generated columns, partitioning, logical replication, extensions such as pgvector and TimescaleDB, and serverless managed offerings (Neon, Aurora Serverless) made "start with PostgreSQL" a common default; PostgreSQL 19 was released on 19 November 2026 per postgresql.org.

text
     Year   Idea                                        What changed in practice
1    2006   Polyglot programming (Ford, via Fowler)     "Right tool per problem" applied to languages
2    2007   Dynamo paper (Amazon, SOSP)                 Highly available key-value, eventual consistency
3    2011   Polyglot persistence (Fowler)               Choose storage per component by data manipulation
4    2012   Spanner (Google, OSDI)                      SQL transactions across regions
5    2018   Houlihan DAT401, single-table design        DynamoDB modelling starts from access patterns
6    2020s  PostgreSQL + JSONB + extensions             One engine covers documents, vectors, time series
7    2020s  Serverless databases                        Pay per request or per second; scale to zero

The concept catalogue ​

The first five blocks are the inputs to the decision. The next ten are the families you choose among. The last two are what happens when you pick more than one, and when you change your mind.

Access patterns and query shapes Must-know ​

In plain words: before you pick a database, write every question your system will ask of its data, how often, and what shape the answer has.

Common misunderstanding: "We will know the queries once the product exists." You know most of them already: they are the screens, API endpoints and jobs in the spec. The ones you do not know are the reason to keep a flexible-query store as the system of record.

Definition: an access pattern is a named, repeatable operation on the data with its key inputs, its result, its rate (peak QPS) and its consistency need. Its query shape is the class of work the engine must do: point lookup (one key), range scan (an ordered slice of one key or index), multi-key lookup, join, full-text search, aggregation over many rows, graph traversal, or similarity search. The read/write ratio says which side the design must optimise.

text
     Step   What you write down                                   Ordering context example
1    List   Screens, endpoints, jobs, reports                     checkout, order page, "my orders", warehouse feed, finance report
2    Name   One line per access pattern                          AP1 place order; AP2 get order; AP3 latest 20 orders; AP4 PLACED feed; AP5 revenue report
3    Shape  Point / range / join / search / aggregate / graph     AP2 point; AP3 range on customer; AP4 range on status; AP5 aggregate
4    Rate   Peak QPS and read:write                               AP1 200 w/s; AP2 1,500 r/s; AP3 400 r/s; AP4 20 r/s; AP5 1/hour
5    Need   Consistency and latency SLO per pattern               AP2 read-your-writes, p99 20 ms; AP5 an hour stale is fine
6    Route  Which store answers which pattern                     AP1-AP4 system of record; AP5 analytics store via CDC

Real scenario: a marketplace team lists 14 access patterns; 12 are point and range lookups by user or listing, one is search, one is a monthly finance report. The search and report patterns go to OpenSearch and a warehouse; the other 12 decide the primary store. A chat product finds that 95 % of reads are "last 50 messages of a channel": a range scan on one partition key, a natural fit for Cassandra or ScyllaDB (see Cassandra & ScyllaDB). An analytics feature turns out to be "group by any column the user picks": an ad-hoc aggregation, which rules out key-value stores for that feature.

What each family does with each shape:

ShapePostgreSQL / MySQLMongoDBDynamoDB / CassandraRedisElasticsearch / OpenSearchClickHouse
Point lookupPrimary-key index_id indexGetItem / partition keyGET, HGETALLBy _id, but near-real-timePossible, not its job
Range on one keyComposite B-tree indexCompound indexSort key / clustering keySorted set ZRANGESort on a fieldPrimary-key order
JoinNative$lookup, limitedNone; denormaliseNoneNone; denormaliseSupported, best with small dimension tables
Ad-hoc filterAny column, with or without indexAny field; index for speedScan (expensive) or new indexNoneAny indexed fieldAny column, fast
Full-textBuilt-in FTS, fine for small corporaAtlas SearchNoneRediSearch module (Redis Stack)Core featureLimited
AggregationGood on replicas, slow at huge scaleAggregation pipelineApplication sideCounters onlyAggregationsCore feature

Fix / how to use it: keep the access-pattern table in the repository next to the schema (the Go port in this chapter has it as a comment), review it in design reviews, and require that every new endpoint names its pattern before code is merged. The capacity arithmetic for each pattern is in Back-of-the-Envelope Capacity Estimation.

Consistency and transaction requirements Must-know ​

In plain words: decide which facts must never be wrong, even for a second, and which can be a little stale; and which changes must happen together or not at all.

Common misunderstanding: "NoSQL databases have no transactions, so they are unsafe." DynamoDB has TransactWriteItems, MongoDB has multi-document transactions, Redis has MULTI/EXEC. What differs is the scope and cost: DynamoDB groups "up to 100 write actions in a single all-or-nothing operation"; MongoDB says "a distributed transaction incurs a greater performance cost over single document writes" and must not replace schema design.

Definition: the consistency requirement is the staleness a reader may observe (strong, read-your-writes, bounded, eventual; see Consistency Models). The transaction requirement is the set of invariants that span more than one record (stock never negative while orders are placed, ledger balances sum to zero), and whether they need serializable isolation (Isolation Levels).

text
     T1 (checkout A)                              T2 (checkout B)              Store
1    read stock(sku-9) = 1
2                                                 read stock(sku-9) = 1
3    write order A; stock = 0
4                                                 write order B; stock = 0     key-value with no condition: oversold
5    -- relational: UPDATE stock SET qty = qty - 1 WHERE sku = 'sku-9' AND qty >= 1 in the same transaction as INSERT order
6    -- DynamoDB:  TransactWriteItems [Put order (attribute_not_exists), Update stock (ConditionExpression qty >= 1)]
7    -- either way: the invariant lives in one atomic step, never in application reads

Real scenario: payments and ledgers (double-entry must balance; see Payment Processing); inventory reservations in a flash sale; seat booking; unique usernames; a shopping cart (can be eventual); a "likes" counter (eventual, even approximate; see Sharded Counters).

What each product provides:

ProductSingle-record atomicityMulti-record transactionDefault read consistency
PostgreSQLYesAny number of rows and tables, up to SERIALIZABLEStrong on the primary; replicas lag
MySQL InnoDBYesAny rows, default REPEATABLE READStrong on the primary
MongoDBOne document, including nested arraysMulti-document; needs a replica set or sharded clusterPrimary reads by default
DynamoDBOne item, with condition expressionsUp to 100 items, 4 MB aggregate, one account and RegionEventually consistent unless ConsistentRead; GSIs are always eventual
CassandraOne partition (lightweight transactions with Paxos)Batches are not isolated transactionsTunable (QUORUM, ONE)
RedisOne command; MULTI/EXEC runs a block without interleavingNo rollback on command errorPrimary; replicas are asynchronous
Spanner / CockroachDBYesDistributed, serializableStrong by default

Fix / how to use it: list invariants by name; for each, pick the smallest atomic unit that contains it (one row, one document, one item, one transaction). If an invariant spans what would become two services, either keep the data together or accept a saga (Saga). The ACID/BASE framing is in ACID vs BASE; CAP and PACELC in CAP & PACELC.

Data shape and schema volatility Important ​

In plain words: how regular is your data, and how often does its structure change?

Common misunderstanding: "Our product attributes vary, so we need a document database." PostgreSQL JSONB stores varying attributes beside typed columns, with GIN indexes; MySQL has a JSON type. Variation alone is not a reason to switch engines. Variation plus "the whole aggregate is always read and written together plus no cross-aggregate invariants" is.

Definition: data shape is whether the data is tabular, a tree (aggregate with nested parts), a graph, a sequence (time series, log) or a vector. Schema volatility is how often the set of fields changes and who controls it (your team, product managers, customers, third parties).

text
     Week   Change                                            Relational + JSONB                   Document store
1    1      Laptop has ram_gb, cpu                            attributes jsonb                     fields in the document
2    3      Phones add sim_slots                              no migration, still jsonb            no migration
3    6      Filter by brand on every listing page             promote: generated column + index    add an index on attributes.brand
4    9      Finance needs price history with FK to suppliers  normal table, FK, transaction         separate collection, application checks

Real scenario: a product catalogue with 400 categories and different attributes per category; user-defined form builders; ingesting third-party webhooks whose payloads change without notice (store raw JSONB, extract what you need); event payloads with versioned schemas; IoT devices with firmware-specific fields.

What each product provides:

ProductFlexible partValidationIndexing flexible fields
PostgreSQLjsonb columnCHECK with jsonb_typeof, jsonb_path_exists; generated columnsGIN (jsonb_ops, jsonb_path_ops), expression indexes
MySQL 8JSON columnCHECK, JSON schema validation functionGenerated columns, multi-valued indexes
MongoDBWhole document$jsonSchema validator on the collectionAny field, wildcard indexes
DynamoDBAny non-key attributeNone in the databaseOnly key attributes and GSI keys
CassandraColumns per table, collections, UDTsCQL typesSecondary indexes with caveats

Fix / how to use it: typed columns for everything you filter, join, sum or constrain; JSONB for the long tail; promote a JSON field to a generated column the day a query needs it often. The SQL is in JSONB as a schema-less excuse. Schema design in depth is in Schema Design.

Scale ceiling, growth and latency SLO Must-know ​

In plain words: how big and how busy will this get, and how fast must each answer be?

Common misunderstanding: "We might become huge, so we need a database that scales infinitely from day one." Estimate it. 200,000 orders a day at 2 KB each is about 139 GB a year (the lab program prints this); that is a single PostgreSQL primary for years. Choosing for an imagined scale costs you joins and ad-hoc queries today.

Definition: the scale ceiling of a design is the load at which the chosen store needs a structural change (sharding, a new store, a new key design). For a single relational primary it is mostly write throughput and working-set memory; for a key-value store it is per-partition throughput and hot keys. The latency SLO is the target percentile per access pattern (SLAs, SLOs, SLIs, Latency Budgets & Tail Latency).

text
     Load      Ordering on PostgreSQL                        Ordering on DynamoDB
1    1x        one primary, one replica                       on-demand table, 2 partitions of throughput
2    10x       bigger instance, more replicas, PgBouncer      more partitions, automatic
3    100x      partitioning, then sharding (Citus) or         same design; hot-key review; per-partition
               distributed SQL; outbox to offload reads       limits 3,000 RCU / 1,000 WCU per partition
4    any       p99 depends on plans and locks                 p99 flat for designed queries

Real scenario: a ticketing on-sale peaks at 50x normal for 10 minutes (Ticketing case study); an IoT fleet writes 100,000 readings a second all day; a B2B SaaS app has 2,000 tenants and 300 GB, mostly reads; a global consumer app needs low-latency writes in three regions.

What each product provides:

ProductHow it scales writesPractical ceiling signal
PostgreSQL (single primary)Vertical; partitioning helps maintenance, not write fan-outWAL rate, CPU, lock contention, vacuum lag
PostgreSQL + CitusSharded by distribution columnCross-shard queries and transactions
MySQL + VitessSharded by keyspace ID; Vitess "distributes data across multiple MySQL instances through sharding"Cross-shard joins, resharding operations
DynamoDBAutomatic partitions; on-demand "can start small and scale to millions of requests per second"Hot partition keys, item size 400 KB
Cassandra / ScyllaDBAdd nodes; consistent-hash ringPartition size, tombstones, repair
Spanner / CockroachDB / YugabyteDBRanges split and move automaticallyCross-region write latency, cost

Fix / how to use it: estimate with numbers, not adjectives (Capacity Estimation); write down the 10x plan before you need it (Storage & Data Scaling); choose the store whose next step you can execute.

Operational maturity, managed services, cost and lock-in Important ​

In plain words: the best database on paper is the wrong one if nobody on the team can restore it from backup at 3 a.m.

Common misunderstanding: "A managed service removes operations." It removes patching, failover mechanics and hardware. It does not remove capacity planning, key design, query tuning, cost monitoring, backups you have tested, or the migration path when you leave.

Definition: operational maturity is the team's proven ability to deploy, monitor, back up, restore, upgrade and tune a store. A managed service (Amazon RDS/Aurora, DynamoDB, MongoDB Atlas, Google Cloud Spanner, Neon, PlanetScale, Elastic Cloud, ClickHouse Cloud) shifts part of that to a vendor. Lock-in is the cost of leaving: proprietary APIs, data export formats, and features with no equivalent elsewhere. Ecosystem is the drivers, ORMs, migration tools, observability and people you can hire.

text
     Question                                     PostgreSQL on RDS         DynamoDB                 MongoDB Atlas
1    Who handles failover?                        AWS (Multi-AZ)            AWS (built in)           Atlas (replica set)
2    Who designs indexes and keys?                You                       You (keys are the design) You
3    API portable to another vendor?              Yes, wire protocol         No, AWS-only API          MongoDB API, self-host possible
4    How do you leave?                            pg_dump / logical repl.    Export to S3, rewrite code mongodump / change streams
5    Laravel support                              First-party pgsql driver   Cache/session drivers only mongodb/laravel-mongodb package

Real scenario: a three-person startup picks DynamoDB because "it is serverless", then learns single-table design under deadline; a bank keeps Oracle for the core ledger because the DBA team and audits are built around it; a team runs self-hosted Cassandra without a repair schedule and loses data consistency silently; a team on Aurora pays more for I/O than for compute.

What each product provides:

ConcernPostgreSQLMySQLMongoDBDynamoDBCassandraRedis
Managed offeringsRDS, Aurora, Cloud SQL, AlloyDB, Azure, Neon, SupabaseRDS, Aurora, PlanetScaleAtlas, DocumentDB (compatible API)AWS onlyAstra DB, Amazon KeyspacesElastiCache, MemoryDB, Redis Cloud
Laravel 13 first-partyYesYes (and MariaDB)Via mongodb/laravel-mongodbCache and session store driversNoYes (Redis facade, cache, queue, session)
Go driverpgxgo-sql-driver/mysqlmongo-go-driveraws-sdk-go-v2gocqlgo-redis
Lock-inLowLowMediumHighLowLow (Valkey fork exists)

Laravel's database docs list the first-party set: "MariaDB 10.3+", "MySQL 5.7+", "PostgreSQL 10.0+", "SQLite 3.26.0+" and "SQL Server 2017+", and add that MongoDB is supported through the mongodb/laravel-mongodb package.

Fix / how to use it: price each candidate per access pattern (requests, storage, I/O, backups, egress); prefer the store with a managed offering your team can operate; keep data behind a repository port so leaving costs an adapter, not a rewrite (Repositories).

Relational: PostgreSQL by default Must-know ​

In plain words: tables, rows, SQL, and an engine that enforces your rules (unique, not null, foreign keys, checks) and runs any question you can express.

Common misunderstanding: "Joins are slow, so avoid relational databases at scale." Joins on indexed keys are cheap; what does not scale is an unbounded join over a huge table on the OLTP primary. That is a modelling and routing problem (send the report to a replica or warehouse), not a reason to lose constraints.

Definition: a relational database stores data as relations (tables) with declared types and constraints, and answers declarative SQL through a cost-based optimiser, with ACID transactions. Relational strengths: joins, constraints and foreign keys, multi-row transactions, ad-hoc queries, mature tooling (backups, PITR, migrations, ORMs, observability). Where it strains: write throughput beyond one primary, very large single tables without partitioning, global multi-region writes, and full-text or vector search at large scale.

text
     Request                             PostgreSQL work
1    POST /orders (AP1)                  BEGIN; INSERT orders; INSERT order_lines (unnest); INSERT outbox; COMMIT
2    GET /orders/01J9A (AP2)             index scan on orders_pkey, then order_lines_pkey
3    GET /customers/42/orders (AP3)      index scan on (customer_id, id DESC) LIMIT 20
4    warehouse feed (AP4)                partial index WHERE status = 'PLACED'
5    finance report (AP5)                runs on a replica or in ClickHouse via CDC, not on the primary

Real scenario: order management, billing, inventory, permissions, SaaS tenant data (Multi-Tenancy), anything with money; a catalogue with JSONB attributes; a job queue with FOR UPDATE SKIP LOCKED; a small search with tsvector; embeddings with pgvector.

What each product provides:

FeaturePostgreSQLMySQL InnoDBSQL ServerOracleSQLite
Foreign keys, CHECKYesYesYesYesYes (FK enforcement is a pragma)
JSONjsonb with GINJSON with generated-column indexesjson typeJSONJSON functions
Partial and expression indexesYesFunctional indexes; no partialFiltered indexesFunction-basedYes
Extensionspgvector, TimescaleDB, PostGIS, CitusPluginsLimitedOptionsLoadable extensions
Error on duplicate keySQLSTATE 23505 unique_violationError 10622627 / 2601ORA-00001SQLITE_CONSTRAINT

Fix / how to use it: start with PostgreSQL unless a requirement rules it out; model with normal forms, then denormalise with evidence. The schema for this chapter's Ordering context, with foreign keys, CHECKs, a partial index and a JSONB table with a generated column:

sql
-- PostgreSQL 16+ schema for the Ordering context (adapter: orders/postgres.go).
-- Relational strengths in one file: foreign keys, CHECK constraints,
-- a transaction across two tables, and indexes that serve AP2-AP4.

CREATE TABLE orders (
    id           text        PRIMARY KEY,                -- time-sortable ID (ULID-style)
    customer_id  text        NOT NULL,
    status       text        NOT NULL CHECK (status IN ('PLACED', 'PAID', 'SHIPPED')),
    total_cents  bigint      NOT NULL CHECK (total_cents >= 0),
    created_at   timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE order_lines (
    order_id     text   NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
    line_no      int    NOT NULL,
    sku          text   NOT NULL,
    quantity     int    NOT NULL CHECK (quantity > 0),
    price_cents  bigint NOT NULL CHECK (price_cents >= 0),
    PRIMARY KEY (order_id, line_no)
);

-- AP3: a customer's latest orders is a range scan on one index.
CREATE INDEX orders_customer_recent ON orders (customer_id, id DESC);
-- AP4: the warehouse feed reads only PLACED orders; a partial index stays small.
CREATE INDEX orders_placed ON orders (id DESC) WHERE status = 'PLACED';

-- JSONB with a contract, not instead of one: typed columns for what you
-- filter and join on, JSONB for the long tail of product attributes.
CREATE TABLE products (
    sku          text   PRIMARY KEY,
    name         text   NOT NULL,
    price_cents  bigint NOT NULL CHECK (price_cents >= 0),
    attributes   jsonb  NOT NULL DEFAULT '{}'::jsonb
                 CHECK (jsonb_typeof(attributes) = 'object'),
    -- a promoted, indexed attribute once a query needs it often
    brand        text GENERATED ALWAYS AS (attributes ->> 'brand') STORED
);
CREATE INDEX products_attributes ON products USING gin (attributes jsonb_path_ops);
CREATE INDEX products_brand ON products (brand);

-- Outbox: the change that other stores (search index, analytics, cache)
-- must see is written in the same transaction as the order.
CREATE TABLE outbox (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    aggregate_id text        NOT NULL,
    event_type   text        NOT NULL,
    payload      jsonb       NOT NULL,
    created_at   timestamptz NOT NULL DEFAULT now()
);

Document databases: MongoDB, embedding vs referencing Must-know ​

In plain words: store each aggregate (a product with its variants, an order with its lines) as one JSON-like document, so one read returns everything a screen needs.

Common misunderstanding: "In MongoDB you embed everything." MongoDB's own guidance says to reference when "The child side of the relationship has high cardinality", when "Your embedded data grows without bounds", or when "Your data is written at different times in a write-heavy workload".

Definition: a document database stores self-describing documents (BSON in MongoDB) in collections. Embedding puts related data inside the parent ("These denormalized data models allow applications to retrieve related data in a single database operation"); referencing stores an ID and resolves it with a second query or $lookup ("References result in normalized data models"). Atomicity is per document: "a write operation is atomic on the level of a single document". The aggregation pipeline is MongoDB's staged query language ($match, $group, $sort, $lookup). Hard limits: "The maximum BSON document size is 16 mebibytes" and no more than 100 levels of nesting.

text
     Decision          Product document                          Why
1    variants          embedded array (bounded, read with it)    "has-a", read together, updated together
2    attributes        embedded object (differs per type)        schema volatility, no cross-product invariant
3    reviews           separate collection, product_id ref        unbounded, written by other users at other times
4    price history     separate collection or time-series coll.  grows forever
5    stock             separate store with transactions           invariant across orders; usually relational

Real scenario: a product catalogue; content management (articles with blocks); user profiles with preferences; mobile app backends syncing whole objects; event payload archives. Less suited: ledgers, highly relational back-office data, reports across collections.

What each product provides:

CapabilityMongoDBPostgreSQL jsonbDynamoDB item
Max size16 MiB per document1 GB per field value (TOAST)400 KB per item
Nested queryDot notation, array operators->, ->>, @>, jsonpathProjection only; filter after read
Secondary index on nested fieldYesGIN or expression indexOnly via GSI key attributes
Joins$lookupFull SQLNone
Multi-record transactionReplica set or sharded clusterNativeTransactWriteItems

Fix / how to use it: embed what is bounded and read together, reference what is unbounded or independently written, and run the aggregation pipeline on a secondary or an analytics store for heavy reports. The Laravel MongoDB model and an aggregation-builder query are in Laravel; the full engine is in MongoDB in Depth.

Key-value and wide-column: DynamoDB, Cassandra, single-table design Must-know ​

In plain words: every read is "give me the item with this key" or "give me the items under this partition key, in sort-key order"; you shape the keys so each screen is one such request.

Common misunderstanding: "One table per entity, like in SQL." DynamoDB's guide says the opposite: "You should maintain as few tables as possible", and "A single table with inverted indexes can usually enable simple queries to create and retrieve the complex hierarchical data structures required by your application." Putting orders and customers in separate tables gives you SQL's layout without SQL's joins.

Definition: a key-value store addresses items by a partition key (hashed to choose a partition) and, in DynamoDB and Cassandra, an optional sort key (clustering key) that orders items inside the partition. A global secondary index (GSI) re-keys the same items by other attributes; DynamoDB GSIs "support eventually consistent reads" only. There are no joins: related data is either co-located under one partition key (an item collection) or duplicated. Single-table design stores several entity types in one table with generic key names (PK, SK, GSI1PK, GSI1SK) and typed key prefixes (CUST#, ORDER#). The DynamoDB guide lists the three properties to know first: data size, data shape ("a NoSQL database organizes data so that its shape in the database corresponds with what will be queried") and data velocity.

Table "ordering" (base table, strong reads allowed)GSI1 (eventually consistent)PKSKattributesGSI1PK / GSI1SKCUST#c-42PROFILEname, email, tier-CUST#c-42ORDER#01J9Astatus, total, Lines[ ]STATUS#PLACED#1CUST#c-42ORDER#01J9Bstatus, total, Lines[ ]STATUS#PAID#3CUST#c-7ORDER#01J8Zstatus, total, Lines[ ]STATUS#PLACED#0GSI1PKGSI1SKSTATUS#PLACED#001J8ZSTATUS#PLACED#101J9ASTATUS#PAID#301J9BAP2 get one orderGetItem PK=CUST#c-42SK=ORDER#01J9A, ConsistentReadone item, lines embeddedcost: ceil(size/4 KB) RCUAP3 latest orders of a customerQuery PK=CUST#c-42 ANDbegins_with(SK, "ORDER#")ScanIndexForward=false, Limit=20one partition, sorted by ULIDAP4 warehouse feed by statusQuery GSI1 GSI1PK=STATUS#PLACED#nfor n in 0..3, merge newest firstshard suffix avoids one hotpartition for a 3-value attribute
text
     Access pattern                     DynamoDB request                                      Items read
1    AP1 place order                    PutItem, ConditionExpression attribute_not_exists(PK) 1 write (+1 GSI write)
2    AP2 get order                      GetItem PK=CUST#c-42, SK=ORDER#01J9A, ConsistentRead  1
3    AP3 latest 20 orders               Query PK=CUST#c-42 AND begins_with(SK,"ORDER#"),      up to 20, one partition
                                        ScanIndexForward=false, Limit=20
4    AP4 PLACED feed                    Query GSI1 GSI1PK=STATUS#PLACED#0..3, merge           4 small queries
5    AP5 revenue report                 not served: stream to S3/ClickHouse via DynamoDB Streams

Real scenario: shopping carts and sessions at retail scale; user profiles and settings; device registries; leaderboards with a sort key; chat messages (Cassandra: partition per channel and time bucket); feature flags; idempotency-key tables (API Idempotency).

What each product provides:

ConceptDynamoDBCassandra / ScyllaDBBigtable
Partition keyPartition key (hash)Partition keyRow key prefix
Order inside partitionSort keyClustering columnsLexicographic row key
Secondary access pathGSI (eventual), LSI (same partition key, 5 per table)Materialized views, SAI indexes, or a second tableSecond table
Per-partition limit3,000 read units and 1,000 write units per secondPartition size guidance (keep partitions bounded)Row size, hotspotting
Conditional writeConditionExpressionLightweight transactions (IF NOT EXISTS)Check-and-mutate
Capacity modelOn-demand (default) or provisionedNodes you run or a managed serviceNodes

Fix / how to use it: write the access-pattern table, draw the item layout with key prefixes, make every pattern a GetItem or a Query, add a GSI per extra path, shard low-cardinality GSI keys, and never ship a Scan on a request path. The adapter is in Go; the engines are in Wide-Column & Key-Value at Scale; partition-key design at system level is in Sharding at System Level.

Redis: primary store or cache Must-know ​

In plain words: Redis keeps all data in memory, gives you data structures (hashes, sorted sets, streams) with very fast commands, and writes to disk only as often as you configure.

Common misunderstanding: "Redis is a cache, so it can never be a primary store", or the opposite, "Redis persists to disk, so it is as safe as PostgreSQL". Redis's own persistence page says to use both RDB and AOF "if you want a degree of data safety comparable to what PostgreSQL can provide you", and with the default appendfsync everysec "you may lose 1 second of data if there is a disaster".

Definition: as a cache, Redis holds copies of data whose source of truth is elsewhere, with TTLs and an eviction policy (maxmemory-policy, for example allkeys-lru; see Caching). As a Redis primary store, it holds the only copy, which needs persistence (RDB snapshots and/or AOF), replication, maxmemory-policy noeviction (so keys are never silently dropped; with noeviction "the server will return an error when you try to execute commands that cache new data"), and a business that accepts the remaining loss window. Memory cost is the deciding factor: every byte of data, plus per-key overhead, plus fork copy-on-write headroom during RDB/AOF rewrite, lives in RAM.

text
     t       Event                                              appendfsync everysec   RDB only (save every 5 min)
1    09:00:00  SET cart:{42} ...                               in AOF buffer           in memory
2    09:00:01  background fsync                                 on disk                 in memory
3    09:00:01.6 HINCRBY cart:{42} sku-9 1                       in AOF buffer           in memory
4    09:00:01.9 power loss
5    restart   replay AOF                                       lost: the last ~1 s     lost: up to 5 minutes

Real scenario: good as primary: carts, sessions, rate-limit counters (Rate Limiting), leaderboards, presence, short-lived OTP codes, feature flags with a fallback. Bad as the only store: balances, orders, payments, anything you must reproduce for audit.

Redis vs DynamoDB for key-value workloads:

QuestionRedis (ElastiCache, MemoryDB, self-hosted)DynamoDB
LatencySub-millisecond, in memorySingle-digit milliseconds
DurabilityConfigurable; AOF everysec loses up to ~1 s; MemoryDB adds a durable logDurable, replicated across AZs on write
Cost driverRAM for the whole datasetRequests and stored GB
Data structuresHashes, lists, sets, sorted sets, streams, HyperLogLogItems with attributes; lists and maps inside items
Size per valueUp to 512 MB per string400 KB per item
Query shapesKey, range on sorted set, scriptsKey, range on sort key, GSIs
Scale outRedis Cluster, 16,384 hash slotsAutomatic partitions
Best whenHot, small, short-lived, latency-criticalDurable records at any scale with known keys

Fix / how to use it: decide per keyspace whether Redis is a cache (eviction allowed) or a store (noeviction, AOF on, replicas, alerts on memory); never keep money only in Redis. Persistence and structures are in Redis in Depth.

In plain words: a search engine builds an inverted index (word → documents) so it can find and rank documents by text relevance and facets, fast.

Common misunderstanding: "Elasticsearch can be our main database." It is a derived index: near-real-time (a document becomes searchable after the next index refresh), with no multi-document transactions; you must be able to rebuild it from a source of truth.

Definition: Elasticsearch and OpenSearch (the open-source fork of Elasticsearch) are distributed search and analytics engines on Apache Lucene, offering full-text search with BM25 scoring, aggregations, typeahead and vector search. They sit beside the system of record and are fed by CDC or an outbox.

text
     Step   Event                                   Where
1    1      Product updated in MongoDB / order in PostgreSQL       source of truth
2    2      Change stream / Debezium emits change event           CDC
3    3      Indexer upserts document by product_id (idempotent)  OpenSearch
4    4      Search request reads the index after refresh          user sees new price
5    5      Index mapping changes: build new index, alias swap      zero downtime reindex

Real scenario: product search with facets; log search; typeahead; marketplace listing search; help-centre search. When the corpus is small (tens of thousands of rows) and ranking needs are simple, PostgreSQL full-text search avoids a second store; the comparison is in Full-Text Search, the system in Search Systems.

NeedPostgreSQL FTSElasticsearch / OpenSearchMongoDB Atlas Search
Rankingts_rank, basicBM25, function scores, learning to rankLucene-based
Facets and aggregationsSQL GROUP BYNative, fastFacets
FreshnessTransactionalNear-real-timeNear-real-time
Extra store to runNoYesManaged within Atlas

Fix / how to use it: one index per searchable aggregate, an idempotent indexer keyed by the source ID, and a full rebuild job you test.

Time series and columnar stores: TimescaleDB, InfluxDB, ClickHouse Important ​

In plain words: when most writes are appends of timestamped measurements and most reads are aggregates over time windows, use a store laid out for that.

Common misunderstanding: "Metrics are just rows; our OLTP PostgreSQL will do." It will, until a dashboard aggregates 500 million rows on the primary at 9 a.m. Time-partitioning (TimescaleDB hypertables) or columnar storage (ClickHouse) changes the cost by orders of magnitude.

Definition: a time series workload is append-heavy, time-ordered, rarely updated, and queried by time range with aggregation and downsampling. TimescaleDB hypertables are "PostgreSQL tables that automatically partition your time-series data by time"; InfluxDB 3 Core is "a database built to collect, process, transform, and store event and time series data"; ClickHouse is "a column-oriented SQL database management system (DBMS) for online analytical processing (OLAP)". Columnar storage keeps each column together, so an aggregate reads only the columns it needs and compresses them well (see OLTP vs OLAP & Columnar Storage).

text
     Query: average temperature per device per hour, last 7 days, 50,000 devices
1    row store, one table      reads every column of every row in range; index on (device, ts) helps filters, not the scan
2    TimescaleDB hypertable    prunes to 7 daily chunks; compressed chunks; continuous aggregate precomputes hourly
3    ClickHouse MergeTree      reads 3 columns (device, ts, temp), compressed; vectorised aggregation

Real scenario: IoT telemetry, application metrics, financial ticks, clickstream analytics, ad impressions, observability backends.

ProductModelSQLBest when
TimescaleDBPostgreSQL extension, hypertables, compression, continuous aggregatesFull PostgreSQLYou want time series next to relational data, joins included
InfluxDB 3Purpose-built time-series databaseSQL and InfluxQLMetrics and events ingestion with real-time queries
ClickHouseColumnar OLAP, MergeTree enginesClickHouse SQLLarge analytical scans and aggregations, also time series
CassandraPartition per device and time bucketCQLHuge write rates with simple range reads

Fix / how to use it: keep the OLTP database for state; stream events to the time-series or columnar store; set retention and downsampling from day one.

Graph databases: Neo4j Good to know ​

In plain words: when the questions are about paths through relationships ("how are these two accounts connected?"), a graph database stores the relationships as first-class records and follows them directly.

Common misunderstanding: "Our data has relationships, so we need a graph database." All data has relationships. A graph store pays off when queries traverse many hops of variable depth; one or two joins are what relational databases do well.

Definition: Neo4j's documentation: "A Neo4j graph database stores data as nodes, relationships, and properties instead of in tables or documents." Queries are written in Cypher (or the ISO GQL standard). PostgreSQL covers shallow cases with recursive CTEs; see Graph Databases.

text
     Query: accounts within 4 hops of a flagged account through shared devices or cards
1    PostgreSQL   WITH RECURSIVE over an edges table; cost grows quickly with hops and fan-out
2    Neo4j        MATCH (a:Account {flagged:true})-[:USES*1..4]-(b:Account) RETURN DISTINCT b

Real scenario: fraud rings, recommendation by co-purchase, access-control graphs (ReBAC; see Authorization Models), network topology, knowledge graphs.

HopsPostgreSQLNeo4j
1 to 2Indexed joins, fineFine
3 to 6, variableRecursive CTE, grows fastDesigned for it
Bulk aggregates over all nodesGoodWeaker

Fix / how to use it: keep the graph as a derived store fed from the system of record unless the graph is the product.

Vector databases and pgvector Good to know ​

In plain words: store embeddings (lists of numbers that represent meaning) and find the nearest ones to a query embedding.

Common misunderstanding: "Retrieval-augmented generation needs a dedicated vector database." pgvector ("Open-source vector similarity search for Postgres") keeps vectors next to the rows they describe, with HNSW and IVFFlat indexes, filters and joins in the same query. Dedicated stores (Qdrant, Milvus, Pinecone) pay off at very large vector counts or with specialised filtering and multi-tenancy needs.

Definition: a vector database indexes high-dimensional vectors for approximate nearest-neighbour (ANN) search, trading recall for latency. Details in Vector Search & pgvector and ML Systems.

text
     Query: 10 products most similar to an image, only in stock, only category 'shoes'
1    pgvector     SELECT ... FROM products WHERE in_stock AND category = 'shoes'
                  ORDER BY embedding <=> $1 LIMIT 10   -- HNSW index, filters in SQL
2    dedicated    filter by payload in the vector store; stock from a second call or a synced copy

Real scenario: semantic search, RAG over documents, image similarity, deduplication, recommendations.

ScaleChoice
Up to tens of millions of vectors, filters on relational datapgvector
Hundreds of millions to billions, specialised filteringDedicated vector database

Fix / how to use it: start with pgvector; measure recall and p99; move when the numbers say so.

NewSQL and distributed SQL: Spanner, CockroachDB, YugabyteDB, Vitess Important ​

In plain words: SQL and transactions, but the data is split into ranges spread over many nodes, replicated with consensus, so writes scale out and survive node or zone loss.

Common misunderstanding: "Distributed SQL is PostgreSQL that scales for free." Every write is a consensus round across replicas (and across regions if you place them so); single-row latency is higher than a local primary, some PostgreSQL features and extensions are missing, and data placement becomes your design problem.

Definition: NewSQL (now usually distributed SQL) databases provide relational SQL with ACID transactions on a shared-nothing cluster. Google Cloud's Spanner overview: "A distributed clock called TrueTime guarantees transactions are strongly consistent even across regions. Data is automatically 'split' for scalability and replicated using a synchronous, Paxos-based scheme for availability." CockroachDB replicates ranges with Raft and commits cross-range transactions with "a distributed, atomic commit protocol called Parallel Commits". YugabyteDB offers a PostgreSQL-compatible API (YSQL) over a distributed storage layer. Vitess is different in kind: "an open-source database clustering system for horizontal scaling of MySQL", routing queries to shards of ordinary MySQL; PlanetScale is built on it.

text
     Write: UPDATE accounts SET balance = balance - 100 WHERE id = 7   (3 replicas, 3 zones)
1    gateway node finds the range for id=7 and its leaseholder / leader
2    leader proposes the write intent through Raft (Paxos in Spanner)
3    majority (2 of 3) acknowledges -> committed; latency = one round trip to the nearest quorum
4    multi-region placement: quorum across regions adds tens of milliseconds per write

Real scenario: a global ledger or inventory that must stay consistent across regions (Spanner's overview names trade ledgers and retail inventory ledgers); a SaaS that outgrew one PostgreSQL primary but cannot give up SQL; a MySQL estate that needs sharding (Vitess).

ProductAPIConsensusNotes
Google Cloud SpannerGoogleSQL and PostgreSQL dialectPaxos + TrueTimeManaged only; external consistency
CockroachDBPostgreSQL wire protocolRaft per rangeSerializable by default; READ COMMITTED available
YugabyteDBYSQL (PostgreSQL), YCQLRaft per tabletReuses PostgreSQL query layer
Vitess / PlanetScaleMySQL protocolMySQL replication per shardSharding layer, not one consensus database
TiDBMySQL protocolRaft (TiKV)HTAP with TiFlash

Fix / how to use it: choose distributed SQL when you need SQL invariants and either write scale beyond one primary or multi-region writes; design locality (tables partitioned by region, follower reads) explicitly. Mechanics in Distributed SQL, Consensus & 2PC.

Serverless databases: Aurora Serverless, Neon, PlanetScale, DynamoDB on-demand Good to know ​

In plain words: you pay for what you use and the capacity follows the load, sometimes down to zero.

Common misunderstanding: "Serverless means infinitely elastic and always cheaper." Scaling has steps and limits, scale-from-zero adds a cold-start delay, and a steady high load is often cheaper on provisioned capacity.

Definition: a serverless database decouples billing (and often compute) from fixed instances. DynamoDB on-demand "offers pay-per-request pricing for read and write requests" and is "the default and recommended throughput option for most DynamoDB workloads". Aurora Serverless v2 scales in Aurora capacity units (ACUs), can "add half an ACU when only a little more capacity is needed", and supports scaling to zero ACUs with automatic pause and resume. Neon separates storage from compute so "compute endpoints can automatically scale up and down according to load, or scale to zero entirely". PlanetScale offers managed Vitess (MySQL) and Postgres.

text
     Hour    Load       Provisioned (fixed)       Serverless (per use)
1    02:00   ~0         paying for idle            near zero (or paused; first request waits)
2    09:00   10x        throttled or over-sized    scales up in steps
3    13:00   steady     cheaper per unit           more expensive per unit at constant load

Real scenario: development and preview environments (Neon branches), spiky internal tools, new products with unknown load, per-tenant databases, event-driven backends (Serverless & Event-Driven Compute).

ProductBilling unitScale to zeroEngine
DynamoDB on-demandPer request + storageYes (no idle compute)DynamoDB
Aurora Serverless v2ACU-hours + I/O + storageYes, with auto-pauseMySQL / PostgreSQL compatible
NeonCompute-hours + storageYesPostgreSQL
PlanetScalePlan/cluster basedDepends on planVitess (MySQL), Postgres

Fix / how to use it: serverless for spiky or unknown load and non-production; provisioned or reserved capacity once load is steady and measured.

Polyglot persistence: one store per bounded context Must-know ​

In plain words: different parts of the system keep their data in different databases, each chosen for how that part uses its data, and each owned by exactly one service or module.

Common misunderstanding: "Polyglot persistence means every service picks its favourite database." It means the workload picks, the store has one owner, and every extra store must justify its operational cost. Fowler: "This will come at a cost in complexity. Each data storage mechanism introduces a new interface to be learned."

Definition: polyglot persistence is using several storage technologies in one system, each behind a boundary (a bounded context, a module or a service). Data that another context needs is published as events (outbox) or captured from the log (CDC) and stored as a read model there; the owning store remains the source of truth. See Data Ownership in Microservices and Data Patterns.

Cart / sessions: Redishash per customer, TTL 7 daysAOF everysec; loss = stale cartno money, no historycheckout reads cart, prices from CatalogCatalog: MongoDBproduct document, variants embeddedattributes differ per product typechange streams outOrdering: PostgreSQLorders + lines + outbox, one transactionFKs, CHECKs, ad-hoc SQLsystem of record for moneyCDC / outbox relayDebezium, change streamsinto Kafka topicsat-least-once, idempotent sinksSearch: OpenSearchfull-text, facets, typeaheadderived, rebuildable indexseconds behind the sourceAnalytics: ClickHousecolumnar, aggregationsrevenue per region per hournever on the OLTP primaryCache invalidationRedis cache keys for productand order pages deleted onchange events
text
     Step   Event                                                   Store
1    1      Customer adds sku-9 to cart                              Redis (Cart)
2    2      Checkout reads cart, prices each sku                      MongoDB (Catalog)
3    3      Order, lines and outbox row in one transaction            PostgreSQL (Ordering)
4    4      Debezium reads the WAL, publishes OrderPlaced             Kafka
5    5      Indexer updates order search; ETL updates revenue tables  OpenSearch, ClickHouse
6    6      Cache invalidator deletes order-page cache keys           Redis (cache)

Real scenario: e-commerce (worked below); a bank with an Oracle ledger, a Kafka event log and an Elasticsearch customer search; a ride-hailing app with a relational trip store, a geospatial index and a time-series location history (Uber case study).

Cost of each extra storeWhat it means
OperationsBackups, restore drills, upgrades, monitoring, on-call runbooks
SecurityCredentials, network rules, encryption, audit per store
ConsistencyA pipeline (CDC/outbox) and its lag, replay and reconciliation
SkillsSomeone who knows its failure modes
Local developmentAnother container in every developer's setup

Fix / how to use it: one owner per store, no shared tables across contexts, sync only through events or CDC, and a written reason per store. The Laravel config/database.php with one connection per context is in Laravel.

Migration between stores: dual write, backfill, shadow reads Important ​

In plain words: move a context from one database to another in reversible steps while production traffic keeps flowing, proving the new store gives the same answers before trusting it.

Common misunderstanding: "Dual write is safe if we write to both in the same request." Without a transaction spanning both stores, one write can succeed and the other fail; dual write must be repairable (a pending queue, a reconciliation job) or replaced by CDC from the old store.

Definition: dual write sends each write to both stores, primary first; backfill copies historical data idempotently; shadow read serves from the old store and also reads the new store, recording differences; the flip makes the new store primary while the old one is kept for rollback. The approach is the data side of the Strangler Fig pattern.

Every arrow is a config flip; every dashed arrow is the rollback0 Old onlyreads: oldwrites: oldport + contract tests1 Dual writereads: oldwrites: old, then newfailed new write queued2 Backfill + shadowcopy history, idempotentread old, also read newlog mismatches to zero3 New primaryreads: newwrites: new, then oldold kept warm4 New onlyold store retiredafter a full cycle(month-end, peaks)Prefer CDC from the primary over application dual writes when the new store can consume a change stream
text
     Phase          Reads     Writes              Exit criterion
1    0 Old only     old       old                 port in place, contract suite green on both adapters
2    1 Dual write   old       old, then new       failed new writes queued and drained
3    2 Backfill     old       old, then new       history copied; duplicates skipped
4    3 Shadow read  old (+new compared)           mismatch rate 0 for a full business cycle
5    4 New primary  new       new, then old       latency and error SLOs met; rollback rehearsed
6    5 New only     new       new                 old store archived, then removed

Real scenario: MongoDB to PostgreSQL after reporting needs grew; a sharded MySQL to Vitess; DynamoDB to Aurora after the access patterns stopped being stable; a self-hosted Cassandra to a managed service.

TechniqueAdvantageRisk
Application dual writeSimple, no infrastructureDivergence on partial failure; must queue and repair
CDC from old storeOne write path; ordered by the logNeeds CDC tooling (Debezium, DynamoDB Streams, change streams)
BackfillBrings historyLoad on the old store; must be idempotent and throttled
Shadow readProves equivalence on real trafficDoubles read load; compare off the hot path
Feature-flag flipInstant rollbackBoth stores must stay in sync until retirement

Fix / how to use it: the Go migrate package below wraps two adapters behind the same port with phases, a pending queue and mismatch recording; schema-level steps inside one database are in Zero-Downtime Schema Migrations.

Mechanics ​

DynamoDB units, limits and the per-partition ceiling ​

The DynamoDB partition-key guide: "Every partition in a DynamoDB table is designed to deliver a maximum capacity of 3,000 read units per second and 1,000 write units per second. One read unit represents one strongly consistent read operation per second, or two eventually consistent read operations per second, for an item up to 4 KB in size. One write unit represents one write operation per second for an item up to 1 KB in size."

Knob or limitValueSource pageDesign consequence
Read unit4 KB strong read, or two eventual readsPartition key best practicesA 20 KB item costs 5 units per strong read
Write unit1 KB writePartition key best practicesEvery GSI that projects the item is another write
Per-partition throughput3,000 RCU and 1,000 WCU per secondPartition key best practicesOne hot key is capped no matter how large the table
Item size400 KB maximumLarge items best practicesLarge blobs go to S3 with a pointer
TransactionsUp to 100 actions, 4 MB aggregate, one account and RegionTransactions APIKeep invariants within 100 items
GSIs per table20 (adjustable)Service quotasEach access path costs one
LSIs per table5, created with the tableService quotasSame partition key, adds a 10 GB item-collection limit
GSI readsEventually consistent onlyGSI pageRead-your-writes needs the base table
Capacity modesOn-demand (default) or provisionedCapacity mode pageProvisioned plus auto scaling for steady load

Running the lab sizing program for the Ordering patterns prints:

text
access pattern                                 units/op    units/s
AP1 place order (2 KB item + 2 KB GSI copy)         4.0        800
AP2 get order, strong                               1.0       1500
AP3 latest 20 orders, eventual                      5.0       2000
AP4 PLACED feed on GSI, eventual                   12.5        250
total: 3750 RCU/s, 800 WCU/s
partitions needed for throughput alone: 2
max strong 2 KB reads/s on ONE key: 3000
max 2 KB writes/s on ONE key: 500
orders storage per year: 139 GB

Two lessons from the numbers: the whole Ordering workload fits in a handful of partitions (and on one PostgreSQL primary), and the real risk is one key. A status GSI keyed on PLACED would put every new order on one GSI partition, capped at 1,000 WCU; the shard suffix (STATUS#PLACED#0..3) is what removes that ceiling.

MongoDB limits and modelling knobs ​

Knob or limitValueConsequence
Document size16 MiB BSONUnbounded arrays must become a collection
Nesting depth100 levelsRarely hit; deep nesting is a smell anyway
AtomicitySingle document, including nested arraysEmbed what must change together
Multi-document transactionsReplica set or sharded cluster required; Laravel MongoDB docs: "your deployment must be a multiple node replica set or sharded cluster"Not available on a standalone development server
Schema validation$jsonSchema validator per collectionUse it; schemaless is a choice, not a default
Write concernw: "majority" for durability across failoverLower values trade durability for latency

Redis persistence and memory knobs ​

text
# redis.conf for a keyspace used as a primary store (carts)
appendonly yes
appendfsync everysec          # "fsync every second ... you may lose 1 second of data"
save 3600 1 300 100 60 10000  # RDB snapshots as well, for backups and faster restarts
maxmemory 4gb
maxmemory-policy noeviction   # never drop a key silently; writes get an error instead
# for a pure cache instance instead:
# appendonly no
# maxmemory-policy allkeys-lru
SettingValuesEffect
appendfsyncalways, everysec (default), noRedis docs: always is "Very very slow, very safe"; no leaves flushing to the OS ("Normally Linux will flush data every 30 seconds with this configuration")
saveSnapshot points (seconds, changes)RDB; "you should be prepared to lose the latest minutes of data"
AOF formatMulti part AOF since Redis 7.0.0Base file plus incremental files, tracked by a manifest
maxmemory-policynoeviction, allkeys-lru, allkeys-lfu, volatile-lru, volatile-ttl, ...allkeys-lru "is a good default option" for caches; noeviction for stores
Fork costRDB and AOF rewrite fork a childRedis docs: may stop serving clients "for some milliseconds or even for one second if the dataset is very big"
Cluster16,384 hash slotsMulti-key commands need keys in one slot: hash tags cart:{42}

PostgreSQL knobs for flexible data ​

KnobEffectNote
json vs jsonbjson stores text and reparses; jsonb stores "a decomposed binary format"PostgreSQL docs: "most applications should prefer to store JSON data as jsonb"
jsonb_ops vs jsonb_path_ops GINjsonb_path_ops is smaller and faster for @> containment onlyDefault jsonb_ops also supports key-existence operators
Generated columnGENERATED ALWAYS AS (attributes ->> 'brand') STOREDTurns a hot JSON field into an indexed column
CHECK (jsonb_typeof(...) = 'object')Rejects arrays or scalars where objects belongValidation without a full JSON Schema
Partial indexWHERE status = 'PLACED'Small index for a hot subset (AP4)

Error codes and messages you will actually see ​

ProductCode / exceptionMessage (verbatim where documented)Retry?Usual cause in this chapter
PostgreSQLSQLSTATE 23505unique_violationNo; return the existing rowRetried order with the same ID
PostgreSQLSQLSTATE 23503foreign_key_violationNoLine for an order that does not exist
PostgreSQLSQLSTATE 23514check_violationNoQuantity 0, unknown status, JSONB not an object
PostgreSQLSQLSTATE 40001serialization_failureYes, whole transactionConcurrent stock updates under SERIALIZABLE
DynamoDBConditionalCheckFailedException"The conditional request failed."Noattribute_not_exists(PK) on a duplicate order
DynamoDBProvisionedThroughputExceededException"You exceeded your maximum allowed provisioned throughput for a table or for one or more global secondary indexes."Yes, with backoffHot partition or under-provisioned GSI
DynamoDBItemCollectionSizeLimitExceededException"Collection size exceeded."Yes (after design change)LSI table with a partition key over 10 GB
DynamoDBTransactionCanceledExceptionCancellation reasons per actionDepends on reasonA condition in TransactWriteItems failed
LaravelIlluminate\Database\UniqueConstraintViolationExceptionWraps the driver's duplicate-key errorNoSame as 23505
RedisOOM error replyReturned on writes under noeviction at maxmemoryAfter freeing memoryStore outgrew RAM

Go ​

The Go module (academy/sql-vs-nosql-decision) has one port and three adapters. The port is the contract: one behavioural test suite runs against the in-memory fake, the DynamoDB adapter (with a fake client that understands the same key conditions) and, when ORDERS_PG_DSN is set, PostgreSQL. pgx v5.13.0 requires Go 1.25, which sets the module's go directive.

Before ​

The store was picked first ("NoSQL for scale"), the handler speaks the DynamoDB API, the total is a float, a retry overwrites, and the only way to answer "orders of a customer" is a Scan with a filter that reads and bills the whole table.

go
// Package before shows the shape this chapter argues against: the store
// was chosen first ("we need scale, so NoSQL"), the use case speaks the
// store's API directly, and every new question becomes a table scan.
package before

import (
	"context"
	"strconv"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

type OrderHandler struct {
	DB *dynamodb.Client
}

// PlaceOrder writes a float total, no condition (a retry overwrites), and
// a key that cannot answer "latest orders of a customer".
func (h OrderHandler) PlaceOrder(ctx context.Context, orderID, customerID string, total float64) error {
	_, err := h.DB.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String("orders"),
		Item: map[string]types.AttributeValue{
			"order_id":    &types.AttributeValueMemberS{Value: orderID},
			"customer_id": &types.AttributeValueMemberS{Value: customerID},
			"total":       &types.AttributeValueMemberN{Value: strconv.FormatFloat(total, 'f', -1, 64)},
		},
	})
	return err
}

// OrdersOfCustomer is the query nobody modelled: a Scan with a filter
// reads (and bills) the whole table, then throws most of it away.
func (h OrderHandler) OrdersOfCustomer(ctx context.Context, customerID string) ([]map[string]types.AttributeValue, error) {
	var out []map[string]types.AttributeValue
	p := dynamodb.NewScanPaginator(h.DB, &dynamodb.ScanInput{
		TableName:        aws.String("orders"),
		FilterExpression: aws.String("customer_id = :c"),
		ExpressionAttributeValues: map[string]types.AttributeValue{
			":c": &types.AttributeValueMemberS{Value: customerID},
		},
	})
	for p.HasMorePages() {
		page, err := p.NextPage(ctx)
		if err != nil {
			return nil, err
		}
		out = append(out, page.Items...)
	}
	return out, nil
}

After ​

The port, with the access patterns written above it. The domain validates its own invariants because key-value stores cannot enforce CHECK constraints:

go
// Package orders is the Ordering bounded context. The domain and the use
// cases depend only on the OrderRepository port; PostgreSQL (pgx) and
// DynamoDB (AWS SDK for Go v2) are adapters behind it.
package orders

import (
	"context"
	"errors"
	"time"
)

// The access patterns this context must serve. They were written down
// before any schema, because they decide which store fits.
//
//	AP1 Place an order (one write, idempotent on order ID)       ~200 writes/s peak
//	AP2 Get one order with its lines by customer + order ID      point lookup
//	AP3 List a customer's latest N orders, newest first          range scan on one key
//	AP4 List orders in a status (PLACED) for the warehouse feed  secondary access path
//
// Anything else (ad-hoc reports, revenue per region) goes to the analytics
// store through CDC, not to this repository.

// Status is the lifecycle state of an order.
type Status string

const (
	StatusPlaced  Status = "PLACED"
	StatusPaid    Status = "PAID"
	StatusShipped Status = "SHIPPED"
)

// Line is one product in an order. Lines are owned by the order and are
// always read with it, so document and key-value adapters embed them.
type Line struct {
	SKU        string
	Quantity   int
	PriceCents int64
}

// Order is the aggregate. Money is integer cents, never float.
type Order struct {
	ID         string // time-sortable ID (ULID-style), so IDs sort by creation
	CustomerID string
	Status     Status
	Lines      []Line
	TotalCents int64
	CreatedAt  time.Time
}

// ErrNotFound and ErrDuplicate are the only errors callers branch on.
var (
	ErrNotFound  = errors.New("orders: not found")
	ErrDuplicate = errors.New("orders: duplicate order id")
	ErrInvalid   = errors.New("orders: invalid order")
)

// OrderRepository is the port. Each method maps to one access pattern.
type OrderRepository interface {
	Save(ctx context.Context, o Order) error                                           // AP1
	Get(ctx context.Context, customerID, orderID string) (Order, error)                // AP2
	ListByCustomer(ctx context.Context, customerID string, limit int) ([]Order, error) // AP3
	ListByStatus(ctx context.Context, status Status, limit int) ([]Order, error)       // AP4
}

// Validate enforces the invariants every adapter relies on. A relational
// store would also enforce them with CHECK constraints; key-value stores
// cannot, so the domain must.
func (o Order) Validate() error {
	if o.ID == "" || o.CustomerID == "" || len(o.Lines) == 0 {
		return ErrInvalid
	}
	var total int64
	for _, l := range o.Lines {
		if l.Quantity <= 0 || l.PriceCents < 0 {
			return ErrInvalid
		}
		total += int64(l.Quantity) * l.PriceCents
	}
	if total != o.TotalCents {
		return ErrInvalid
	}
	return nil
}
go
package orders

import (
	"context"
	"errors"
	"time"
)

// Service holds the use cases. It never imports a driver.
type Service struct {
	Repo  OrderRepository
	Clock func() time.Time
}

// PlaceOrder computes the total, validates and saves. A retried request
// with the same order ID returns the stored order instead of a second one.
func (s Service) PlaceOrder(ctx context.Context, id, customerID string, lines []Line) (Order, error) {
	o := Order{ID: id, CustomerID: customerID, Status: StatusPlaced, Lines: lines, CreatedAt: s.Clock().UTC()}
	for _, l := range lines {
		o.TotalCents += int64(l.Quantity) * l.PriceCents
	}
	if err := o.Validate(); err != nil {
		return Order{}, err
	}
	err := s.Repo.Save(ctx, o)
	if errors.Is(err, ErrDuplicate) {
		return s.Repo.Get(ctx, customerID, id)
	}
	return o, err
}

PostgreSQL adapter with pgx. pgx.BeginFunc wraps the order, its lines (one unnest insert) and the outbox row in one transaction; SQLSTATE 23505 becomes ErrDuplicate; lists load lines with = ANY($1) instead of N+1 queries:

go
package orders

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
)

// PGDB is the subset of *pgxpool.Pool the adapter needs; *pgxpool.Pool
// and pgx.Tx both satisfy it.
type PGDB interface {
	Begin(ctx context.Context) (pgx.Tx, error)
	Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
}

// Postgres implements OrderRepository on the schema in sql/schema.sql.
type Postgres struct{ DB PGDB }

const uniqueViolation = "23505" // SQLSTATE unique_violation

func (p Postgres) Save(ctx context.Context, o Order) error {
	if err := o.Validate(); err != nil {
		return err
	}
	err := pgx.BeginFunc(ctx, p.DB, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx,
			`INSERT INTO orders (id, customer_id, status, total_cents, created_at)
			 VALUES ($1, $2, $3, $4, $5)`,
			o.ID, o.CustomerID, string(o.Status), o.TotalCents, o.CreatedAt); err != nil {
			return err
		}
		skus, qty, price, nos := make([]string, 0, len(o.Lines)), make([]int32, 0, len(o.Lines)),
			make([]int64, 0, len(o.Lines)), make([]int32, 0, len(o.Lines))
		for i, l := range o.Lines {
			skus, qty, price, nos = append(skus, l.SKU), append(qty, int32(l.Quantity)),
				append(price, l.PriceCents), append(nos, int32(i+1))
		}
		// One statement for all lines: unnest the arrays into rows.
		if _, err := tx.Exec(ctx,
			`INSERT INTO order_lines (order_id, line_no, sku, quantity, price_cents)
			 SELECT $1::text, * FROM unnest($2::int[], $3::text[], $4::int[], $5::bigint[])`,
			o.ID, nos, skus, qty, price); err != nil {
			return err
		}
		// Same transaction: the event other stores consume (see migrate/ and CDC).
		_, err := tx.Exec(ctx,
			`INSERT INTO outbox (aggregate_id, event_type, payload)
			 VALUES ($1, 'OrderPlaced', jsonb_build_object('order_id', $1::text, 'customer_id', $2::text, 'total_cents', $3::bigint))`,
			o.ID, o.CustomerID, o.TotalCents)
		return err
	})
	var pgErr *pgconn.PgError
	if errors.As(err, &pgErr) && pgErr.Code == uniqueViolation {
		return ErrDuplicate
	}
	return err
}

func (p Postgres) Get(ctx context.Context, customerID, orderID string) (Order, error) {
	list, err := p.queryOrders(ctx,
		`SELECT id, customer_id, status, total_cents, created_at FROM orders
		 WHERE customer_id = $1 AND id = $2`, customerID, orderID)
	if err != nil {
		return Order{}, err
	}
	if len(list) == 0 {
		return Order{}, ErrNotFound
	}
	return list[0], nil
}

func (p Postgres) ListByCustomer(ctx context.Context, customerID string, limit int) ([]Order, error) {
	return p.queryOrders(ctx,
		`SELECT id, customer_id, status, total_cents, created_at FROM orders
		 WHERE customer_id = $1 ORDER BY id DESC LIMIT $2`, customerID, limit)
}

func (p Postgres) ListByStatus(ctx context.Context, status Status, limit int) ([]Order, error) {
	return p.queryOrders(ctx,
		`SELECT id, customer_id, status, total_cents, created_at FROM orders
		 WHERE status = $1 ORDER BY id DESC LIMIT $2`, string(status), limit)
}

// queryOrders loads headers, then all their lines in one round trip
// (WHERE order_id = ANY($1)), avoiding N+1 queries.
func (p Postgres) queryOrders(ctx context.Context, sql string, args ...any) ([]Order, error) {
	rows, err := p.DB.Query(ctx, sql, args...)
	if err != nil {
		return nil, err
	}
	list, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (Order, error) {
		var o Order
		var st string
		err := r.Scan(&o.ID, &o.CustomerID, &st, &o.TotalCents, &o.CreatedAt)
		o.Status = Status(st)
		return o, err
	})
	if err != nil || len(list) == 0 {
		return list, err
	}
	ids := make([]string, len(list))
	pos := make(map[string]int, len(list))
	for i, o := range list {
		ids[i], pos[o.ID] = o.ID, i
	}
	lrows, err := p.DB.Query(ctx,
		`SELECT order_id, sku, quantity, price_cents FROM order_lines
		 WHERE order_id = ANY($1) ORDER BY order_id, line_no`, ids)
	if err != nil {
		return nil, err
	}
	defer lrows.Close()
	for lrows.Next() {
		var id string
		var l Line
		if err := lrows.Scan(&id, &l.SKU, &l.Quantity, &l.PriceCents); err != nil {
			return nil, err
		}
		list[pos[id]].Lines = append(list[pos[id]].Lines, l)
	}
	return list, lrows.Err()
}

DynamoDB adapter with the AWS SDK for Go v2, single-table design. PutItem with attribute_not_exists(PK) makes creation idempotent, GetItem uses ConsistentRead, AP3 is one Query with begins_with in descending order, AP4 is a scatter-gather over four GSI shards:

go
package orders

import (
	"context"
	"errors"
	"fmt"
	"hash/fnv"
	"sort"
	"strconv"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoAPI is the subset of *dynamodb.Client the adapter uses, so tests
// can pass a fake. The method signatures are the SDK's own.
type DynamoAPI interface {
	PutItem(ctx context.Context, in *dynamodb.PutItemInput, opts ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error)
	GetItem(ctx context.Context, in *dynamodb.GetItemInput, opts ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error)
	Query(ctx context.Context, in *dynamodb.QueryInput, opts ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error)
}

// Single-table design: every entity of the Ordering context lives in one
// table; the key layout, not the table name, separates them.
//
//	Entity    PK            SK              GSI1PK                 GSI1SK
//	Customer  CUST#c-42     PROFILE         -                      -
//	Order     CUST#c-42     ORDER#01J..     STATUS#PLACED#3        01J..
//
// AP2 = GetItem(PK, SK). AP3 = Query(PK, begins_with(SK, "ORDER#")) newest
// first. AP4 = Query on GSI1 per shard, merged. Lines are embedded in the
// order item (read together, written together, bounded in number).
type Dynamo struct {
	Client DynamoAPI
	Table  string
	// StatusShards spreads one status over N GSI partition keys; a GSI on a
	// three-value attribute would otherwise be a hot partition.
	StatusShards int
}

type orderItem struct {
	PK, SK         string
	Type           string
	GSI1PK, GSI1SK string
	OrderID        string
	CustomerID     string
	Status         string
	TotalCents     int64
	CreatedAt      string
	Lines          []lineItem
}

type lineItem struct {
	SKU        string `dynamodbav:"sku"`
	Quantity   int    `dynamodbav:"qty"`
	PriceCents int64  `dynamodbav:"price"`
}

func customerPK(id string) string { return "CUST#" + id }
func orderSK(id string) string    { return "ORDER#" + id }

func (d Dynamo) shards() int {
	if d.StatusShards < 1 {
		return 1
	}
	return d.StatusShards
}

func (d Dynamo) statusPK(s Status, orderID string) string {
	h := fnv.New32a()
	h.Write([]byte(orderID))
	return fmt.Sprintf("STATUS#%s#%d", s, int(h.Sum32())%d.shards())
}

func (d Dynamo) toItem(o Order) orderItem {
	it := orderItem{
		PK: customerPK(o.CustomerID), SK: orderSK(o.ID), Type: "ORDER",
		GSI1PK: d.statusPK(o.Status, o.ID), GSI1SK: o.ID,
		OrderID: o.ID, CustomerID: o.CustomerID, Status: string(o.Status),
		TotalCents: o.TotalCents, CreatedAt: o.CreatedAt.UTC().Format(time.RFC3339Nano),
	}
	for _, l := range o.Lines {
		it.Lines = append(it.Lines, lineItem(l))
	}
	return it
}

func fromItem(it orderItem) (Order, error) {
	t, err := time.Parse(time.RFC3339Nano, it.CreatedAt)
	o := Order{ID: it.OrderID, CustomerID: it.CustomerID, Status: Status(it.Status), TotalCents: it.TotalCents, CreatedAt: t}
	for _, l := range it.Lines {
		o.Lines = append(o.Lines, Line(l))
	}
	return o, err
}

func (d Dynamo) Save(ctx context.Context, o Order) error {
	if err := o.Validate(); err != nil {
		return err
	}
	av, err := attributevalue.MarshalMap(d.toItem(o))
	if err != nil {
		return err
	}
	_, err = d.Client.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(d.Table),
		Item:      av,
		// Idempotent create: refuse to overwrite an existing order.
		ConditionExpression: aws.String("attribute_not_exists(PK)"),
	})
	var ccf *types.ConditionalCheckFailedException
	if errors.As(err, &ccf) {
		return ErrDuplicate
	}
	return err
}

func (d Dynamo) Get(ctx context.Context, customerID, orderID string) (Order, error) {
	out, err := d.Client.GetItem(ctx, &dynamodb.GetItemInput{
		TableName: aws.String(d.Table),
		Key: map[string]types.AttributeValue{
			"PK": &types.AttributeValueMemberS{Value: customerPK(customerID)},
			"SK": &types.AttributeValueMemberS{Value: orderSK(orderID)},
		},
		ConsistentRead: aws.Bool(true), // base table only; GSIs are eventually consistent
	})
	if err != nil {
		return Order{}, err
	}
	if len(out.Item) == 0 {
		return Order{}, ErrNotFound
	}
	var it orderItem
	if err := attributevalue.UnmarshalMap(out.Item, &it); err != nil {
		return Order{}, err
	}
	return fromItem(it)
}

func (d Dynamo) ListByCustomer(ctx context.Context, customerID string, limit int) ([]Order, error) {
	return d.query(ctx, &dynamodb.QueryInput{
		TableName:              aws.String(d.Table),
		KeyConditionExpression: aws.String("PK = :pk AND begins_with(SK, :prefix)"),
		ExpressionAttributeValues: map[string]types.AttributeValue{
			":pk":     &types.AttributeValueMemberS{Value: customerPK(customerID)},
			":prefix": &types.AttributeValueMemberS{Value: "ORDER#"},
		},
		ScanIndexForward: aws.Bool(false), // newest first: sort key descending
		Limit:            aws.Int32(int32(limit)),
	})
}

// ListByStatus is a scatter-gather over the write shards of GSI1.
func (d Dynamo) ListByStatus(ctx context.Context, status Status, limit int) ([]Order, error) {
	var all []Order
	for s := 0; s < d.shards(); s++ {
		part, err := d.query(ctx, &dynamodb.QueryInput{
			TableName:              aws.String(d.Table),
			IndexName:              aws.String("GSI1"),
			KeyConditionExpression: aws.String("GSI1PK = :pk"),
			ExpressionAttributeValues: map[string]types.AttributeValue{
				":pk": &types.AttributeValueMemberS{Value: "STATUS#" + string(status) + "#" + strconv.Itoa(s)},
			},
			ScanIndexForward: aws.Bool(false),
			Limit:            aws.Int32(int32(limit)),
		})
		if err != nil {
			return nil, err
		}
		all = append(all, part...)
	}
	sort.Slice(all, func(i, j int) bool { return all[i].ID > all[j].ID })
	if len(all) > limit {
		all = all[:limit]
	}
	return all, nil
}

func (d Dynamo) query(ctx context.Context, in *dynamodb.QueryInput) ([]Order, error) {
	out, err := d.Client.Query(ctx, in)
	if err != nil {
		return nil, err
	}
	var items []orderItem
	if err := attributevalue.UnmarshalListOfMaps(out.Items, &items); err != nil {
		return nil, err
	}
	list := make([]Order, 0, len(items))
	for _, it := range items {
		o, err := fromItem(it)
		if err != nil {
			return nil, err
		}
		list = append(list, o)
	}
	return list, nil
}

The in-memory fake and the contract suite. The same four tests run against every adapter; a candidate store that cannot pass them cannot serve the context:

go
package orders

import (
	"context"
	"sort"
	"sync"
)

// Memory is the in-process fake used by use-case tests and as the
// reference behaviour every real adapter must match.
type Memory struct {
	mu   sync.Mutex
	rows map[string]Order // key: customerID + "/" + orderID
}

func NewMemory() *Memory { return &Memory{rows: map[string]Order{}} }

func (m *Memory) Save(_ context.Context, o Order) error {
	if err := o.Validate(); err != nil {
		return err
	}
	m.mu.Lock()
	defer m.mu.Unlock()
	k := o.CustomerID + "/" + o.ID
	if _, ok := m.rows[k]; ok {
		return ErrDuplicate
	}
	o.Lines = append([]Line(nil), o.Lines...)
	m.rows[k] = o
	return nil
}

func (m *Memory) Get(_ context.Context, customerID, orderID string) (Order, error) {
	m.mu.Lock()
	defer m.mu.Unlock()
	o, ok := m.rows[customerID+"/"+orderID]
	if !ok {
		return Order{}, ErrNotFound
	}
	return o, nil
}

func (m *Memory) ListByCustomer(_ context.Context, customerID string, limit int) ([]Order, error) {
	return m.list(func(o Order) bool { return o.CustomerID == customerID }, limit), nil
}

func (m *Memory) ListByStatus(_ context.Context, status Status, limit int) ([]Order, error) {
	return m.list(func(o Order) bool { return o.Status == status }, limit), nil
}

func (m *Memory) list(keep func(Order) bool, limit int) []Order {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []Order
	for _, o := range m.rows {
		if keep(o) {
			out = append(out, o)
		}
	}
	// Newest first; IDs are time-sortable so ID order equals creation order.
	sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
	if limit > 0 && len(out) > limit {
		out = out[:limit]
	}
	return out
}
go
package orders

import (
	"context"
	"sort"
	"strings"
	"sync"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// fakeDynamo understands exactly the key conditions the adapter sends:
// PK = :pk [AND begins_with(SK, :prefix)] on the table, GSI1PK = :pk on GSI1.
type fakeDynamo struct {
	mu    sync.Mutex
	items map[string]map[string]types.AttributeValue
}

func newFakeDynamo() *fakeDynamo {
	return &fakeDynamo{items: map[string]map[string]types.AttributeValue{}}
}

func s(av types.AttributeValue) string {
	if v, ok := av.(*types.AttributeValueMemberS); ok {
		return v.Value
	}
	return ""
}

func (f *fakeDynamo) PutItem(_ context.Context, in *dynamodb.PutItemInput, _ ...func(*dynamodb.Options)) (*dynamodb.PutItemOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	k := s(in.Item["PK"]) + "|" + s(in.Item["SK"])
	if _, exists := f.items[k]; exists && aws.ToString(in.ConditionExpression) == "attribute_not_exists(PK)" {
		return nil, &types.ConditionalCheckFailedException{Message: aws.String("The conditional request failed")}
	}
	f.items[k] = in.Item
	return &dynamodb.PutItemOutput{}, nil
}

func (f *fakeDynamo) GetItem(_ context.Context, in *dynamodb.GetItemInput, _ ...func(*dynamodb.Options)) (*dynamodb.GetItemOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	return &dynamodb.GetItemOutput{Item: f.items[s(in.Key["PK"])+"|"+s(in.Key["SK"])]}, nil
}

func (f *fakeDynamo) Query(_ context.Context, in *dynamodb.QueryInput, _ ...func(*dynamodb.Options)) (*dynamodb.QueryOutput, error) {
	f.mu.Lock()
	defer f.mu.Unlock()
	pk := s(in.ExpressionAttributeValues[":pk"])
	prefix := s(in.ExpressionAttributeValues[":prefix"])
	pkAttr, skAttr := "PK", "SK"
	if aws.ToString(in.IndexName) == "GSI1" {
		pkAttr, skAttr = "GSI1PK", "GSI1SK"
	}
	var out []map[string]types.AttributeValue
	for _, it := range f.items {
		if s(it[pkAttr]) == pk && strings.HasPrefix(s(it[skAttr]), prefix) {
			out = append(out, it)
		}
	}
	desc := in.ScanIndexForward != nil && !*in.ScanIndexForward
	sort.Slice(out, func(i, j int) bool {
		if desc {
			return s(out[i][skAttr]) > s(out[j][skAttr])
		}
		return s(out[i][skAttr]) < s(out[j][skAttr])
	})
	if in.Limit != nil && int(*in.Limit) < len(out) {
		out = out[:*in.Limit]
	}
	return &dynamodb.QueryOutput{Items: out, Count: int32(len(out))}, nil
}
go
package orders

import (
	"context"
	"errors"
	"os"
	"testing"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
)

// One behavioural suite, run against every adapter: the port is the
// contract, and a store is only a candidate if it passes.
func repoContract(t *testing.T, newRepo func(t *testing.T) OrderRepository) {
	ctx := context.Background()
	base := time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)
	svc := func(r OrderRepository, n int) Service {
		return Service{Repo: r, Clock: func() time.Time { return base.Add(time.Duration(n) * time.Minute) }}
	}
	lines := []Line{{SKU: "book-1", Quantity: 2, PriceCents: 1500}, {SKU: "pen-7", Quantity: 1, PriceCents: 250}}

	t.Run("AP1 place is idempotent on order id", func(t *testing.T) {
		r := newRepo(t)
		a, err := svc(r, 0).PlaceOrder(ctx, "01J0000001", "c-42", lines)
		if err != nil {
			t.Fatal(err)
		}
		b, err := svc(r, 5).PlaceOrder(ctx, "01J0000001", "c-42", lines)
		if err != nil {
			t.Fatal(err)
		}
		if a.TotalCents != 3250 || !b.CreatedAt.Equal(a.CreatedAt) {
			t.Fatalf("retry must return the first order: %+v vs %+v", a, b)
		}
		if err := r.Save(ctx, a); !errors.Is(err, ErrDuplicate) {
			t.Fatalf("want ErrDuplicate, got %v", err)
		}
	})

	t.Run("AP2 get returns lines; missing is ErrNotFound", func(t *testing.T) {
		r := newRepo(t)
		if _, err := svc(r, 0).PlaceOrder(ctx, "01J0000002", "c-42", lines); err != nil {
			t.Fatal(err)
		}
		o, err := r.Get(ctx, "c-42", "01J0000002")
		if err != nil || len(o.Lines) != 2 || o.Lines[0].SKU != "book-1" {
			t.Fatalf("get: %+v %v", o, err)
		}
		if _, err := r.Get(ctx, "c-42", "nope"); !errors.Is(err, ErrNotFound) {
			t.Fatalf("want ErrNotFound, got %v", err)
		}
	})

	t.Run("AP3 and AP4 newest first with limit", func(t *testing.T) {
		r := newRepo(t)
		for i, id := range []string{"01J0000010", "01J0000011", "01J0000012"} {
			if _, err := svc(r, i).PlaceOrder(ctx, id, "c-7", lines); err != nil {
				t.Fatal(err)
			}
		}
		if _, err := svc(r, 9).PlaceOrder(ctx, "01J0000013", "c-8", lines); err != nil {
			t.Fatal(err)
		}
		got, err := r.ListByCustomer(ctx, "c-7", 2)
		if err != nil || len(got) != 2 || got[0].ID != "01J0000012" || got[1].ID != "01J0000011" {
			t.Fatalf("by customer: %+v %v", got, err)
		}
		placed, err := r.ListByStatus(ctx, StatusPlaced, 3)
		if err != nil || len(placed) != 3 || placed[0].ID != "01J0000013" {
			t.Fatalf("by status: %+v %v", placed, err)
		}
	})

	t.Run("invalid order never reaches the store", func(t *testing.T) {
		r := newRepo(t)
		bad := Order{ID: "x", CustomerID: "c", Lines: []Line{{SKU: "a", Quantity: 0, PriceCents: 1}}}
		if err := r.Save(ctx, bad); !errors.Is(err, ErrInvalid) {
			t.Fatalf("want ErrInvalid, got %v", err)
		}
	})
}

func TestMemoryContract(t *testing.T) {
	repoContract(t, func(*testing.T) OrderRepository { return NewMemory() })
}

func TestDynamoContract(t *testing.T) {
	repoContract(t, func(*testing.T) OrderRepository {
		return Dynamo{Client: newFakeDynamo(), Table: "ordering", StatusShards: 4}
	})
}

// TestPostgresContract runs only when ORDERS_PG_DSN points at a scratch
// database that already has sql/schema.sql applied, for example
// ORDERS_PG_DSN=postgres://app:app@localhost:5432/orders_test
func TestPostgresContract(t *testing.T) {
	dsn := os.Getenv("ORDERS_PG_DSN")
	if dsn == "" {
		t.Skip("ORDERS_PG_DSN not set")
	}
	repoContract(t, func(t *testing.T) OrderRepository {
		pool, err := pgxpool.New(context.Background(), dsn)
		if err != nil {
			t.Fatal(err)
		}
		t.Cleanup(pool.Close)
		if _, err := pool.Exec(context.Background(), "TRUNCATE orders, order_lines, outbox"); err != nil {
			t.Fatal(err)
		}
		return Postgres{DB: pool}
	})
}

func TestStatusKeySpreadsOverShards(t *testing.T) {
	d := Dynamo{StatusShards: 4}
	seen := map[string]bool{}
	for _, id := range []string{"01J1", "01J2", "01J3", "01J4", "01J5", "01J6", "01J7", "01J8"} {
		seen[d.statusPK(StatusPlaced, id)] = true
	}
	if len(seen) < 2 {
		t.Fatalf("all orders landed on one GSI partition: %v", seen)
	}
}

Migration wrapper: dual write, backfill, shadow read, flip. Each phase is a value of Phase; failed secondary writes are queued for the backfill; shadow reads record mismatches without affecting the response:

go
// Package migrate moves the Ordering context from one store to another
// without a big-bang cutover: dual write, backfill, shadow read, then flip.
package migrate

import (
	"context"
	"errors"
	"reflect"
	"sync"

	"academy/sql-vs-nosql-decision/orders"
)

// Phase is where the migration stands. Each phase is a config flip, and
// each can be rolled back to the previous one.
type Phase int

const (
	OldOnly    Phase = iota // reads and writes on the old store
	DualWrite               // writes to both, reads from old
	ShadowRead              // writes to both, reads from old, new compared in the background
	NewPrimary              // writes to both, reads from new (old kept for rollback)
	NewOnly                 // old store retired
)

// Mismatch is recorded when the shadow read disagrees with the primary.
type Mismatch struct {
	CustomerID, OrderID string
	Reason              string
}

// Repo wraps two adapters behind the same port.
type Repo struct {
	Old, New orders.OrderRepository
	Phase    Phase

	mu         sync.Mutex
	Mismatches []Mismatch
	Pending    []orders.Order // secondary writes that failed; the backfill job retries them
}

var _ orders.OrderRepository = (*Repo)(nil)

func (r *Repo) primary() orders.OrderRepository {
	if r.Phase >= NewPrimary {
		return r.New
	}
	return r.Old
}

func (r *Repo) secondary() orders.OrderRepository {
	switch {
	case r.Phase == OldOnly || r.Phase == NewOnly:
		return nil
	case r.Phase >= NewPrimary:
		return r.Old
	default:
		return r.New
	}
}

// Save writes the primary first; only its result decides success. A failed
// secondary write is queued, never surfaced: dual write without a
// transaction across stores cannot be atomic, so it must be repairable.
func (r *Repo) Save(ctx context.Context, o orders.Order) error {
	if err := r.primary().Save(ctx, o); err != nil {
		return err
	}
	if sec := r.secondary(); sec != nil {
		if err := sec.Save(ctx, o); err != nil && !errors.Is(err, orders.ErrDuplicate) {
			r.mu.Lock()
			r.Pending = append(r.Pending, o)
			r.mu.Unlock()
		}
	}
	return nil
}

// Get serves from the primary; in ShadowRead it also reads the new store
// and records any difference. The caller never sees the shadow result.
func (r *Repo) Get(ctx context.Context, customerID, orderID string) (orders.Order, error) {
	o, err := r.primary().Get(ctx, customerID, orderID)
	if r.Phase == ShadowRead {
		so, serr := r.New.Get(ctx, customerID, orderID)
		switch {
		case errors.Is(err, orders.ErrNotFound) != errors.Is(serr, orders.ErrNotFound):
			r.record(customerID, orderID, "presence differs")
		case err == nil && serr == nil && !sameOrder(o, so):
			r.record(customerID, orderID, "content differs")
		}
	}
	return o, err
}

func (r *Repo) ListByCustomer(ctx context.Context, customerID string, limit int) ([]orders.Order, error) {
	return r.primary().ListByCustomer(ctx, customerID, limit)
}

func (r *Repo) ListByStatus(ctx context.Context, status orders.Status, limit int) ([]orders.Order, error) {
	return r.primary().ListByStatus(ctx, status, limit)
}

func (r *Repo) record(c, o, reason string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.Mismatches = append(r.Mismatches, Mismatch{CustomerID: c, OrderID: o, Reason: reason})
}

func sameOrder(a, b orders.Order) bool {
	return a.ID == b.ID && a.CustomerID == b.CustomerID && a.Status == b.Status &&
		a.TotalCents == b.TotalCents && a.CreatedAt.Equal(b.CreatedAt) && reflect.DeepEqual(a.Lines, b.Lines)
}

// Backfill copies historical orders (from a snapshot or an export of the
// old store) into the new one. It is idempotent: ErrDuplicate means the
// dual write already copied that order.
func Backfill(ctx context.Context, history []orders.Order, dst orders.OrderRepository) (copied, skipped int, err error) {
	for _, o := range history {
		switch e := dst.Save(ctx, o); {
		case e == nil:
			copied++
		case errors.Is(e, orders.ErrDuplicate):
			skipped++
		default:
			return copied, skipped, e
		}
	}
	return copied, skipped, nil
}
go
package migrate

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/sql-vs-nosql-decision/orders"
)

type flaky struct {
	orders.OrderRepository
	fail bool
}

func (f *flaky) Save(ctx context.Context, o orders.Order) error {
	if f.fail {
		return errors.New("new store unavailable")
	}
	return f.OrderRepository.Save(ctx, o)
}

func order(id string) orders.Order {
	return orders.Order{ID: id, CustomerID: "c-1", Status: orders.StatusPlaced,
		Lines: []orders.Line{{SKU: "a", Quantity: 1, PriceCents: 100}}, TotalCents: 100,
		CreatedAt: time.Date(2026, 11, 26, 0, 0, 0, 0, time.UTC)}
}

func TestMigrationPhases(t *testing.T) {
	ctx := context.Background()
	oldRepo, newMem := orders.NewMemory(), orders.NewMemory()
	newRepo := &flaky{OrderRepository: newMem}
	r := &Repo{Old: oldRepo, New: newRepo, Phase: OldOnly}

	// History written before the migration exists only in the old store.
	_ = r.Save(ctx, order("01A"))

	r.Phase = DualWrite
	_ = r.Save(ctx, order("01B"))
	newRepo.fail = true
	if err := r.Save(ctx, order("01C")); err != nil {
		t.Fatalf("a failed secondary write must not fail the request: %v", err)
	}
	newRepo.fail = false
	if len(r.Pending) != 1 {
		t.Fatalf("want 1 pending repair, got %d", len(r.Pending))
	}

	// Backfill the history plus the pending repairs; 01B is skipped as a duplicate.
	copied, skipped, err := Backfill(ctx, append([]orders.Order{order("01A"), order("01B")}, r.Pending...), newRepo)
	if err != nil || copied != 2 || skipped != 1 {
		t.Fatalf("backfill copied=%d skipped=%d err=%v", copied, skipped, err)
	}

	r.Phase = ShadowRead
	for _, id := range []string{"01A", "01B", "01C"} {
		if _, err := r.Get(ctx, "c-1", id); err != nil {
			t.Fatal(err)
		}
	}
	if len(r.Mismatches) != 0 {
		t.Fatalf("stores should agree after backfill: %+v", r.Mismatches)
	}

	// A write that reached only the old store is caught by the shadow read.
	_ = oldRepo.Save(ctx, order("01D"))
	if _, err := r.Get(ctx, "c-1", "01D"); err != nil {
		t.Fatal(err)
	}
	if len(r.Mismatches) != 1 || r.Mismatches[0].Reason != "presence differs" {
		t.Fatalf("want one presence mismatch, got %+v", r.Mismatches)
	}

	r.Phase = NewPrimary
	if _, err := r.Get(ctx, "c-1", "01D"); !errors.Is(err, orders.ErrNotFound) {
		t.Fatalf("after the flip reads come from the new store: %v", err)
	}
}

Sizing from the access-pattern table (output in Mechanics):

go
// Command sizing turns an access-pattern table into DynamoDB capacity
// units and a per-key ceiling, using the unit sizes and per-partition
// limits from the DynamoDB Developer Guide (4 KB read unit, 1 KB write
// unit, 3,000 RCU and 1,000 WCU per partition). Run: go run ./sizing
package main

import (
	"fmt"
	"math"
)

type pattern struct {
	name      string
	perSecond float64 // peak operations per second
	itemKB    float64 // bytes touched per operation, in KB
	write     bool
	strong    bool // strongly consistent read (base table only)
	items     float64
}

const (
	readUnitKB, writeUnitKB = 4.0, 1.0
	partitionRCU            = 3000.0
	partitionWCU            = 1000.0
)

func units(p pattern) float64 {
	if p.write {
		return math.Ceil(p.itemKB/writeUnitKB) * p.items
	}
	u := math.Ceil(p.itemKB/readUnitKB) * p.items
	if !p.strong {
		u /= 2 // eventually consistent reads cost half
	}
	return u
}

func main() {
	ps := []pattern{
		{name: "AP1 place order (2 KB item + 2 KB GSI copy)", perSecond: 200, itemKB: 2, write: true, items: 2},
		{name: "AP2 get order, strong", perSecond: 1500, itemKB: 2, strong: true, items: 1},
		{name: "AP3 latest 20 orders, eventual", perSecond: 400, itemKB: 40, items: 1},
		{name: "AP4 PLACED feed on GSI, eventual", perSecond: 20, itemKB: 100, items: 1},
	}
	var rcu, wcu float64
	fmt.Printf("%-46s %8s %10s\n", "access pattern", "units/op", "units/s")
	for _, p := range ps {
		u := units(p)
		fmt.Printf("%-46s %8.1f %10.0f\n", p.name, u, u*p.perSecond)
		if p.write {
			wcu += u * p.perSecond
		} else {
			rcu += u * p.perSecond
		}
	}
	fmt.Printf("total: %.0f RCU/s, %.0f WCU/s\n", rcu, wcu)
	fmt.Printf("partitions needed for throughput alone: %.0f\n", math.Ceil(math.Max(rcu/partitionRCU, wcu/partitionWCU)))
	// One hot key (a celebrity customer, one status value) is capped by a
	// single partition no matter how big the table is.
	fmt.Printf("max strong 2 KB reads/s on ONE key: %.0f\n", partitionRCU/math.Ceil(2/readUnitKB))
	fmt.Printf("max 2 KB writes/s on ONE key: %.0f\n", partitionWCU/math.Ceil(2/writeUnitKB))
	// Storage, for the relational-vs-NoSQL "scale ceiling" question.
	ordersPerDay, kb := 200000.0, 2.0
	fmt.Printf("orders storage per year: %.0f GB\n", ordersPerDay*365*kb/1024/1024)
}

The Go angle ​

Go packageUse hereNote
github.com/jackc/pgx/v5pgx.BeginFunc, pgx.CollectRows, array parametersNative PostgreSQL protocol; pgx.Tx and *pgxpool.Pool share the Begin/Query methods the adapter needs
github.com/jackc/pgx/v5/pgxpoolpgxpool.New(ctx, dsn)One pool per process; see Connection Pooling
github.com/jackc/pgx/v5/pgconn*pgconn.PgError and .CodeBranch on SQLSTATE, never on message text
github.com/aws/aws-sdk-go-v2/service/dynamodbPutItem, GetItem, Query, NewScanPaginatorAccept an interface with the SDK's method signatures for tests
github.com/aws/aws-sdk-go-v2/service/dynamodb/typesAttributeValueMemberS, ConditionalCheckFailedExceptionTyped errors with errors.As
github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalueMarshalMap, UnmarshalMap, UnmarshalListOfMapsStruct tags dynamodbav
go.mongodb.org/mongo-driver/v2Would be the MongoDB adapterSame port, same contract suite
github.com/redis/go-redis/v9Cart adapter in GoTxPipelined for MULTI/EXEC
hash/fnvGSI write shardingStable, cheap hash for the shard suffix

Laravel ​

Before ​

Redis was chosen as "the fast database" and became the only store for orders. The total is a float in a hash, nothing is transactional, and a restart between snapshots loses orders.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

// Before: Redis was chosen as "the fast database" and became the only
// store. The order total is a float in a hash, there is no transaction
// with stock, no constraint, and no history if the instance restarts
// between snapshots.
class CheckoutBeforeController
{
    public function __invoke(Request $request)
    {
        $customerId = (string) $request->user()->id;
        $cart = Redis::hgetall("cart:{$customerId}");

        $total = 0.0;
        foreach ($cart as $sku => $qty) {
            $total += (float) Redis::get("price:{$sku}") * (int) $qty; // float money
        }

        $orderId = (string) Redis::incr('order:seq');
        Redis::hmset("order:{$orderId}", [
            'customer' => $customerId,
            'total' => $total,          // the only copy of what the customer owes
            'status' => 'PLACED',
        ]);
        Redis::del("cart:{$customerId}");

        return response()->json(['order_id' => $orderId, 'total' => $total], 201);
    }
}

After ​

One connection per bounded context. Ordering on PostgreSQL, Catalog on MongoDB through mongodb/laravel-mongodb (the official package; version 5.12.2 on Packagist requires illuminate/support ^12|^13.0, so it supports Laravel 13), carts on their own Redis database:

php
<?php

use Illuminate\Support\Str;

// config/database.php (excerpt): one connection per bounded context and
// workload. Ordering owns PostgreSQL, Catalog owns MongoDB, the cart and
// sessions use a Redis connection that is allowed to lose data.
return [

    'default' => env('DB_CONNECTION', 'orders'),

    'connections' => [

        // System of record for money: constraints, transactions, ad-hoc SQL.
        'orders' => [
            'driver' => 'pgsql',
            'url' => env('ORDERS_DB_URL'),
            'host' => env('ORDERS_DB_HOST', '127.0.0.1'),
            'port' => env('ORDERS_DB_PORT', '5432'),
            'database' => env('ORDERS_DB_DATABASE', 'orders'),
            'username' => env('ORDERS_DB_USERNAME', 'orders_app'),
            'password' => env('ORDERS_DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => env('ORDERS_DB_SSLMODE', 'prefer'),
        ],

        // Catalog documents: variable attributes per product type, read whole.
        // Driver provided by mongodb/laravel-mongodb (MongoDB\Laravel\MongoDBServiceProvider).
        'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => env('CATALOG_MONGODB_URI', 'mongodb://127.0.0.1:27017'),
            'database' => env('CATALOG_MONGODB_DATABASE', 'catalog'),
        ],
    ],

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        // Carts: a separate logical database so a FLUSHDB on the cache
        // connection cannot take carts with it.
        'cart' => [
            'url' => env('REDIS_CART_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CART_DB', '2'),
        ],
    ],
];

The Ordering schema on its own connection ($connection = 'orders' on the migration), with constraints the schema builder cannot express added as SQL:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    // Runs on the Ordering context's own connection.
    protected $connection = 'orders';

    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->string('id', 26)->primary();          // ULID: time-sortable
            $table->string('customer_id');
            $table->string('status', 16);
            $table->bigInteger('total_cents');
            $table->timestampTz('created_at')->useCurrent();
            $table->index(['customer_id', 'id']);          // AP3
        });

        Schema::create('order_lines', function (Blueprint $table) {
            $table->string('order_id', 26);
            $table->integer('line_no');
            $table->string('sku');
            $table->integer('quantity');
            $table->bigInteger('price_cents');
            $table->primary(['order_id', 'line_no']);
            $table->foreign('order_id')->references('id')->on('orders')->cascadeOnDelete();
        });

        Schema::create('outbox', function (Blueprint $table) {
            $table->id();
            $table->string('aggregate_id');
            $table->string('event_type');
            $table->jsonb('payload');
            $table->timestampTz('created_at')->useCurrent();
        });

        // Constraints the schema builder does not express are plain SQL.
        DB::connection($this->connection)->statement(
            "ALTER TABLE orders ADD CONSTRAINT orders_status_chk CHECK (status IN ('PLACED','PAID','SHIPPED'))"
        );
        DB::connection($this->connection)->statement(
            'ALTER TABLE order_lines ADD CONSTRAINT order_lines_qty_chk CHECK (quantity > 0)'
        );
        DB::connection($this->connection)->statement(
            "CREATE INDEX orders_placed ON orders (id DESC) WHERE status = 'PLACED'"   // AP4
        );
    }

    public function down(): void
    {
        Schema::dropIfExists('outbox');
        Schema::dropIfExists('order_lines');
        Schema::dropIfExists('orders');
    }
};

Eloquent models and the repository port. DB::connection('orders')->transaction() holds the order, lines and outbox row together; UniqueConstraintViolationException turns a retry into a read:

php
<?php

namespace App\Ordering;

use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Order extends Model
{
    use HasUlids;

    // The Ordering context's own PostgreSQL connection.
    protected $connection = 'orders';

    public $timestamps = false;

    protected $fillable = ['id', 'customer_id', 'status', 'total_cents', 'created_at'];

    protected function casts(): array
    {
        return [
            'total_cents' => 'integer',
            'created_at' => 'immutable_datetime',
        ];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class, 'order_id')->orderBy('line_no');
    }
}
php
<?php

namespace App\Ordering;

use Illuminate\Database\Eloquent\Model;

class OrderLine extends Model
{
    protected $connection = 'orders';

    protected $table = 'order_lines';

    public $incrementing = false;

    public $timestamps = false;

    protected $primaryKey = null;

    protected $fillable = ['order_id', 'line_no', 'sku', 'quantity', 'price_cents'];
}
php
<?php

namespace App\Ordering;

use Illuminate\Support\Collection;

// The port. Each method is one access pattern (AP1-AP4 in the chapter);
// controllers and jobs depend on this interface, never on a connection.
interface OrderRepository
{
    /** @param list<array{sku: string, quantity: int, price_cents: int}> $lines */
    public function place(string $orderId, string $customerId, array $lines): Order;

    public function find(string $customerId, string $orderId): ?Order;

    /** @return Collection<int, Order> */
    public function latestForCustomer(string $customerId, int $limit = 20): Collection;

    /** @return Collection<int, Order> */
    public function placedFeed(int $limit = 100): Collection;
}
php
<?php

namespace App\Ordering;

use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class EloquentOrderRepository implements OrderRepository
{
    public function place(string $orderId, string $customerId, array $lines): Order
    {
        try {
            return DB::connection('orders')->transaction(function () use ($orderId, $customerId, $lines) {
                $total = array_sum(array_map(fn (array $l) => $l['quantity'] * $l['price_cents'], $lines));

                $order = Order::create([
                    'id' => $orderId,
                    'customer_id' => $customerId,
                    'status' => 'PLACED',
                    'total_cents' => $total,
                    'created_at' => now(),
                ]);

                foreach (array_values($lines) as $i => $line) {
                    $order->lines()->create($line + ['line_no' => $i + 1]);
                }

                // Same transaction as the order: the relay publishes it to
                // search, analytics and cache invalidation (see the outbox chapter).
                DB::connection('orders')->table('outbox')->insert([
                    'aggregate_id' => $orderId,
                    'event_type' => 'OrderPlaced',
                    'payload' => json_encode(['order_id' => $orderId, 'customer_id' => $customerId, 'total_cents' => $total]),
                ]);

                return $order->load('lines');
            });
        } catch (UniqueConstraintViolationException) {
            // A retried request with the same order ID: return the first result.
            return $this->find($customerId, $orderId) ?? throw new \RuntimeException("order {$orderId} belongs to another customer");
        }
    }

    public function find(string $customerId, string $orderId): ?Order
    {
        return Order::with('lines')->where('customer_id', $customerId)->find($orderId);
    }

    public function latestForCustomer(string $customerId, int $limit = 20): Collection
    {
        return Order::with('lines')
            ->where('customer_id', $customerId)
            ->orderByDesc('id')
            ->limit($limit)
            ->get();
    }

    public function placedFeed(int $limit = 100): Collection
    {
        return Order::where('status', 'PLACED')->orderByDesc('id')->limit($limit)->get();
    }
}

The Catalog on MongoDB. MongoDB\Laravel\Eloquent\Model with embedded variants and attributes, a dot-notation filter, and the aggregation builder (Product::aggregate()->match()->group()):

php
<?php

namespace App\Catalog;

use MongoDB\Laravel\Eloquent\Model;

// Catalog context: one document per product, variants and attributes
// embedded because they are read with the product, change with it and
// are bounded (tens, not millions). Reviews are NOT embedded: unbounded,
// written at different times, so they live in their own collection.
class Product extends Model
{
    protected $connection = 'mongodb';

    protected $table = 'products';

    protected $fillable = ['sku', 'name', 'type', 'price_cents', 'attributes', 'variants'];

    protected function casts(): array
    {
        return [
            'price_cents' => 'integer',
            'attributes' => 'array',
            'variants' => 'array',
        ];
    }
}
php
<?php

namespace App\Catalog;

use Illuminate\Support\Collection;
use MongoDB\Builder\Accumulator;
use MongoDB\Builder\Expression;
use MongoDB\Builder\Query;

class CatalogQueries
{
    // A point lookup by SKU and a filter on an embedded attribute (dot notation).
    public function bySku(string $sku): ?Product
    {
        return Product::where('sku', $sku)->first();
    }

    /** @return Collection<int, Product> */
    public function laptopsWithRam(int $minGb): Collection
    {
        return Product::where('type', 'laptop')
            ->where('attributes.ram_gb', '>=', $minGb)
            ->orderBy('price_cents')
            ->limit(50)
            ->get();
    }

    // Aggregation pipeline through the Laravel MongoDB aggregation builder:
    // product count and average price per type.
    public function pricePerType(): Collection
    {
        return Product::aggregate()
            ->match(price_cents: Query::gte(1))
            ->group(
                _id: Expression::fieldPath('type'),
                products: Accumulator::sum(1),
                avg_price_cents: Accumulator::avg(Expression::numberFieldPath('price_cents')),
            )
            ->get();
    }
}

The cart on Redis with Redis::connection('cart')->transaction() (MULTI/EXEC) and a hash tag for Redis Cluster:

php
<?php

namespace App\Cart;

use Illuminate\Support\Facades\Redis;

// Cart context: Redis as the primary store for data the business accepts
// losing (a few seconds with appendfsync everysec). Money never lives here:
// at checkout the prices come from the Catalog and the total is written
// to the Ordering database.
class RedisCartStore
{
    private const TTL_SECONDS = 7 * 24 * 3600;

    public function add(string $customerId, string $sku, int $quantity): void
    {
        $key = $this->key($customerId);

        // MULTI/EXEC: the increment and the TTL refresh apply together.
        Redis::connection('cart')->transaction(function ($redis) use ($key, $sku, $quantity) {
            $redis->hincrby($key, $sku, $quantity);
            $redis->expire($key, self::TTL_SECONDS);
        });
    }

    /** @return array<string, int> sku => quantity */
    public function items(string $customerId): array
    {
        $raw = Redis::connection('cart')->hgetall($this->key($customerId));

        return array_filter(array_map('intval', $raw), fn (int $q) => $q > 0);
    }

    public function clear(string $customerId): void
    {
        Redis::connection('cart')->del($this->key($customerId));
    }

    private function key(string $customerId): string
    {
        // Hash tag keeps one customer's keys on one Redis Cluster slot.
        return "cart:{{$customerId}}";
    }
}

Wiring and the checkout flow across three stores:

php
<?php

namespace App\Providers;

use App\Ordering\EloquentOrderRepository;
use App\Ordering\OrderRepository;
use Illuminate\Support\ServiceProvider;

// Register in bootstrap/providers.php next to
// MongoDB\Laravel\MongoDBServiceProvider::class.
class PersistenceServiceProvider extends ServiceProvider
{
    public array $singletons = [
        OrderRepository::class => EloquentOrderRepository::class,
    ];
}
php
<?php

namespace App\Http\Controllers;

use App\Cart\RedisCartStore;
use App\Catalog\CatalogQueries;
use App\Ordering\OrderRepository;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

// After: three stores, three owners, one flow. Redis holds the cart,
// MongoDB prices it, PostgreSQL records the order (and its outbox event)
// in one transaction. The client sends an order ID so a retry is safe.
class CheckoutController
{
    public function __construct(
        private RedisCartStore $cart,
        private CatalogQueries $catalog,
        private OrderRepository $orders,
    ) {}

    public function __invoke(Request $request): JsonResponse
    {
        $customerId = (string) $request->user()->id;
        $orderId = (string) $request->input('order_id', (string) Str::ulid());

        $lines = [];
        foreach ($this->cart->items($customerId) as $sku => $quantity) {
            $product = $this->catalog->bySku($sku) ?? abort(422, "unknown sku {$sku}");
            $lines[] = ['sku' => $sku, 'quantity' => $quantity, 'price_cents' => $product->price_cents];
        }
        abort_if($lines === [], 422, 'empty cart');

        $order = $this->orders->place($orderId, $customerId, $lines);
        $this->cart->clear($customerId);   // losing this step only leaves a stale cart

        return response()->json([
            'order_id' => $order->id,
            'total_cents' => $order->total_cents,
        ], 201);
    }
}

The Laravel angle ​

Laravel 13 featureUseNote
config/database.php connectionsOne named connection per context (orders, mongodb)Models set protected $connection
DB::connection('orders')->transaction()Atomic order + lines + outboxTransactions never span connections
Schema in a migration with $connectionMigrations per contextRun per database in CI
HasUlidsTime-sortable string keysMatches the Go ULID-style IDs and the id DESC index
Illuminate\Database\UniqueConstraintViolationExceptionIdempotent createCatch it, then read the existing row
Redis::connection('cart')A dedicated logical database for cartsSeparate from the cache connection
Redis::transaction(fn ($redis) => ...)MULTI/EXEC blockNot a rollback-capable transaction
mongodb/laravel-mongodbdriver => 'mongodb', MongoDB\Laravel\Eloquent\Model, embedsMany, aggregation builderRegister MongoDB\Laravel\MongoDBServiceProvider; transactions need a replica set
$singletons on a service providerBind the port to the Eloquent adapterSwap the adapter during a migration
Cache and session driversredis, database, dynamodbDynamoDB is supported for cache and sessions, not as an Eloquent connection

Solving the classic problems ​

"We chose NoSQL for scale" and now need a report ​

text
     Month   Event
1    0       Team picks DynamoDB "because it scales"; designs keys for 4 access patterns
2    4       Product asks for "orders by region and promo code, last quarter"
3    4       Only answer on the request path: Scan + FilterExpression -> reads the whole table, slow, billed per item
4    5       Fix: DynamoDB Streams / export to S3 -> analytics store; or move Ordering to PostgreSQL
SolutionHowAdvantageCost
Stream to an analytics storeDynamoDB Streams or export to S3, then ClickHouse / AthenaNo change to the OLTP designSecond store, lag
New GSI per new patternAdd GSI, backfill attributesStays in DynamoDBWrite cost per GSI; 20 per table
Move the context to PostgreSQLMigration phases aboveAd-hoc SQL foreverA migration project
Avoid next timeWrite the access patterns; if unstable, start relationalCheapestRequires discipline up front
sql
-- What the report is in the relational design: one query, on a replica.
SELECT c.region, o.promo_code, count(*) AS orders, sum(o.total_cents) / 100.0 AS revenue
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= date_trunc('quarter', now()) - interval '3 months'
  AND o.created_at <  date_trunc('quarter', now())
GROUP BY c.region, o.promo_code
ORDER BY revenue DESC;

Redis as the only store for money ​

SolutionHowAdvantageCost
System of record in PostgreSQLOrders and balances in SQL with constraints; Redis only cachesDurable, auditableOne more store if you had only Redis
Redis as a write bufferAccept in Redis, flush to SQL in batchesAbsorbs spikesLoss window equals the flush interval plus fsync
Durable Redis-compatible serviceAmazon MemoryDB keeps a multi-AZ transaction logRedis API with durabilityHigher write latency and cost
Ledger patternAppend-only entries, balance derivedReconstructableMore rows

The Laravel After code is the fix: the cart stays in Redis (losing it costs a re-add), the price comes from the Catalog, and the total is computed and stored in PostgreSQL in the same transaction as the outbox event.

JSONB as a schema-less excuse ​

sql
-- Smell: everything in one document, nothing enforced, every query a JSON path.
CREATE TABLE orders_blob (id bigserial PRIMARY KEY, doc jsonb);
SELECT doc FROM orders_blob WHERE doc ->> 'customer' = '42';  -- no index, no type, no FK

-- Fix: typed columns for what you filter, join, sum or constrain; JSONB for the long tail.
ALTER TABLE products
  ADD CONSTRAINT products_attributes_shape
  CHECK (jsonb_path_exists(attributes, '$.brand') OR attributes = '{}'::jsonb);

-- Containment query served by the jsonb_path_ops GIN index:
SELECT sku, name FROM products WHERE attributes @> '{"color": "red", "size": 42}';

-- A field queried on every listing page becomes a generated, indexed column:
SELECT sku, name FROM products WHERE brand = 'Acme' ORDER BY price_cents LIMIT 20;
SolutionWhen
Typed columns + FK + CHECKAnything in a join, sum, uniqueness rule or report
JSONB with CHECK (jsonb_typeof(...) = 'object')Varying attributes, third-party payloads
Generated column + B-tree indexOne JSON field queried often
GIN jsonb_path_opsContainment (@>) filters on many keys

A hot partition in DynamoDB ​

SolutionHowAdvantageCost
Write shardingSuffix #0..N-1 on a low-cardinality keySpreads writes over N partitionsReads fan out N ways
Higher-cardinality keyKey by order ID, not statusNo fan-outNeed a GSI for the other path
Cache in front of hot readsDAX or Redis for a celebrity itemAbsorbs read spikesStaleness
Batch or bufferAggregate increments before writingFewer writesDelay (Write Buffering)

The adapter's statusPK and ListByStatus are the write-sharding fix; TestStatusKeySpreadsOverShards checks that eight orders do not land on one key.

SolutionHowAdvantageCost
PostgreSQL FTS + GINtsvector column, websearch_to_tsqueryNo new storeBasic ranking
OpenSearch via outbox/CDCOutbox row in the order transaction, Debezium to Kafka, idempotent indexerRelevance, facetsSecond store, lag, rebuild job
Managed search on the document storeMongoDB Atlas SearchOne vendorLock-in

Too many stores ​

SolutionHowAdvantageCost
Store inventory with ownersOne row per store: owner, purpose, access patterns, on-callVisibilityAn hour of work
Consolidate into PostgreSQLJSONB, pgvector, TimescaleDB, FTS replace small storesFewer moving partsLess headroom per feature
Retire by migrationPhases above, in reverseSafeTime

Choosing ​

Decision table by workload ​

WorkloadRecommended storeExtra techniqueReason
Orders, payments, ledgers, inventoryPostgreSQL (or MySQL)Constraints, outbox, idempotency keysMulti-entity invariants and audits
Same, multi-region writes or beyond one primarySpanner, CockroachDB, YugabyteDBRegion-aware partitioningSQL invariants plus horizontal writes
Product catalogue with varying attributesPostgreSQL JSONB, or MongoDB if aggregates are read whole and owned by one teamGenerated columns or $jsonSchemaSchema volatility
Carts, sessions, rate-limit countersRedis (store mode) or DynamoDBTTLs, noeviction for storesSmall, hot, loss-tolerant or key-addressed
User profiles at very large scale, known patternsDynamoDB or CassandraSingle-table design, GSIsPredictable latency at any size
Chat messages, activity feedsCassandra / ScyllaDB or DynamoDBPartition per channel and time bucketRange scans on one key, high write rate (Feeds)
Product or content searchElasticsearch / OpenSearchCDC-fed, alias reindexRelevance and facets
Metrics, IoT telemetryTimescaleDB, InfluxDB, ClickHouseRetention, downsamplingAppend-heavy, time-window aggregates
Analytics and BIClickHouse, a warehouseCDC from OLTPColumnar scans
Fraud rings, recommendations by pathsNeo4j (derived)Fed from OLTPVariable-depth traversals
Semantic search, RAGpgvector firstHNSW index, filters in SQLVectors next to relational filters
Unknown load, previews, dev branchesNeon, Aurora Serverless, DynamoDB on-demandBudgets and alarmsPay per use
Cache in front of anythingRedisCache-aside, TTL, allkeys-lru (Caching)Latency and load shedding

SQL vs NoSQL in one table ​

Choose relational whenChoose a NoSQL family when
Access patterns are many, evolving or unknownAccess patterns are few, stable and known
Invariants span entities (money, stock, bookings)Each operation touches one aggregate or one key
You need ad-hoc queries and reports on live dataReports go to an analytics store anyway
One primary can carry the writes for the next 2 to 3 yearsWrite rate or data size is beyond a large primary, or needs many regions
The team knows SQL and the ORMThe team knows the NoSQL modelling method (single-table, embedding rules)
You want low lock-inYou accept the vendor API in exchange for operations you do not run

Worked example 1: e-commerce (catalogue, orders, carts, search) ​

text
     Context    Patterns (peak)                                   Store                 Why
1    Ordering   place 200 w/s; get 1,500 r/s; list 400 r/s        PostgreSQL            money, FKs, ad-hoc, 139 GB/year
2    Catalog    get product 5,000 r/s; edit 5 w/s; attrs vary     MongoDB or PG JSONB   aggregate read whole; volatile attributes
3    Cart       add item 300 w/s; read cart 1,000 r/s; TTL 7 d     Redis (AOF everysec)  hot, small, loss of 1 s acceptable
4    Search     queries 800 r/s; facets; typeahead               OpenSearch            relevance; fed by CDC from Catalog
5    Analytics  hourly revenue, funnels                           ClickHouse            columnar; fed by CDC from Ordering

One owner per store, no context reads another's tables, CDC/outbox for everything derived. With a two-person team, the Catalog goes to PostgreSQL JSONB and Search to PostgreSQL FTS until the numbers say otherwise: two stores (PostgreSQL, Redis) instead of five.

Worked example 2: IoT telemetry ​

text
     Fact                                   Estimate (back-of-envelope)
1    50,000 devices x 1 reading / 2 s        25,000 writes/s, all day
2    100 bytes per reading                   ~2.2 GB/day raw, ~0.8 TB/year before compression
3    Queries                                 last hour per device (range on one key); hourly averages per site (aggregate)
4    Device registry                         50,000 rows, relational, joins with customers and sites

Telemetry goes to TimescaleDB (hypertables, compression, continuous aggregates, joins with the registry in one PostgreSQL) or ClickHouse if analytical scans dominate; InfluxDB if the team wants a purpose-built metrics store. The device registry and billing stay relational. Redis holds the latest reading per device for dashboards.

Worked example 3: social graph ​

text
     Pattern                                         Shape                    Store
1    Follow / unfollow, 2,000 w/s                     write to two adjacency lists   Cassandra or DynamoDB (followers, following)
2    "Do I follow X?" 50,000 r/s                       point lookup             same table, or Redis set
3    Home timeline                                     range on one key         precomputed feed per user ([Feeds](/system-design/feeds-fanout-fanin))
4    "People you may know" (2 to 3 hops)               graph traversal          Neo4j or an offline job, derived
5    Profiles, settings, billing                       relational                PostgreSQL

Adjacency lists for one-hop questions belong in a key-value or wide-column store; multi-hop recommendations run on a derived graph or as a batch job; the account system stays relational.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Laravel or Go application, one PostgreSQL. The database decision here is mostly "PostgreSQL, and which features of it": JSONB for the catalogue's attributes, FTS for search, a jobs table or Redis for queues, Redis for cache and sessions. Write the access-pattern table anyway and keep it in the repository; it is the input for every later decision. Put data access behind repositories even in a monolith so a later move is an adapter change.

Modular monolith: boundaries without the network ​

Each module owns its tables (schemas ordering, catalog, cart in one PostgreSQL), and modules never join across them; they call each other's interfaces or read their published events. This is where polyglot persistence becomes possible without being required: the Catalog module can move to MongoDB later because nobody else touches its tables. Laravel makes this concrete with one connection name per module even when they point at the same server (Modular Monolith).

Microservices: one owner per store ​

Each service owns its database; others get its data through APIs or events (Database per Service). The checkout flow becomes: Cart service (Redis) → Catalog service (MongoDB) for prices → Ordering service (PostgreSQL) writes the order and the outbox row in one transaction → relay publishes OrderPlaced to Kafka → Search and Analytics consumers update their stores idempotently (Idempotent Consumers). What does not survive the boundary: joins, foreign keys and transactions across services. Invariants that span services become sagas (Saga).

Distributed data: replicas, caches, regions ​

Read replicas lag, so read-your-writes patterns (AP2 right after AP1) go to the primary or use a session token (Replication Topologies). DynamoDB GSIs, search indexes and caches are all eventually consistent copies; the UI must tolerate seconds of staleness on those paths. Multi-region writes force a choice: a single-writer region with replicas elsewhere, a multi-leader or leaderless design with conflict resolution (DynamoDB global tables, Cassandra), or distributed SQL with consensus across regions and its latency per write (CAP & PACELC).

Scaling path: 1x, 10x, 100x ​

LoadTypical design
1xPostgreSQL primary + replica; Redis cache/sessions; everything else as PostgreSQL features
10xBigger primary, more replicas, connection pooling, partitioning of the largest tables; search and analytics moved out via CDC
100xShard the write-heavy context (Citus, Vitess) or move it to distributed SQL or a key-value store with a single-table design; hot-key reviews; per-context stores

Lab: model the queries, size them, prove the port ​

1. Size the access patterns (run on this machine; small single-process Go program):

bash
cd docs/snippets/system-design/sql-vs-nosql-decision/go
go run ./sizing
# access pattern                                 units/op    units/s
# AP1 place order (2 KB item + 2 KB GSI copy)         4.0        800
# AP2 get order, strong                               1.0       1500
# AP3 latest 20 orders, eventual                      5.0       2000
# AP4 PLACED feed on GSI, eventual                   12.5        250
# total: 3750 RCU/s, 800 WCU/s
# partitions needed for throughput alone: 2
# max strong 2 KB reads/s on ONE key: 3000
# max 2 KB writes/s on ONE key: 500
# orders storage per year: 139 GB

2. Run the contract suite against the fake DynamoDB and the in-memory adapter (run on this machine):

bash
go test ./... 
# ok   academy/sql-vs-nosql-decision/migrate
# ok   academy/sql-vs-nosql-decision/orders
# TestPostgresContract is skipped unless ORDERS_PG_DSN is set

3. Run the same suite against PostgreSQL (expected, not run):

bash
createdb orders_test
psql orders_test -f ../sql/schema.sql
ORDERS_PG_DSN=postgres://app:app@localhost:5432/orders_test go test ./orders -run Postgres -v
# --- PASS: TestPostgresContract (0.05s)
#     --- PASS: TestPostgresContract/AP1_place_is_idempotent_on_order_id
#     --- PASS: TestPostgresContract/AP2_get_returns_lines;_missing_is_ErrNotFound
#     --- PASS: TestPostgresContract/AP3_and_AP4_newest_first_with_limit
#     --- PASS: TestPostgresContract/invalid_order_never_reaches_the_store

4. See which index serves which pattern (expected, not run):

sql
EXPLAIN SELECT id FROM orders WHERE customer_id = 'c-42' ORDER BY id DESC LIMIT 20;
-- Limit -> Index Only Scan using orders_customer_recent on orders
EXPLAIN SELECT id FROM orders WHERE status = 'PLACED' ORDER BY id DESC LIMIT 100;
-- Limit -> Index Scan using orders_placed on orders
INSERT INTO products (sku, name, price_cents, attributes) VALUES ('p1', 'Lamp', 1999, '[1,2]');
-- ERROR:  new row for relation "products" violates check constraint "products_attributes_check"

5. Watch Redis lose (or not lose) a second of writes (expected, not run, on a scratch Redis):

bash
redis-cli CONFIG SET appendonly yes
redis-cli CONFIG SET appendfsync everysec
redis-cli CONFIG GET maxmemory-policy
# 1) "maxmemory-policy"
# 2) "noeviction"
redis-cli HINCRBY "cart:{42}" sku-9 1
redis-cli INFO persistence | grep -E "aof_enabled|aof_last_write_status"
# aof_enabled:1
# aof_last_write_status:ok

6. Feel the cost of an unmodelled query on DynamoDB (expected, not run, against DynamoDB Local or a sandbox account):

bash
aws dynamodb scan --table-name orders --filter-expression "customer_id = :c" \
  --expression-attribute-values '{":c":{"S":"c-42"}}' --return-consumed-capacity TOTAL
# "Count": 3, "ScannedCount": 120000, "ConsumedCapacity": {"CapacityUnits": 1450.5}
aws dynamodb query --table-name ordering --key-condition-expression "PK = :pk AND begins_with(SK, :p)" \
  --expression-attribute-values '{":pk":{"S":"CUST#c-42"},":p":{"S":"ORDER#"}}' --no-scan-index-forward \
  --return-consumed-capacity TOTAL
# "Count": 3, "ScannedCount": 3, "ConsumedCapacity": {"CapacityUnits": 0.5}

Common misconceptions ​

BeliefReality
NoSQL scales, SQL does notA single PostgreSQL primary carries most workloads; distributed SQL scales SQL out; NoSQL gives predictable performance for designed queries
Schemaless means no schemaThe schema moves into every reader; MongoDB and PostgreSQL docs both recommend predictable structure
MongoDB means embed everythingReference unbounded, independently written or high-cardinality children
DynamoDB needs one table per entityThe guide recommends as few tables as possible; single-table design co-locates entities
A GSI gives strongly consistent readsDynamoDB GSIs support eventually consistent reads only
Redis persistence makes it as safe as PostgreSQLeverysec can lose about a second; RDB alone can lose minutes
JSONB means we do not need columnsFilter, join, sum and constrain on typed columns; JSONB for the long tail
Distributed SQL is free scalingEach write is a consensus round; regions add latency
Polyglot persistence means many databasesIt means the right store per workload, each with one owner, and as few as possible
Dual write in the request is enough to migratePartial failures diverge the stores; queue, reconcile or use CDC
Serverless is always cheaperSteady high load is often cheaper provisioned; scale-from-zero adds cold starts
Search engines can be the source of truthThey are derived, near-real-time indexes you must be able to rebuild
Graph data needs a graph databaseOne or two hops are joins; graph stores pay off for deep variable traversals

Cheat sheet ​

TopicRemember
First stepAccess-pattern table: name, shape, QPS, consistency, SLO
DefaultPostgreSQL unless a requirement rules it out
Relational strengthsJoins, constraints, foreign keys, transactions, ad-hoc queries, tooling
Document ruleEmbed bounded and read-together data; reference unbounded data; 16 MiB limit
DynamoDB ruleKnow the questions first; few tables; PK + SK + GSIs; no Scan on request paths
DynamoDB numbers4 KB read unit, 1 KB write unit, 3,000 RCU / 1,000 WCU per partition, 400 KB item, 100-item transactions
Redis as storeAOF everysec (about 1 s loss), RDB snapshots, noeviction, replicas; never the only copy of money
Redis vs DynamoDBRedis for hot, small, sub-millisecond; DynamoDB for durable key-addressed records at any size
SearchElasticsearch/OpenSearch as a derived index fed by CDC
Time seriesTimescaleDB, InfluxDB, ClickHouse; retention and downsampling
Vectorspgvector first
Distributed SQLSpanner, CockroachDB, YugabyteDB; Vitess shards MySQL
ServerlessNeon, Aurora Serverless v2, DynamoDB on-demand, PlanetScale
PolyglotOne owner per store; sync by outbox/CDC; count the operational cost
MigrationDual write → backfill → shadow read → flip → retire, each reversible

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 does the DynamoDB guide say not to design the schema until you know the questions? Must-know ​

Answer

Answer: Because DynamoDB queries are efficient only for the key conditions you designed (partition key, sort key, GSIs). Anything else is a Scan. The keys are the query plan, so they must follow the access patterns.

2 — Classify each as a query shape: "order 01J9A", "last 20 orders of customer 42", "revenue per region last quarter", "red shoes size 42", "friends of friends". Must-know ​

Answer

Answer: Point lookup; range scan on one key; aggregation (ad-hoc, with a join); full-text search; graph traversal.

3 — A team says "attributes differ per product, so we need MongoDB". What do you ask? Must-know ​

Answer

Answer: Is the product read and written as a whole by one owner? Are there cross-product invariants or reports with joins? How big is the team's PostgreSQL experience? Varying attributes alone fit PostgreSQL JSONB with generated columns; MongoDB fits when the aggregate shape and ownership also point there.

4 — When must a MongoDB child be referenced instead of embedded? Must-know ​

Answer

Answer: When the child side has high cardinality, grows without bounds, is written at different times in a write-heavy workload, can exist without the parent, or would make the document too large (16 MiB limit) or too costly to transfer.

5 — Why does a GSI keyed on order status create a hot partition, and how does the adapter fix it? Important ​

Answer

Answer: A three-value attribute puts all PLACED orders on one GSI partition key, capped at 1,000 write units per second. The adapter appends a hash-based shard suffix (STATUS#PLACED#0..3) and queries all shards, merging results.

6 — What can a Redis primary store lose with appendfsync everysec, and what settings make it a store rather than a cache? Important ​

Answer

Answer: About one second of writes on a crash. Store settings: AOF on, RDB snapshots for backups, maxmemory-policy noeviction, replicas, memory alerts.

7 — Redis or DynamoDB for (a) sessions with 30-minute TTL, (b) user profiles for 200 million users, (c) a leaderboard updated 10,000 times a second? Must-know ​

Answer

Answer: (a) Redis (or DynamoDB with TTL if you want no servers); (b) DynamoDB (durable, key-addressed, size); (c) Redis sorted set, with periodic snapshots to a durable store.

8 — What does distributed SQL give you that PostgreSQL does not, and what does it cost? Important ​

Answer

Answer: Writes and storage scale across nodes and survive node or zone loss while keeping SQL and serializable transactions. Cost: consensus latency per write (higher across regions), operational and financial cost, and fewer PostgreSQL features and extensions.

9 — Why is application dual write risky, and how does the migrate package contain the risk? Must-know ​

Answer

Answer: Without a cross-store transaction, one write can succeed and the other fail, so the stores diverge. The package writes the primary first, returns its result, queues failed secondary writes for an idempotent backfill, and uses shadow reads to detect remaining differences before the flip.

10 — Give the stores for an e-commerce system run by two developers, and why. Must-know ​

Answer

Answer: PostgreSQL for orders, catalogue (JSONB) and search (FTS), Redis for carts, sessions and cache. Two stores the team can operate; move Catalog or Search out only when measured patterns require it.

Glossary ​

TermMeaning
Access patternA named, repeatable data operation with inputs, result, rate and consistency need
Query shapeThe class of work: point lookup, range scan, join, full-text search, aggregation, graph traversal, similarity
Point lookupFetch one record by its key
Range scanRead an ordered slice of one key or index
Full-text searchFind and rank documents by words, via an inverted index
AggregationSum, count, average or percentile over many records
Graph traversalFollowing relationships over one or more hops
Read/write ratioProportion of reads to writes for a workload
Consistency requirementHow stale a read may be for a given pattern
Transaction requirementWhich invariants must change atomically across records
Schema volatilityHow often the set of fields changes and who controls it
Scale ceilingLoad at which the current design needs a structural change
Latency SLOTarget latency percentile per access pattern
Operational maturityProven ability to run, back up, restore and tune a store
Managed serviceA vendor-operated database offering (RDS, Atlas, DynamoDB, Neon)
Lock-inThe cost of leaving a product or vendor
RelationalTables with declared types and constraints queried by SQL
JoinCombining rows from tables by matching keys
ConstraintA rule the database enforces: NOT NULL, UNIQUE, CHECK, FOREIGN KEY
Foreign keyA column whose value must exist as a key in another table
Ad-hoc queryA question nobody designed the storage for
PostgreSQL by defaultStarting with PostgreSQL unless a requirement rules it out
JSONBPostgreSQL's binary, indexable JSON type
Document databaseA store of self-describing documents (MongoDB)
EmbeddingStoring related data inside the parent document
ReferencingStoring an ID and resolving it separately
Aggregation pipelineMongoDB's staged query language ($match, $group, $lookup)
Key-valueA store addressed by key, values opaque or semi-structured
Wide-columnPartitioned rows with clustering columns (Cassandra, Bigtable)
Partition keyThe key hashed to choose the partition
Sort keyThe key that orders items within a partition (clustering key in Cassandra)
GSIDynamoDB global secondary index: the same items re-keyed by other attributes, eventually consistent
Single-table designSeveral entity types in one DynamoDB table with generic keys and prefixes
No joinsKey-value stores do not combine records; co-locate or duplicate instead
Item collectionAll items sharing one partition key
Hot partitionA partition receiving more traffic than its per-partition limit
Write shardingAdding a suffix to a key to spread its writes
Redis primary storeRedis holding the only copy of a keyspace, with persistence and noeviction
Persistence AOF RDBRedis's append-only file (operation log) and point-in-time snapshots
Memory costRAM needed for the full dataset plus overhead and fork headroom
Elasticsearch / OpenSearchDistributed Lucene-based search and analytics engines
Time seriesAppend-heavy timestamped data queried by time windows
TimescaleDBPostgreSQL extension with hypertables partitioned by time
InfluxDBPurpose-built time-series database
ClickHouseColumn-oriented SQL database for OLAP
ColumnarStoring each column together for fast scans and compression
Graph databaseStore of nodes and relationships with properties (Neo4j)
Neo4jGraph database queried with Cypher
Vector databaseStore indexed for approximate nearest-neighbour search
pgvectorPostgreSQL extension for vector similarity search
NewSQL / distributed SQLSQL and ACID transactions on a shared-nothing cluster
SpannerGoogle Cloud's globally distributed SQL database with TrueTime
CockroachDBPostgreSQL-compatible distributed SQL with Raft per range
YugabyteDBDistributed SQL with a PostgreSQL-compatible YSQL API
VitessSharding and clustering layer for MySQL
Serverless databaseBilling and capacity that follow usage, sometimes to zero
Aurora ServerlessAurora with capacity in ACUs that scales automatically
NeonServerless PostgreSQL with separated storage and compute
PlanetScaleManaged Vitess (MySQL) and Postgres service
DynamoDB on-demandPay-per-request capacity mode, the default
Polyglot persistenceSeveral storage technologies, each chosen per workload and owned by one boundary
Bounded contextA model boundary that owns its data and language
CDCChange data capture: reading the database log to publish changes
OutboxA table written in the business transaction and relayed as events
Dual writeWriting each change to two stores during a migration
BackfillCopying historical data into a new store, idempotently
Shadow readReading the new store alongside the old and comparing, without serving it

References ​

Built by Morteza Negahi