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 for | Go to |
|---|---|
| The whole decision in three tables | Everything in one minute |
| Why "SQL vs NoSQL" is the wrong first question | Why it exists |
| Fowler's polyglot persistence, Dynamo, single-table design | Where it comes from |
| The inputs: access patterns, consistency, schema, scale, operations | Access patterns, Consistency and transactions, Schema volatility, Scale ceiling and latency, Operations, cost, lock-in |
| The store families, one block each | Relational, Document, Key-value and wide-column, Redis, Search, Time series, Graph, Vector, Distributed SQL, Serverless |
| One store per bounded context | Polyglot persistence |
| Moving from one store to another | Migration |
| Units, limits, knobs, error codes | Mechanics |
| Code | Go, Laravel |
| Classic mistakes and their fixes | Solving the classic problems |
| Decision tables and three worked designs | Choosing |
| Monolith to distributed system | In architecture |
| Sizing and contract tests you can run | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Query shape decides the family.
| Query shape | In plain words | Tiny example | Natural fit | Strains on |
|---|---|---|---|---|
| Point lookup | Fetch one thing by its key | GET order 01J9A | Any store; key-value is cheapest at scale | Nothing, until one key is hot |
| Range scan on one key | The latest N things of one owner | Last 20 orders of customer 42 | B-tree index (PostgreSQL), sort key (DynamoDB, Cassandra) | Ranges across owners in key-value stores |
| Multi-entity transaction | Change several things or none | Order + stock + payment row | Relational, distributed SQL | Key-value (limited transactions), document across documents |
| Ad-hoc query and join | A question nobody planned | "Revenue per region for customers who returned twice" | Relational, then a warehouse | Key-value and wide-column (no joins) |
| Full-text search | Find by words, rank by relevance | "red running shoes size 42" | Elasticsearch, OpenSearch; PostgreSQL FTS for small | Every OLTP store at scale |
| Aggregation over many rows | Sum, count, percentile over time | Requests per minute per endpoint | ClickHouse, TimescaleDB, InfluxDB (columnar or time-partitioned) | Row stores on the primary |
| Graph traversal | Follow relationships several hops | Friends of friends who like X | Neo4j; recursive SQL for shallow cases | Joins beyond 2 to 3 hops |
| Similarity | Nearest neighbours of a vector | "products like this photo" | pgvector, then a dedicated vector database | Exact-match stores |
Each family's promise and its price.
| Family | Strength | Price | Products |
|---|---|---|---|
| Relational | Joins, constraints, foreign keys, transactions, ad-hoc SQL, mature tooling | Write scaling beyond one primary needs sharding work | PostgreSQL, MySQL, SQL Server, Oracle, SQLite |
| Document | Aggregate stored and read whole; flexible fields | Cross-document invariants and joins are weaker | MongoDB, Couchbase, Firestore |
| Key-value / wide-column | Predictable latency at any size, horizontal by design | Only the queries you designed for; no joins | DynamoDB, Cassandra, ScyllaDB, Bigtable |
| In-memory data structures | Microsecond reads, counters, sets, streams | RAM cost; durability is a setting, not a given | Redis, Valkey, Memcached (cache only) |
| Search engine | Relevance, facets, typeahead | Derived copy; eventual; not a system of record | Elasticsearch, OpenSearch, Solr |
| Time series / columnar | Fast aggregations, compression | Point updates and transactions are weak | TimescaleDB, InfluxDB, ClickHouse |
| Graph | Deep, variable-length traversals | Niche skills; poor at bulk aggregation | Neo4j, Amazon Neptune |
| Vector | Approximate nearest-neighbour search | Recall vs latency tuning, memory | pgvector, Qdrant, Milvus, Pinecone |
| Distributed SQL (NewSQL) | SQL and transactions across nodes and regions | Latency per write, cost, fewer extensions | Spanner, CockroachDB, YugabyteDB, Vitess (sharded MySQL) |
The inputs you write down before naming a product.
| Input | Question | Example answer |
|---|---|---|
| Access patterns | Which 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 ratio | Mostly reads, mostly writes, or both? | 10:1 for orders; 1:50 for telemetry |
| Consistency requirement | Can a reader see a stale value? For how long? | Order status: read-your-writes; recommendations: minutes |
| Transaction requirement | Which invariants span more than one entity? | Stock never below zero while orders are placed |
| Schema volatility | How often do fields change, and who controls them? | Product attributes differ per category and change weekly |
| Scale ceiling | Size and write rate in 3 years; how many regions? | 140 GB/year orders, one region |
| Latency SLO | Target p99 per pattern | AP2 p99 under 20 ms |
| Operational maturity | Who runs it at 3 a.m.? Managed service available? | Two backend devs, no DBA: managed only |
| Cost and lock-in | Price per request, per GB, per node; exit path? | DynamoDB on-demand vs Aurora; export via S3 |
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 appear | Know the questions first, shape keys to answer them |
| Joins, constraints and transactions in the engine | Duplication and invariants in the application |
| New question = new SQL, maybe a new index | New question = new index or a backfill of new items |
| Scales up, then out with replicas and sharding work | Scales out by adding partitions, automatically on managed services |
| Latency depends on the plan the optimiser picks | Latency is flat because every query is a key lookup or a range on one key |
| Mistakes are cheap to fix later | Mistakes 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
- "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.
- "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.
- "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.
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 zeroThe 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.
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 CDCReal 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:
| Shape | PostgreSQL / MySQL | MongoDB | DynamoDB / Cassandra | Redis | Elasticsearch / OpenSearch | ClickHouse |
|---|---|---|---|---|---|---|
| Point lookup | Primary-key index | _id index | GetItem / partition key | GET, HGETALL | By _id, but near-real-time | Possible, not its job |
| Range on one key | Composite B-tree index | Compound index | Sort key / clustering key | Sorted set ZRANGE | Sort on a field | Primary-key order |
| Join | Native | $lookup, limited | None; denormalise | None | None; denormalise | Supported, best with small dimension tables |
| Ad-hoc filter | Any column, with or without index | Any field; index for speed | Scan (expensive) or new index | None | Any indexed field | Any column, fast |
| Full-text | Built-in FTS, fine for small corpora | Atlas Search | None | RediSearch module (Redis Stack) | Core feature | Limited |
| Aggregation | Good on replicas, slow at huge scale | Aggregation pipeline | Application side | Counters only | Aggregations | Core 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).
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 readsReal 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:
| Product | Single-record atomicity | Multi-record transaction | Default read consistency |
|---|---|---|---|
| PostgreSQL | Yes | Any number of rows and tables, up to SERIALIZABLE | Strong on the primary; replicas lag |
| MySQL InnoDB | Yes | Any rows, default REPEATABLE READ | Strong on the primary |
| MongoDB | One document, including nested arrays | Multi-document; needs a replica set or sharded cluster | Primary reads by default |
| DynamoDB | One item, with condition expressions | Up to 100 items, 4 MB aggregate, one account and Region | Eventually consistent unless ConsistentRead; GSIs are always eventual |
| Cassandra | One partition (lightweight transactions with Paxos) | Batches are not isolated transactions | Tunable (QUORUM, ONE) |
| Redis | One command; MULTI/EXEC runs a block without interleaving | No rollback on command error | Primary; replicas are asynchronous |
| Spanner / CockroachDB | Yes | Distributed, serializable | Strong 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).
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 checksReal 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:
| Product | Flexible part | Validation | Indexing flexible fields |
|---|---|---|---|
| PostgreSQL | jsonb column | CHECK with jsonb_typeof, jsonb_path_exists; generated columns | GIN (jsonb_ops, jsonb_path_ops), expression indexes |
| MySQL 8 | JSON column | CHECK, JSON schema validation function | Generated columns, multi-valued indexes |
| MongoDB | Whole document | $jsonSchema validator on the collection | Any field, wildcard indexes |
| DynamoDB | Any non-key attribute | None in the database | Only key attributes and GSI keys |
| Cassandra | Columns per table, collections, UDTs | CQL types | Secondary 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).
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 queriesReal 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:
| Product | How it scales writes | Practical ceiling signal |
|---|---|---|
| PostgreSQL (single primary) | Vertical; partitioning helps maintenance, not write fan-out | WAL rate, CPU, lock contention, vacuum lag |
| PostgreSQL + Citus | Sharded by distribution column | Cross-shard queries and transactions |
| MySQL + Vitess | Sharded by keyspace ID; Vitess "distributes data across multiple MySQL instances through sharding" | Cross-shard joins, resharding operations |
| DynamoDB | Automatic partitions; on-demand "can start small and scale to millions of requests per second" | Hot partition keys, item size 400 KB |
| Cassandra / ScyllaDB | Add nodes; consistent-hash ring | Partition size, tombstones, repair |
| Spanner / CockroachDB / YugabyteDB | Ranges split and move automatically | Cross-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.
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 packageReal 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:
| Concern | PostgreSQL | MySQL | MongoDB | DynamoDB | Cassandra | Redis |
|---|---|---|---|---|---|---|
| Managed offerings | RDS, Aurora, Cloud SQL, AlloyDB, Azure, Neon, Supabase | RDS, Aurora, PlanetScale | Atlas, DocumentDB (compatible API) | AWS only | Astra DB, Amazon Keyspaces | ElastiCache, MemoryDB, Redis Cloud |
| Laravel 13 first-party | Yes | Yes (and MariaDB) | Via mongodb/laravel-mongodb | Cache and session store drivers | No | Yes (Redis facade, cache, queue, session) |
| Go driver | pgx | go-sql-driver/mysql | mongo-go-driver | aws-sdk-go-v2 | gocql | go-redis |
| Lock-in | Low | Low | Medium | High | Low | Low (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.
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 primaryReal 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:
| Feature | PostgreSQL | MySQL InnoDB | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
| Foreign keys, CHECK | Yes | Yes | Yes | Yes | Yes (FK enforcement is a pragma) |
| JSON | jsonb with GIN | JSON with generated-column indexes | json type | JSON | JSON functions |
| Partial and expression indexes | Yes | Functional indexes; no partial | Filtered indexes | Function-based | Yes |
| Extensions | pgvector, TimescaleDB, PostGIS, Citus | Plugins | Limited | Options | Loadable extensions |
| Error on duplicate key | SQLSTATE 23505 unique_violation | Error 1062 | 2627 / 2601 | ORA-00001 | SQLITE_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:
-- 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.
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 relationalReal 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:
| Capability | MongoDB | PostgreSQL jsonb | DynamoDB item |
|---|---|---|---|
| Max size | 16 MiB per document | 1 GB per field value (TOAST) | 400 KB per item |
| Nested query | Dot notation, array operators | ->, ->>, @>, jsonpath | Projection only; filter after read |
| Secondary index on nested field | Yes | GIN or expression index | Only via GSI key attributes |
| Joins | $lookup | Full SQL | None |
| Multi-record transaction | Replica set or sharded cluster | Native | TransactWriteItems |
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.
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 StreamsReal 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:
| Concept | DynamoDB | Cassandra / ScyllaDB | Bigtable |
|---|---|---|---|
| Partition key | Partition key (hash) | Partition key | Row key prefix |
| Order inside partition | Sort key | Clustering columns | Lexicographic row key |
| Secondary access path | GSI (eventual), LSI (same partition key, 5 per table) | Materialized views, SAI indexes, or a second table | Second table |
| Per-partition limit | 3,000 read units and 1,000 write units per second | Partition size guidance (keep partitions bounded) | Row size, hotspotting |
| Conditional write | ConditionExpression | Lightweight transactions (IF NOT EXISTS) | Check-and-mutate |
| Capacity model | On-demand (default) or provisioned | Nodes you run or a managed service | Nodes |
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.
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 minutesReal 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:
| Question | Redis (ElastiCache, MemoryDB, self-hosted) | DynamoDB |
|---|---|---|
| Latency | Sub-millisecond, in memory | Single-digit milliseconds |
| Durability | Configurable; AOF everysec loses up to ~1 s; MemoryDB adds a durable log | Durable, replicated across AZs on write |
| Cost driver | RAM for the whole dataset | Requests and stored GB |
| Data structures | Hashes, lists, sets, sorted sets, streams, HyperLogLog | Items with attributes; lists and maps inside items |
| Size per value | Up to 512 MB per string | 400 KB per item |
| Query shapes | Key, range on sorted set, scripts | Key, range on sort key, GSIs |
| Scale out | Redis Cluster, 16,384 hash slots | Automatic partitions |
| Best when | Hot, small, short-lived, latency-critical | Durable 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.
Search engines: Elasticsearch and OpenSearch Important
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.
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 reindexReal 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.
| Need | PostgreSQL FTS | Elasticsearch / OpenSearch | MongoDB Atlas Search |
|---|---|---|---|
| Ranking | ts_rank, basic | BM25, function scores, learning to rank | Lucene-based |
| Facets and aggregations | SQL GROUP BY | Native, fast | Facets |
| Freshness | Transactional | Near-real-time | Near-real-time |
| Extra store to run | No | Yes | Managed 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).
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 aggregationReal scenario: IoT telemetry, application metrics, financial ticks, clickstream analytics, ad impressions, observability backends.
| Product | Model | SQL | Best when |
|---|---|---|---|
| TimescaleDB | PostgreSQL extension, hypertables, compression, continuous aggregates | Full PostgreSQL | You want time series next to relational data, joins included |
| InfluxDB 3 | Purpose-built time-series database | SQL and InfluxQL | Metrics and events ingestion with real-time queries |
| ClickHouse | Columnar OLAP, MergeTree engines | ClickHouse SQL | Large analytical scans and aggregations, also time series |
| Cassandra | Partition per device and time bucket | CQL | Huge 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.
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 bReal scenario: fraud rings, recommendation by co-purchase, access-control graphs (ReBAC; see Authorization Models), network topology, knowledge graphs.
| Hops | PostgreSQL | Neo4j |
|---|---|---|
| 1 to 2 | Indexed joins, fine | Fine |
| 3 to 6, variable | Recursive CTE, grows fast | Designed for it |
| Bulk aggregates over all nodes | Good | Weaker |
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.
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 copyReal scenario: semantic search, RAG over documents, image similarity, deduplication, recommendations.
| Scale | Choice |
|---|---|
| Up to tens of millions of vectors, filters on relational data | pgvector |
| Hundreds of millions to billions, specialised filtering | Dedicated 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.
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 writeReal 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).
| Product | API | Consensus | Notes |
|---|---|---|---|
| Google Cloud Spanner | GoogleSQL and PostgreSQL dialect | Paxos + TrueTime | Managed only; external consistency |
| CockroachDB | PostgreSQL wire protocol | Raft per range | Serializable by default; READ COMMITTED available |
| YugabyteDB | YSQL (PostgreSQL), YCQL | Raft per tablet | Reuses PostgreSQL query layer |
| Vitess / PlanetScale | MySQL protocol | MySQL replication per shard | Sharding layer, not one consensus database |
| TiDB | MySQL protocol | Raft (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.
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 loadReal 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).
| Product | Billing unit | Scale to zero | Engine |
|---|---|---|---|
| DynamoDB on-demand | Per request + storage | Yes (no idle compute) | DynamoDB |
| Aurora Serverless v2 | ACU-hours + I/O + storage | Yes, with auto-pause | MySQL / PostgreSQL compatible |
| Neon | Compute-hours + storage | Yes | PostgreSQL |
| PlanetScale | Plan/cluster based | Depends on plan | Vitess (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.
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 store | What it means |
|---|---|
| Operations | Backups, restore drills, upgrades, monitoring, on-call runbooks |
| Security | Credentials, network rules, encryption, audit per store |
| Consistency | A pipeline (CDC/outbox) and its lag, replay and reconciliation |
| Skills | Someone who knows its failure modes |
| Local development | Another 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.
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 removedReal 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.
| Technique | Advantage | Risk |
|---|---|---|
| Application dual write | Simple, no infrastructure | Divergence on partial failure; must queue and repair |
| CDC from old store | One write path; ordered by the log | Needs CDC tooling (Debezium, DynamoDB Streams, change streams) |
| Backfill | Brings history | Load on the old store; must be idempotent and throttled |
| Shadow read | Proves equivalence on real traffic | Doubles read load; compare off the hot path |
| Feature-flag flip | Instant rollback | Both 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 limit | Value | Source page | Design consequence |
|---|---|---|---|
| Read unit | 4 KB strong read, or two eventual reads | Partition key best practices | A 20 KB item costs 5 units per strong read |
| Write unit | 1 KB write | Partition key best practices | Every GSI that projects the item is another write |
| Per-partition throughput | 3,000 RCU and 1,000 WCU per second | Partition key best practices | One hot key is capped no matter how large the table |
| Item size | 400 KB maximum | Large items best practices | Large blobs go to S3 with a pointer |
| Transactions | Up to 100 actions, 4 MB aggregate, one account and Region | Transactions API | Keep invariants within 100 items |
| GSIs per table | 20 (adjustable) | Service quotas | Each access path costs one |
| LSIs per table | 5, created with the table | Service quotas | Same partition key, adds a 10 GB item-collection limit |
| GSI reads | Eventually consistent only | GSI page | Read-your-writes needs the base table |
| Capacity modes | On-demand (default) or provisioned | Capacity mode page | Provisioned plus auto scaling for steady load |
Running the lab sizing program for the Ordering patterns prints:
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 GBTwo 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 limit | Value | Consequence |
|---|---|---|
| Document size | 16 MiB BSON | Unbounded arrays must become a collection |
| Nesting depth | 100 levels | Rarely hit; deep nesting is a smell anyway |
| Atomicity | Single document, including nested arrays | Embed what must change together |
| Multi-document transactions | Replica 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 collection | Use it; schemaless is a choice, not a default |
| Write concern | w: "majority" for durability across failover | Lower values trade durability for latency |
Redis persistence and memory knobs
# 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| Setting | Values | Effect |
|---|---|---|
appendfsync | always, everysec (default), no | Redis 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") |
save | Snapshot points (seconds, changes) | RDB; "you should be prepared to lose the latest minutes of data" |
| AOF format | Multi part AOF since Redis 7.0.0 | Base file plus incremental files, tracked by a manifest |
maxmemory-policy | noeviction, allkeys-lru, allkeys-lfu, volatile-lru, volatile-ttl, ... | allkeys-lru "is a good default option" for caches; noeviction for stores |
| Fork cost | RDB and AOF rewrite fork a child | Redis docs: may stop serving clients "for some milliseconds or even for one second if the dataset is very big" |
| Cluster | 16,384 hash slots | Multi-key commands need keys in one slot: hash tags cart:{42} |
PostgreSQL knobs for flexible data
| Knob | Effect | Note |
|---|---|---|
json vs jsonb | json 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 GIN | jsonb_path_ops is smaller and faster for @> containment only | Default jsonb_ops also supports key-existence operators |
| Generated column | GENERATED ALWAYS AS (attributes ->> 'brand') STORED | Turns a hot JSON field into an indexed column |
CHECK (jsonb_typeof(...) = 'object') | Rejects arrays or scalars where objects belong | Validation without a full JSON Schema |
| Partial index | WHERE status = 'PLACED' | Small index for a hot subset (AP4) |
Error codes and messages you will actually see
| Product | Code / exception | Message (verbatim where documented) | Retry? | Usual cause in this chapter |
|---|---|---|---|---|
| PostgreSQL | SQLSTATE 23505 | unique_violation | No; return the existing row | Retried order with the same ID |
| PostgreSQL | SQLSTATE 23503 | foreign_key_violation | No | Line for an order that does not exist |
| PostgreSQL | SQLSTATE 23514 | check_violation | No | Quantity 0, unknown status, JSONB not an object |
| PostgreSQL | SQLSTATE 40001 | serialization_failure | Yes, whole transaction | Concurrent stock updates under SERIALIZABLE |
| DynamoDB | ConditionalCheckFailedException | "The conditional request failed." | No | attribute_not_exists(PK) on a duplicate order |
| DynamoDB | ProvisionedThroughputExceededException | "You exceeded your maximum allowed provisioned throughput for a table or for one or more global secondary indexes." | Yes, with backoff | Hot partition or under-provisioned GSI |
| DynamoDB | ItemCollectionSizeLimitExceededException | "Collection size exceeded." | Yes (after design change) | LSI table with a partition key over 10 GB |
| DynamoDB | TransactionCanceledException | Cancellation reasons per action | Depends on reason | A condition in TransactWriteItems failed |
| Laravel | Illuminate\Database\UniqueConstraintViolationException | Wraps the driver's duplicate-key error | No | Same as 23505 |
| Redis | OOM error reply | Returned on writes under noeviction at maxmemory | After freeing memory | Store 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.
// 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:
// 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
}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:
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:
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:
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
}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
}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:
// 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
}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):
// 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 package | Use here | Note |
|---|---|---|
github.com/jackc/pgx/v5 | pgx.BeginFunc, pgx.CollectRows, array parameters | Native PostgreSQL protocol; pgx.Tx and *pgxpool.Pool share the Begin/Query methods the adapter needs |
github.com/jackc/pgx/v5/pgxpool | pgxpool.New(ctx, dsn) | One pool per process; see Connection Pooling |
github.com/jackc/pgx/v5/pgconn | *pgconn.PgError and .Code | Branch on SQLSTATE, never on message text |
github.com/aws/aws-sdk-go-v2/service/dynamodb | PutItem, GetItem, Query, NewScanPaginator | Accept an interface with the SDK's method signatures for tests |
github.com/aws/aws-sdk-go-v2/service/dynamodb/types | AttributeValueMemberS, ConditionalCheckFailedException | Typed errors with errors.As |
github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue | MarshalMap, UnmarshalMap, UnmarshalListOfMaps | Struct tags dynamodbav |
go.mongodb.org/mongo-driver/v2 | Would be the MongoDB adapter | Same port, same contract suite |
github.com/redis/go-redis/v9 | Cart adapter in Go | TxPipelined for MULTI/EXEC |
hash/fnv | GSI write sharding | Stable, 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
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
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
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
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
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
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
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
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
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
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
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
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 feature | Use | Note |
|---|---|---|
config/database.php connections | One named connection per context (orders, mongodb) | Models set protected $connection |
DB::connection('orders')->transaction() | Atomic order + lines + outbox | Transactions never span connections |
Schema in a migration with $connection | Migrations per context | Run per database in CI |
HasUlids | Time-sortable string keys | Matches the Go ULID-style IDs and the id DESC index |
Illuminate\Database\UniqueConstraintViolationException | Idempotent create | Catch it, then read the existing row |
Redis::connection('cart') | A dedicated logical database for carts | Separate from the cache connection |
Redis::transaction(fn ($redis) => ...) | MULTI/EXEC block | Not a rollback-capable transaction |
mongodb/laravel-mongodb | driver => 'mongodb', MongoDB\Laravel\Eloquent\Model, embedsMany, aggregation builder | Register MongoDB\Laravel\MongoDBServiceProvider; transactions need a replica set |
$singletons on a service provider | Bind the port to the Eloquent adapter | Swap the adapter during a migration |
| Cache and session drivers | redis, database, dynamodb | DynamoDB 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
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| Solution | How | Advantage | Cost |
|---|---|---|---|
| Stream to an analytics store | DynamoDB Streams or export to S3, then ClickHouse / Athena | No change to the OLTP design | Second store, lag |
| New GSI per new pattern | Add GSI, backfill attributes | Stays in DynamoDB | Write cost per GSI; 20 per table |
| Move the context to PostgreSQL | Migration phases above | Ad-hoc SQL forever | A migration project |
| Avoid next time | Write the access patterns; if unstable, start relational | Cheapest | Requires discipline up front |
-- 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| System of record in PostgreSQL | Orders and balances in SQL with constraints; Redis only caches | Durable, auditable | One more store if you had only Redis |
| Redis as a write buffer | Accept in Redis, flush to SQL in batches | Absorbs spikes | Loss window equals the flush interval plus fsync |
| Durable Redis-compatible service | Amazon MemoryDB keeps a multi-AZ transaction log | Redis API with durability | Higher write latency and cost |
| Ledger pattern | Append-only entries, balance derived | Reconstructable | More 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
-- 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;| Solution | When |
|---|---|
| Typed columns + FK + CHECK | Anything in a join, sum, uniqueness rule or report |
JSONB with CHECK (jsonb_typeof(...) = 'object') | Varying attributes, third-party payloads |
| Generated column + B-tree index | One JSON field queried often |
GIN jsonb_path_ops | Containment (@>) filters on many keys |
A hot partition in DynamoDB
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Write sharding | Suffix #0..N-1 on a low-cardinality key | Spreads writes over N partitions | Reads fan out N ways |
| Higher-cardinality key | Key by order ID, not status | No fan-out | Need a GSI for the other path |
| Cache in front of hot reads | DAX or Redis for a celebrity item | Absorbs read spikes | Staleness |
| Batch or buffer | Aggregate increments before writing | Fewer writes | Delay (Write Buffering) |
The adapter's statusPK and ListByStatus are the write-sharding fix; TestStatusKeySpreadsOverShards checks that eight orders do not land on one key.
Search on the OLTP database is slow
| Solution | How | Advantage | Cost |
|---|---|---|---|
| PostgreSQL FTS + GIN | tsvector column, websearch_to_tsquery | No new store | Basic ranking |
| OpenSearch via outbox/CDC | Outbox row in the order transaction, Debezium to Kafka, idempotent indexer | Relevance, facets | Second store, lag, rebuild job |
| Managed search on the document store | MongoDB Atlas Search | One vendor | Lock-in |
Too many stores
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Store inventory with owners | One row per store: owner, purpose, access patterns, on-call | Visibility | An hour of work |
| Consolidate into PostgreSQL | JSONB, pgvector, TimescaleDB, FTS replace small stores | Fewer moving parts | Less headroom per feature |
| Retire by migration | Phases above, in reverse | Safe | Time |
Choosing
Decision table by workload
| Workload | Recommended store | Extra technique | Reason |
|---|---|---|---|
| Orders, payments, ledgers, inventory | PostgreSQL (or MySQL) | Constraints, outbox, idempotency keys | Multi-entity invariants and audits |
| Same, multi-region writes or beyond one primary | Spanner, CockroachDB, YugabyteDB | Region-aware partitioning | SQL invariants plus horizontal writes |
| Product catalogue with varying attributes | PostgreSQL JSONB, or MongoDB if aggregates are read whole and owned by one team | Generated columns or $jsonSchema | Schema volatility |
| Carts, sessions, rate-limit counters | Redis (store mode) or DynamoDB | TTLs, noeviction for stores | Small, hot, loss-tolerant or key-addressed |
| User profiles at very large scale, known patterns | DynamoDB or Cassandra | Single-table design, GSIs | Predictable latency at any size |
| Chat messages, activity feeds | Cassandra / ScyllaDB or DynamoDB | Partition per channel and time bucket | Range scans on one key, high write rate (Feeds) |
| Product or content search | Elasticsearch / OpenSearch | CDC-fed, alias reindex | Relevance and facets |
| Metrics, IoT telemetry | TimescaleDB, InfluxDB, ClickHouse | Retention, downsampling | Append-heavy, time-window aggregates |
| Analytics and BI | ClickHouse, a warehouse | CDC from OLTP | Columnar scans |
| Fraud rings, recommendations by paths | Neo4j (derived) | Fed from OLTP | Variable-depth traversals |
| Semantic search, RAG | pgvector first | HNSW index, filters in SQL | Vectors next to relational filters |
| Unknown load, previews, dev branches | Neon, Aurora Serverless, DynamoDB on-demand | Budgets and alarms | Pay per use |
| Cache in front of anything | Redis | Cache-aside, TTL, allkeys-lru (Caching) | Latency and load shedding |
SQL vs NoSQL in one table
| Choose relational when | Choose a NoSQL family when |
|---|---|
| Access patterns are many, evolving or unknown | Access 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 data | Reports go to an analytics store anyway |
| One primary can carry the writes for the next 2 to 3 years | Write rate or data size is beyond a large primary, or needs many regions |
| The team knows SQL and the ORM | The team knows the NoSQL modelling method (single-table, embedding rules) |
| You want low lock-in | You accept the vendor API in exchange for operations you do not run |
Worked example 1: e-commerce (catalogue, orders, carts, search)
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 OrderingOne 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
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 sitesTelemetry 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
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 PostgreSQLAdjacency 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
| Load | Typical design |
|---|---|
| 1x | PostgreSQL primary + replica; Redis cache/sessions; everything else as PostgreSQL features |
| 10x | Bigger primary, more replicas, connection pooling, partitioning of the largest tables; search and analytics moved out via CDC |
| 100x | Shard 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):
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 GB2. Run the contract suite against the fake DynamoDB and the in-memory adapter (run on this machine):
go test ./...
# ok academy/sql-vs-nosql-decision/migrate
# ok academy/sql-vs-nosql-decision/orders
# TestPostgresContract is skipped unless ORDERS_PG_DSN is set3. Run the same suite against PostgreSQL (expected, not run):
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_store4. See which index serves which pattern (expected, not run):
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):
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:ok6. Feel the cost of an unmodelled query on DynamoDB (expected, not run, against DynamoDB Local or a sandbox account):
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
| Belief | Reality |
|---|---|
| NoSQL scales, SQL does not | A single PostgreSQL primary carries most workloads; distributed SQL scales SQL out; NoSQL gives predictable performance for designed queries |
| Schemaless means no schema | The schema moves into every reader; MongoDB and PostgreSQL docs both recommend predictable structure |
| MongoDB means embed everything | Reference unbounded, independently written or high-cardinality children |
| DynamoDB needs one table per entity | The guide recommends as few tables as possible; single-table design co-locates entities |
| A GSI gives strongly consistent reads | DynamoDB GSIs support eventually consistent reads only |
| Redis persistence makes it as safe as PostgreSQL | everysec can lose about a second; RDB alone can lose minutes |
| JSONB means we do not need columns | Filter, join, sum and constrain on typed columns; JSONB for the long tail |
| Distributed SQL is free scaling | Each write is a consensus round; regions add latency |
| Polyglot persistence means many databases | It means the right store per workload, each with one owner, and as few as possible |
| Dual write in the request is enough to migrate | Partial failures diverge the stores; queue, reconcile or use CDC |
| Serverless is always cheaper | Steady high load is often cheaper provisioned; scale-from-zero adds cold starts |
| Search engines can be the source of truth | They are derived, near-real-time indexes you must be able to rebuild |
| Graph data needs a graph database | One or two hops are joins; graph stores pay off for deep variable traversals |
Cheat sheet
| Topic | Remember |
|---|---|
| First step | Access-pattern table: name, shape, QPS, consistency, SLO |
| Default | PostgreSQL unless a requirement rules it out |
| Relational strengths | Joins, constraints, foreign keys, transactions, ad-hoc queries, tooling |
| Document rule | Embed bounded and read-together data; reference unbounded data; 16 MiB limit |
| DynamoDB rule | Know the questions first; few tables; PK + SK + GSIs; no Scan on request paths |
| DynamoDB numbers | 4 KB read unit, 1 KB write unit, 3,000 RCU / 1,000 WCU per partition, 400 KB item, 100-item transactions |
| Redis as store | AOF everysec (about 1 s loss), RDB snapshots, noeviction, replicas; never the only copy of money |
| Redis vs DynamoDB | Redis for hot, small, sub-millisecond; DynamoDB for durable key-addressed records at any size |
| Search | Elasticsearch/OpenSearch as a derived index fed by CDC |
| Time series | TimescaleDB, InfluxDB, ClickHouse; retention and downsampling |
| Vectors | pgvector first |
| Distributed SQL | Spanner, CockroachDB, YugabyteDB; Vitess shards MySQL |
| Serverless | Neon, Aurora Serverless v2, DynamoDB on-demand, PlanetScale |
| Polyglot | One owner per store; sync by outbox/CDC; count the operational cost |
| Migration | Dual write → backfill → shadow read → flip → retire, each reversible |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why 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
| Term | Meaning |
|---|---|
| Access pattern | A named, repeatable data operation with inputs, result, rate and consistency need |
| Query shape | The class of work: point lookup, range scan, join, full-text search, aggregation, graph traversal, similarity |
| Point lookup | Fetch one record by its key |
| Range scan | Read an ordered slice of one key or index |
| Full-text search | Find and rank documents by words, via an inverted index |
| Aggregation | Sum, count, average or percentile over many records |
| Graph traversal | Following relationships over one or more hops |
| Read/write ratio | Proportion of reads to writes for a workload |
| Consistency requirement | How stale a read may be for a given pattern |
| Transaction requirement | Which invariants must change atomically across records |
| Schema volatility | How often the set of fields changes and who controls it |
| Scale ceiling | Load at which the current design needs a structural change |
| Latency SLO | Target latency percentile per access pattern |
| Operational maturity | Proven ability to run, back up, restore and tune a store |
| Managed service | A vendor-operated database offering (RDS, Atlas, DynamoDB, Neon) |
| Lock-in | The cost of leaving a product or vendor |
| Relational | Tables with declared types and constraints queried by SQL |
| Join | Combining rows from tables by matching keys |
| Constraint | A rule the database enforces: NOT NULL, UNIQUE, CHECK, FOREIGN KEY |
| Foreign key | A column whose value must exist as a key in another table |
| Ad-hoc query | A question nobody designed the storage for |
| PostgreSQL by default | Starting with PostgreSQL unless a requirement rules it out |
| JSONB | PostgreSQL's binary, indexable JSON type |
| Document database | A store of self-describing documents (MongoDB) |
| Embedding | Storing related data inside the parent document |
| Referencing | Storing an ID and resolving it separately |
| Aggregation pipeline | MongoDB's staged query language ($match, $group, $lookup) |
| Key-value | A store addressed by key, values opaque or semi-structured |
| Wide-column | Partitioned rows with clustering columns (Cassandra, Bigtable) |
| Partition key | The key hashed to choose the partition |
| Sort key | The key that orders items within a partition (clustering key in Cassandra) |
| GSI | DynamoDB global secondary index: the same items re-keyed by other attributes, eventually consistent |
| Single-table design | Several entity types in one DynamoDB table with generic keys and prefixes |
| No joins | Key-value stores do not combine records; co-locate or duplicate instead |
| Item collection | All items sharing one partition key |
| Hot partition | A partition receiving more traffic than its per-partition limit |
| Write sharding | Adding a suffix to a key to spread its writes |
| Redis primary store | Redis holding the only copy of a keyspace, with persistence and noeviction |
| Persistence AOF RDB | Redis's append-only file (operation log) and point-in-time snapshots |
| Memory cost | RAM needed for the full dataset plus overhead and fork headroom |
| Elasticsearch / OpenSearch | Distributed Lucene-based search and analytics engines |
| Time series | Append-heavy timestamped data queried by time windows |
| TimescaleDB | PostgreSQL extension with hypertables partitioned by time |
| InfluxDB | Purpose-built time-series database |
| ClickHouse | Column-oriented SQL database for OLAP |
| Columnar | Storing each column together for fast scans and compression |
| Graph database | Store of nodes and relationships with properties (Neo4j) |
| Neo4j | Graph database queried with Cypher |
| Vector database | Store indexed for approximate nearest-neighbour search |
| pgvector | PostgreSQL extension for vector similarity search |
| NewSQL / distributed SQL | SQL and ACID transactions on a shared-nothing cluster |
| Spanner | Google Cloud's globally distributed SQL database with TrueTime |
| CockroachDB | PostgreSQL-compatible distributed SQL with Raft per range |
| YugabyteDB | Distributed SQL with a PostgreSQL-compatible YSQL API |
| Vitess | Sharding and clustering layer for MySQL |
| Serverless database | Billing and capacity that follow usage, sometimes to zero |
| Aurora Serverless | Aurora with capacity in ACUs that scales automatically |
| Neon | Serverless PostgreSQL with separated storage and compute |
| PlanetScale | Managed Vitess (MySQL) and Postgres service |
| DynamoDB on-demand | Pay-per-request capacity mode, the default |
| Polyglot persistence | Several storage technologies, each chosen per workload and owned by one boundary |
| Bounded context | A model boundary that owns its data and language |
| CDC | Change data capture: reading the database log to publish changes |
| Outbox | A table written in the business transaction and relayed as events |
| Dual write | Writing each change to two stores during a migration |
| Backfill | Copying historical data into a new store, idempotently |
| Shadow read | Reading the new store alongside the old and comparing, without serving it |
References
- Amazon Web Services — NoSQL design for DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html
- Amazon Web Services — Best practices for designing and architecting with DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html
- Amazon Web Services — Data modeling in DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/data-modeling.html
- Amazon Web Services — Best practices for designing and using partition keys effectively. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html
- Amazon Web Services — DynamoDB throughput capacity (on-demand and provisioned). https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/capacity-mode.html
- Amazon Web Services — Using Global Secondary Indexes in DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
- Amazon Web Services — Quotas in Amazon DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ServiceQuotas.html
- Amazon Web Services — Amazon DynamoDB Transactions: How it works. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis.html
- Amazon Web Services — Best practices for storing large items and attributes. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-use-s3-too.html
- Amazon Web Services — Error handling with DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html
- Amazon Web Services — First steps for modeling relational data in DynamoDB. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-relational-modeling.html
- Rick Houlihan — Amazon DynamoDB Deep Dive: Advanced Design Patterns for DynamoDB (DAT401), AWS re:Invent 2018 (talk). https://www.youtube.com/watch?v=HaEPXoXVf2k
- Amazon Web Services — Aurora Serverless v2. https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.html
- Martin Fowler — PolyglotPersistence (16 November 2011). https://martinfowler.com/bliki/PolyglotPersistence.html
- Werner Vogels — Amazon's Dynamo (2007). https://www.allthingsdistributed.com/2007/10/amazons_dynamo.html
- Corbett et al. — Spanner: Google's Globally-Distributed Database (OSDI 2012). https://research.google/pubs/spanner-googles-globally-distributed-database-2/
- Martin Kleppmann — Designing Data-Intensive Applications, chapter 2 "Data Models and Query Languages" (O'Reilly, 2017; book, not fetched).
- MongoDB — Data Modeling. https://www.mongodb.com/docs/manual/data-modeling/
- MongoDB — Embedded Data in Your MongoDB Schema. https://www.mongodb.com/docs/manual/data-modeling/embedding/
- MongoDB — Reference Data in Your MongoDB Schema. https://www.mongodb.com/docs/manual/data-modeling/referencing/
- MongoDB — Embedding vs references. https://www.mongodb.com/docs/manual/data-modeling/concepts/embedding-vs-references/
- MongoDB — MongoDB Limits and Thresholds. https://www.mongodb.com/docs/manual/reference/limits/
- MongoDB — Aggregation Operations. https://www.mongodb.com/docs/manual/aggregation/
- MongoDB — Laravel MongoDB (documentation home, configuration, model class, transactions, aggregation builder, relationships). https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/
- MongoDB — Laravel MongoDB: Configure your MongoDB connection. https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/quick-start/configure-mongodb/
- MongoDB — Laravel MongoDB: Eloquent Model Class. https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/eloquent-models/model-class/
- MongoDB — Laravel MongoDB: Transactions. https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/transactions/
- MongoDB — Laravel MongoDB: Aggregation Builder. https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/fundamentals/aggregation-builder/
- Packagist — mongodb/laravel-mongodb. https://packagist.org/packages/mongodb/laravel-mongodb
- GitHub — mongodb/laravel-mongodb. https://github.com/mongodb/laravel-mongodb
- Redis — Redis persistence. https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/
- Redis — Key eviction. https://redis.io/docs/latest/develop/reference/eviction/
- Redis — Scale with Redis Open Source (cluster, hash slots). https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/
- Redis — Redis strings. https://redis.io/docs/latest/develop/data-types/strings/
- PostgreSQL — JSON Types. https://www.postgresql.org/docs/current/datatype-json.html
- PostgreSQL — Constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
- PostgreSQL — PostgreSQL Error Codes. https://www.postgresql.org/docs/current/errcodes-appendix.html
- Google Cloud — Spanner overview. https://cloud.google.com/spanner/docs/overview
- Google Cloud — Spanner: TrueTime and external consistency. https://cloud.google.com/spanner/docs/true-time-external-consistency
- Cockroach Labs — Architecture Overview. https://www.cockroachlabs.com/docs/stable/architecture/overview
- Cockroach Labs — Transaction Layer. https://www.cockroachlabs.com/docs/stable/architecture/transaction-layer
- Cockroach Labs — PostgreSQL Compatibility. https://www.cockroachlabs.com/docs/stable/postgresql-compatibility
- YugabyteDB — Architecture. https://docs.yugabyte.com/stable/architecture/
- Vitess — What is Vitess. https://vitess.io/docs/overview/whatisvitess/
- PlanetScale — Documentation. https://planetscale.com/docs
- Neon — Architecture overview. https://neon.com/docs/introduction/architecture-overview
- Neon — Autoscaling. https://neon.com/docs/introduction/autoscaling
- ClickHouse — What is ClickHouse? https://clickhouse.com/docs/intro
- ClickHouse — What is a columnar database? https://clickhouse.com/docs/faq/general/columnar-database
- Tiger Data (TimescaleDB) — Hypertables. https://docs.timescale.com/use-timescale/latest/hypertables/
- InfluxData — InfluxDB 3 Core. https://docs.influxdata.com/influxdb3/core/
- Neo4j — What is a graph database. https://neo4j.com/docs/getting-started/graph-database/
- OpenSearch — Introduction to OpenSearch. https://docs.opensearch.org/latest/getting-started/intro/
- Elastic — Get started with Elasticsearch. https://www.elastic.co/docs/get-started
- pgvector — Open-source vector similarity search for Postgres. https://github.com/pgvector/pgvector
- Laravel 13 — Database: Getting Started. https://laravel.com/docs/13.x/database
- Laravel 13 — Redis. https://laravel.com/docs/13.x/redis
- Laravel 13 — Eloquent: Getting Started. https://laravel.com/docs/13.x/eloquent
- Go packages — github.com/jackc/pgx/v5. https://pkg.go.dev/github.com/jackc/pgx/v5
- Go packages — github.com/jackc/pgx/v5/pgxpool. https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool
- Go packages — github.com/aws/aws-sdk-go-v2/service/dynamodb. https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb
- Go packages — github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue. https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue