Key-value and document stores: Redis, DynamoDB, MongoDB
Start from the access patterns, then pay for every query you did not list: the shop modelled three ways
The shop runs on DynamoDB. Order headers live under PK=ORDER#id and carry GSI1PK=CUST#id so the 'my orders' page can Query the GSI. A customer places an order; the write succeeds and the browser immediately loads 'my orders' from GSI1. What does the customer see?
The relational model asks you to model the data and lets the queries come later; the planner works out how to answer them. Key-value and document stores invert that. You list the questions first, and you lay the data out so each question is a single lookup on a key you chose in advance. In exchange you get predictable latency at any size, horizontal scaling that needs no planner, and a bill that grows linearly with traffic. The cost is that any question you did not list is either a full scan or a migration.
This chapter models the shop three ways: in Redis, a data-structure server that lives in memory; in DynamoDB, a managed partitioned key-value store with a documented cost per request; and in MongoDB, a document database with secondary indexes and an aggregation language. You will see where each is fast, where each lies to you about consistency if you do not ask, and what each charges you for flexibility.
Access patterns first
The modelling chapter in module one, Modelling: keys, normalisation, and when to denormalise, normalised the shop into six tables because a planner can join them for any question. Here you start from the questions. For the shop:
| # | Access pattern | Rate (peak) | Must see own writes? |
|---|---|---|---|
| AP1 | Get a customer profile by id | 2 000/s | no |
| AP2 | A customer’s ten most recent orders | 500/s | yes, right after checkout |
| AP3 | One order with its lines and payment | 1 000/s | yes |
| AP4 | Open orders (placed or paid) for the warehouse dashboard | 1/s | no, seconds are fine |
| AP5 | Product by SKU | 3 000/s | no |
| AP6 | Revenue by category per month | a few per day | no |
Write the table before you write a key. The rate column tells you which patterns need a key of their own and which can be a slower path. The last column tells you which patterns cannot be served from anything asynchronous: a replica, a cache, or a secondary index that is updated after the write is acknowledged. AP6 is analytics; no store in this chapter is the right home for it, and the chapter on columnar engines later in this module is where it goes.
Redis: a data-structure server
Redis keeps every key in memory and executes commands one at a time on a single thread. That is the whole performance model. A GET or HSET costs a hash-table lookup plus a network round trip, so one instance serves on the order of 100 000 operations per second per core with sub-millisecond latency, and pipelining many commands per round trip takes it several times higher. Because commands run one at a time, each command is atomic, and MULTI/EXEC or a Lua script makes a group of them atomic. It also means one slow command stops everyone: KEYS * on ten million keys, an HGETALL on a hash with a million fields, or a Lua script with a loop blocks every other client for its whole duration.
The value of Redis is in its types. A hash is a small record. A sorted set keeps members ordered by a score with O(log n) insert and range reads, which is a leaderboard, a per-customer order index by timestamp, or a sliding-window rate limiter in a few commands. A list is a queue, a stream is an append-only log with consumer groups. For the shop, carts (a hash per cart, with a TTL), sessions, a ‘top products this hour’ sorted set and rate limits are natural Redis data.
Durability is a configuration, not a property. The defaults matter. With no configuration file, Redis takes RDB snapshots on the save points 3600 1 300 100 60 10000 (after an hour if one key changed, after five minutes if 100 did, after a minute if 10 000 did) and has the append-only file switched off. A kill -9 or a power cut loses everything since the last snapshot, which can be an hour. With appendonly yes and the default appendfsync everysec, a background thread fsyncs the log once a second and you lose about a second. appendfsync always fsyncs on every write batch and costs you the fsync price from the first chapter on every command. Snapshots also fork() the process: with a large dataset the fork itself can stall the server for tens to hundreds of milliseconds, and copy-on-write can need up to the dataset’s size again in RAM if writes are heavy during the snapshot. Size a Redis host for roughly twice its data, not once.
Replication is asynchronous. A replica acknowledges nothing before the primary replies to the client. WAIT 1 100 blocks until one replica has the preceding writes or 100 ms pass, and returns how many did, but Redis’s own documentation is explicit that it does not make Redis strongly consistent: a failover can still promote a replica that missed writes. Redis Cluster splits the keyspace into 16 384 hash slots; multi-key commands work only when all keys hash to one slot, which you force with a hash tag such as cust:{42}:cart and cust:{42}:orders.
Memory is the limit and the bill. Every key carries dozens of bytes of overhead beyond its payload. When used_memory reaches maxmemory, the default policy noeviction makes every write fail with OOM command not allowed, and the alternatives (allkeys-lru and friends) keep writes working by silently deleting data. For a cache that is right. For carts or orders it is data loss, and the lab makes it happen.
Redis can hold the shop’s orders, and the lab does it: a hash per order, a sorted set per customer of order ids scored by timestamp. AP2 and AP3 become a ZREVRANGE and a pipelined HGETALL, both well under a millisecond. But nothing enforces a schema, there are no secondary indexes unless you maintain them by hand in the same MULTI, and the durability story is ‘about a second, if you configured it’. Use Redis as the system of record only for data you can afford to lose or rebuild.
DynamoDB: Dynamo’s name, not its design
The 2007 Dynamo paper described Amazon’s shopping-cart store: leaderless replication, sloppy quorums with hinted handoff, consistent hashing for placement (the consistent hashing lesson shows the ring), and vector clocks so that concurrent writes come back as siblings for the application to merge. Cassandra and Riak inherited that design. DynamoDB, launched in 2012, took the name and the goal of predictable performance at any scale, but its 2022 USENIX ATC paper describes something different. A table is split into partitions by a hash of the partition key. Each partition is a replication group of three replicas in three availability zones that elect a leader with Multi-Paxos. Writes go to the leader and are acknowledged once a quorum has logged them. There are no siblings and no vector clocks: the last write a leader accepted wins, and conditional writes (ConditionExpression) give you compare-and-set.
Reads are eventually consistent by default and may go to any replica. ConsistentRead=True sends the read to the leader and costs twice as much. A partition serves at most 3 000 read units and 1 000 write units per second, and splits as it grows past about 10 GB or as traffic rises. Those per-partition ceilings are the reason every DynamoDB design discussion is about the partition key: a key that concentrates traffic (today’s date, a celebrity’s id, the status ‘placed’) is throttled at those numbers no matter how much table capacity you pay for. Adaptive capacity shifts unused throughput towards hot partitions and splits hot ones, which helps with skew but not with one key receiving more than one partition’s worth.
The rest of the API follows from the storage layout. GetItem reads one item by its full primary key. Query reads one item collection (all items with one partition key) in sort-key order, optionally narrowed by a sort-key condition such as begins_with, at most 1 MB per page. Scan reads the whole table. A FilterExpression is applied after the read, so you pay for every item the Query or Scan touched, not the ones it returned. An item is at most 400 KB. TransactWriteItems makes up to 100 actions atomic across items and tables, at double the write cost. A table can have up to 20 global secondary indexes, each effectively a second table, keyed however you like and maintained asynchronously, and up to 5 local secondary indexes that share the partition key, allow strongly consistent reads, must be created with the table, and cap each item collection at 10 GB.
Single-table design for the shop
Single-table design puts every entity in one table with generic key attributes, PK and SK, and overloads them so that the items each access pattern needs sit in one item collection. Here is the shop:
| Entity | PK | SK | GSI1PK / GSI1SK | GSI2PK / GSI2SK |
|---|---|---|---|---|
| Customer | CUST#42 |
PROFILE |
||
| Order header | ORDER#1001 |
HEADER |
CUST#42 / ORDER#2026-10-30T09:12:00+00:00 |
OPEN#1 / placed#2026-10-30T09:12:00+00:00 (only while open) |
| Order line | ORDER#1001 |
ITEM#001, ITEM#002, … |
||
| Payment | ORDER#1001 |
PAYMENT |
||
| Product | PRODUCT#SKU-000123 |
PRODUCT |
Each access pattern is now one request:
- AP1, AP5:
GetItemonCUST#42 / PROFILEorPRODUCT#sku / PRODUCT. - AP3:
Query PK = ORDER#1001returns the header, the lines and the payment in one round trip, sorted by SK. Because it is the base table, it can beConsistentRead, which AP3’s last column demands. - AP2:
Query GSI1 where GSI1PK = CUST#42 and begins_with(GSI1SK, 'ORDER#'), descending,Limit=10. Sort keys are ISO-8601 strings, so lexical order is time order. This is the Predict’s trap: it is a GSI, so it is eventually consistent. Checkout must render the new order from what it wrote, or AP2 must be redesigned onto the base table (customer’s order summaries underPK = CUST#42, written in the same transaction as the order). - AP4: GSI2 is sparse. Only open orders carry
GSI2PK; when an order ships, the update removes the attribute and DynamoDB deletes it from the index. The dashboard reads a few hundred open orders instead of filtering two million. The partition key is write-sharded:OPEN#plusorder_id % 10. Without the suffix, every new order in the shop writes the same GSI partition, and at about 1 000 writes per second that one partition throttles, and GSI throttling throttles the base table’s writes too. The price is that the dashboard runs ten Queries and merges them.
Count what that layout costs on writes. Placing an order puts five items (header, three lines, payment) in one TransactWriteItems: 10 write units. The header also writes GSI1 and GSI2, one unit each. Each status change that alters GSI2SK costs two GSI writes (a delete and a put), plus the base write. Denormalisation in DynamoDB is paid in write units on every change, forever.
And count what it costs to ask a new question. Finance wants ‘every order containing product 123’. No key has product_id in it. Your options are a Scan with a filter, which reads the whole table, or a new GSI keyed on product_id, which needs that attribute on the line items (it is there) and backfills automatically, but takes hours on a large table and adds a write to every future order line. ‘All orders over 500 euros from Nigerian customers last March’ needs the customer’s country on the order and a key that encodes it; that is a data migration. The lab runs the first question both ways and prints what the Scan read.
MongoDB: documents and the embed-or-reference decision
MongoDB stores BSON documents in collections, on the WiredTiger engine: B-trees, document-level concurrency control, compression, and a journal. Unlike DynamoDB it has a real query language and secondary indexes that are updated in the same write as the document on the primary, so a query on a secondary index sees your write as soon as the primary does. It has compound, multikey (one index entry per array element), partial and TTL indexes, and an aggregation pipeline that can group, join ($lookup) and reshape. For ad-hoc questions it sits between DynamoDB and Postgres.
The modelling decision is embed or reference. A document is read and written as a unit and capped at 16 MiB. So:
- Embed what is owned, bounded and read together. An order’s one to five lines and its payment belong inside the order document: AP3 is one
find_oneby_id, one index lookup, one document. - Reference what grows without bound. A customer’s orders do not go inside the customer document. The shop’s heaviest customers place about twenty times as many orders as the median one; embedding makes their documents the largest, every new order rewrites the whole thing, and over years some approach the 16 MiB wall. The order holds
customer_id, and an index on(customer_id, created_at)serves AP2. - Copy the few fields you show alongside (the customer’s name and country inside each order), accepting that a name change does not propagate. That is the ‘extended reference’ pattern, and it is the same denormalisation trade the modelling chapter made in SQL, with the same update anomaly.
The consistency knobs are per operation and the defaults are where teams get hurt. Write concern says how many replica-set members must have the write before the client hears ‘ok’. Since 5.0 the implicit default is w: "majority" (journaled on a majority), except in a replica set with an arbiter where data-bearing voters are not more than a majority, where it falls back to w: 1. Before 5.0 it was w: 1 everywhere, and that is the default Jepsen measured losing acknowledged writes on failover. Read concern says what a read may return. The default, local, returns the node’s newest data even if it has not reached a majority and may yet be rolled back. majority returns only majority-committed data. linearizable applies to single-document reads on the primary and waits to confirm the node is still primary. snapshot is for transactions. Read preference decides which member serves the read; anything other than primary gives you replica lag. Causal consistency (read your writes, monotonic reads) holds within a causally consistent session and only with majority reads and writes.
Multi-document transactions exist since 4.0 on replica sets and 4.2 across shards, with a 60-second default lifetime (transactionLifetimeLimitSeconds). They work, but they cost coordination and they are a sign the model fights the data: if most writes need a transaction across documents, the data wanted a relational schema.
The three side by side
| Redis | DynamoDB | MongoDB | Postgres (baseline) | |
|---|---|---|---|---|
| Efficient reads | by key; ranges in sorted sets | by PK; SK ranges; GSI keys | any indexed field; aggregation | any indexed column; joins |
| New question | new structure, maintained by hand | Scan, or new GSI plus backfill | new index, online | new index, online |
| Secondary index consistency | whatever your code does | eventual (GSI), strong (LSI) | same as the document on the primary | transactional |
| Read consistency options | primary only is current | eventual or strong per read | read concern and read preference per op | snapshot per statement or transaction |
| Multi-item atomicity | MULTI/EXEC, Lua, one slot | 100 actions, 2x cost | multi-document transactions | everything |
| Scaling unit | instance, then 16 384 slots | partition: 3 000 RCU / 1 000 WCU / ~10 GB | replica set, then shards | one primary |
| What you pay for | RAM, around the clock | requests and GB-month | instances | instances |
| First failure you meet | OOM or lost writes after a crash | hot partition, Scan bill | unbounded documents, weak defaults | write ceiling of one node |
What the bill looks like
DynamoDB is the one store here whose price is a function of your access patterns, so you can do the arithmetic before you build. On-demand prices in us-east-1, checked November 2026: $0.625 per million write request units (1 KB each, two for a transactional write), $0.125 per million read request units (4 KB per unit for a strong read, half a unit eventually consistent, two for transactional), and $0.25 per GB-month of storage.
A shop with a million orders a month, each roughly 15 write units over its life including GSI maintenance, spends 15 million WRU, about $9.40 a month. Thirty million strongly consistent order-page reads of under 4 KB is 30 million RRU, $3.75. Ten million ‘my orders’ pages on the GSI, about 5 KB each eventually consistent, is another 10 million RRU, $1.25. Eighty GB of table and indexes is $20. Around $35 a month for the operational path, with no servers. That is the case for DynamoDB.
Now someone builds the warehouse dashboard as a Scan with a filter, once a minute. An 80 GB table is about 21 million 4 KB units; an eventually consistent Scan reads it for about 10.5 million RRU, $1.31 per run. Once a minute for a month is 43 200 runs: about $56 600. It also cannot finish: at the default per-table limit of 40 000 read units per second the Scan takes over four minutes. The sparse GSI2 answers the same question for a few read units. Every key-value store has this cliff; DynamoDB prints it on the invoice.
Redis and MongoDB bill by the machine. Redis’s machine is sized by RAM, at twice the dataset for fork headroom, and it costs the same idle as busy. MongoDB’s is sized like Postgres’s: working set in cache, disk for the rest.
You will copy a slice of the shop (the first 1 000 customers and their orders, about 4 000 orders) into all three stores, run the same access patterns against each next to Postgres, ask a question nobody planned for, and then lose data in Redis twice. Work in a new directory, labs/databases/d3-kv/.
1. Start the shop and the three stores.
cd labs/databases
docker compose up -d
docker compose exec -T db psql -U atlas -d shop -v scale=0.1 -f /shop/load.sql # skip if already loaded
docker compose exec -T db psql -U atlas -d shop -c "CREATE INDEX IF NOT EXISTS orders_customer_created ON orders (customer_id, created_at);"
docker run -d --name d3-redis -p 6390:6379 redis:8.6.8
docker run -d --name d3-redis-aof -p 6391:6379 redis:8.6.8 redis-server --appendonly yes
docker run -d --name d3-dynamo -p 8000:8000 amazon/dynamodb-local:3.3.2 -jar DynamoDBLocal.jar -inMemory -sharedDb
docker run -d --name d3-mongo -p 27017:27017 mongo:8.0.34 --replSet rs0 --bind_ip_all
sleep 5
docker exec d3-mongo mongosh --quiet --eval 'rs.initiate({_id: "rs0", members: [{_id: 0, host: "localhost:27017"}]})'
docker exec d3-redis redis-cli CONFIG GET save
docker exec d3-redis redis-cli CONFIG GET appendonlyrs.initiate call prints { ok: 1 }: MongoDB is a one-member replica set, which is what transactions and majority writes need. CONFIG GET save prints 3600 1 300 100 60 10000 and appendonly prints no: these are the defaults the body described, and the d3-redis container runs with them. d3-redis-aof is the same image with the append-only file on.2. Install the clients and write the slice reader.
mkdir -p d3-kv && cd d3-kv
python3 -m venv .venv && . .venv/bin/activate
pip install "psycopg[binary]==3.3.6" boto3==1.43.123 pymongo==4.19.0 redis==8.1.0Create shop_slice.py. It reads customers, their orders, each order’s lines as a JSON array, and the payment:
import os
import psycopg
from psycopg.rows import dict_row
DSN = os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")
N = int(os.environ.get("CUSTOMERS", "1000"))
def load():
"""Return [(customer, [order, ...])]; each order has 'items' and 'payment'."""
with psycopg.connect(DSN, row_factory=dict_row) as db:
custs = db.execute(
"SELECT id, email, name, country, created_at FROM customers WHERE id <= %s ORDER BY id",
(N,)).fetchall()
orders = db.execute("""
SELECT o.id, o.customer_id, o.status, o.total_cents, o.created_at,
json_agg(json_build_object('product_id', i.product_id, 'qty', i.qty,
'unit_price_cents', i.unit_price_cents) ORDER BY i.id) AS items
FROM orders o JOIN order_items i ON i.order_id = o.id
WHERE o.customer_id <= %s GROUP BY o.id ORDER BY o.id""", (N,)).fetchall()
pays = {r["order_id"]: r for r in db.execute("""
SELECT p.order_id, p.id, p.provider, p.status, p.amount_cents
FROM payments p JOIN orders o ON o.id = p.order_id
WHERE o.customer_id <= %s""", (N,))}
by_cust = {}
for o in orders:
p = pays.get(o["id"])
o["payment"] = p and {k: p[k] for k in ("id", "provider", "status", "amount_cents")}
by_cust.setdefault(o["customer_id"], []).append(o)
return [(c, by_cust.get(c["id"], [])) for c in custs]json_agg returns each order’s lines as a list, which psycopg turns into Python dicts.3. Load the three models.
Create load.py:
import json, time
import boto3, pymongo, redis
from boto3.dynamodb.types import TypeSerializer
from shop_slice import load
ddb = boto3.client("dynamodb", endpoint_url="http://localhost:8000", region_name="eu-west-1",
aws_access_key_id="local", aws_secret_access_key="local")
ser = TypeSerializer()
mongo = pymongo.MongoClient("mongodb://localhost:27017/?directConnection=true").shop
r = redis.Redis(port=6390)
def create_table():
if "shop" in ddb.list_tables()["TableNames"]:
ddb.delete_table(TableName="shop")
s = lambda n: {"AttributeName": n, "AttributeType": "S"}
k = lambda h, rng: [{"AttributeName": h, "KeyType": "HASH"}, {"AttributeName": rng, "KeyType": "RANGE"}]
ddb.create_table(
TableName="shop", BillingMode="PAY_PER_REQUEST",
AttributeDefinitions=[s(n) for n in ("PK", "SK", "GSI1PK", "GSI1SK", "GSI2PK", "GSI2SK")],
KeySchema=k("PK", "SK"),
GlobalSecondaryIndexes=[
{"IndexName": "GSI1", "KeySchema": k("GSI1PK", "GSI1SK"), "Projection": {"ProjectionType": "ALL"}},
{"IndexName": "GSI2", "KeySchema": k("GSI2PK", "GSI2SK"),
"Projection": {"ProjectionType": "INCLUDE", "NonKeyAttributes": ["customer_id", "total_cents"]}},
])
def order_items(c, o):
ts = o["created_at"].isoformat()
header = {"PK": f"ORDER#{o['id']}", "SK": "HEADER", "customer_id": c["id"], "status": o["status"],
"total_cents": o["total_cents"], "created_at": ts,
"GSI1PK": f"CUST#{c['id']}", "GSI1SK": f"ORDER#{ts}"}
if o["status"] in ("placed", "paid"): # sparse, write-sharded index
header |= {"GSI2PK": f"OPEN#{o['id'] % 10}", "GSI2SK": f"{o['status']}#{ts}"}
lines = [{"PK": f"ORDER#{o['id']}", "SK": f"ITEM#{n:03d}", **it} for n, it in enumerate(o["items"], 1)]
pay = [{"PK": f"ORDER#{o['id']}", "SK": "PAYMENT", **o["payment"]}] if o["payment"] else []
return [header, *lines, *pay]
data = load()
print(f"{len(data)} customers, {sum(len(os) for _, os in data)} orders")
t = time.perf_counter(); create_table()
for c, orders in data:
ddb.put_item(TableName="shop", Item={k: ser.serialize(v) for k, v in {
"PK": f"CUST#{c['id']}", "SK": "PROFILE", "email": c["email"], "name": c["name"],
"country": c["country"], "created_at": c["created_at"].isoformat()}.items()})
for o in orders: # one atomic write per order
ddb.transact_write_items(TransactItems=[
{"Put": {"TableName": "shop", "Item": {k: ser.serialize(v) for k, v in it.items()}}}
for it in order_items(c, o)])
print(f"dynamodb {time.perf_counter() - t:.1f}s")
t = time.perf_counter()
mongo.customers.drop(); mongo.orders.drop()
mongo.customers.insert_many([{"_id": c["id"], "email": c["email"], "name": c["name"],
"country": c["country"], "created_at": c["created_at"]} for c, _ in data])
mongo.orders.insert_many([{"_id": o["id"], "customer_id": c["id"],
"customer": {"name": c["name"], "country": c["country"]}, # extended reference
"status": o["status"], "total_cents": o["total_cents"],
"created_at": o["created_at"], "items": o["items"], "payment": o["payment"]}
for c, orders in data for o in orders])
mongo.orders.create_index([("customer_id", 1), ("created_at", -1)])
print(f"mongodb {time.perf_counter() - t:.1f}s")
t = time.perf_counter()
r.flushdb(); p = r.pipeline(transaction=False)
for c, orders in data:
p.hset(f"cust:{c['id']}", mapping={"email": c["email"], "name": c["name"], "country": c["country"]})
for o in orders:
p.hset(f"order:{o['id']}", mapping={"customer_id": c["id"], "status": o["status"],
"total_cents": o["total_cents"], "created_at": o["created_at"].isoformat(),
"items": json.dumps(o["items"])})
p.zadd(f"cust:{c['id']}:orders", {o["id"]: o["created_at"].timestamp()})
for it in o["items"]:
p.zincrby("product:revenue", it["qty"] * it["unit_price_cents"], it["product_id"])
p.execute()
print(f"redis {time.perf_counter() - t:.1f}s")python load.py1000 customers, 4000 orders (the exact number depends on the scale; the 20 heavy customers, ids 1, 51, 101, …, hold about a third of them). DynamoDB Local takes the longest, tens of seconds, because every order is its own TransactWriteItems round trip. MongoDB and Redis take about a second: insert_many and a pipeline batch thousands of writes per round trip. Batching is the first performance lever in all three.4. Run the access patterns against all four stores.
Create queries.py:
import statistics, time
import boto3, psycopg, pymongo, redis
from boto3.dynamodb.conditions import Key
table = boto3.resource("dynamodb", endpoint_url="http://localhost:8000", region_name="eu-west-1",
aws_access_key_id="local", aws_secret_access_key="local").Table("shop")
mongo = pymongo.MongoClient("mongodb://localhost:27017/?directConnection=true").shop
r = redis.Redis(port=6390, decode_responses=True)
pg = psycopg.connect("postgres://atlas:atlas@localhost:5432/shop")
CUST = 1
OID = mongo.orders.find_one({"customer_id": CUST}, sort=[("created_at", -1)])["_id"]
def timed(name, fn, n=200):
ts = []
for _ in range(n):
t = time.perf_counter(); out = fn(); ts.append((time.perf_counter() - t) * 1000)
print(f" {name:<9} {statistics.median(ts):6.2f} ms ({len(out)} rows)")
def redis_recent():
p = r.pipeline(transaction=False)
for oid in r.zrevrange(f"cust:{CUST}:orders", 0, 9):
p.hgetall(f"order:{oid}")
return p.execute()
print(f"AP2: ten most recent orders of customer {CUST}")
timed("postgres", lambda: pg.execute("SELECT id, status, total_cents, created_at FROM orders "
"WHERE customer_id = %s ORDER BY created_at DESC LIMIT 10", (CUST,)).fetchall())
timed("dynamodb", lambda: table.query(IndexName="GSI1", ScanIndexForward=False, Limit=10,
KeyConditionExpression=Key("GSI1PK").eq(f"CUST#{CUST}") & Key("GSI1SK").begins_with("ORDER#"))["Items"])
timed("mongodb", lambda: list(mongo.orders.find({"customer_id": CUST}).sort("created_at", -1).limit(10)))
timed("redis", redis_recent)
print(f"AP3: order {OID} with lines and payment")
timed("postgres", lambda: pg.execute("SELECT * FROM orders o JOIN order_items i ON i.order_id = o.id "
"JOIN payments p ON p.order_id = o.id WHERE o.id = %s", (OID,)).fetchall())
timed("dynamodb", lambda: table.query(KeyConditionExpression=Key("PK").eq(f"ORDER#{OID}"),
ConsistentRead=True)["Items"])
timed("mongodb", lambda: [mongo.orders.find_one({"_id": OID})])
timed("redis", lambda: [r.hgetall(f"order:{OID}")])
res = table.query(KeyConditionExpression=Key("PK").eq(f"ORDER#{OID}"), ConsistentRead=True,
ReturnConsumedCapacity="TOTAL")
print("AP3 consumed:", res.get("ConsumedCapacity"))
try:
table.query(IndexName="GSI1", ConsistentRead=True, KeyConditionExpression=Key("GSI1PK").eq(f"CUST#{CUST}"))
except Exception as e:
print("consistent GSI read:", type(e).__name__, str(e)[:90])
print("AP4 open orders:", sum(table.query(IndexName="GSI2", Select="COUNT",
KeyConditionExpression=Key("GSI2PK").eq(f"OPEN#{s}"))["Count"] for s in range(10)))
print("top products by revenue (redis):", r.zrevrange("product:revenue", 0, 2, withscores=True))
print("mongo defaults:", mongo.client.admin.command("getDefaultRWConcern"))python queries.py1.0 capacity unit (some versions of DynamoDB Local print None here; the service always reports it). The consistent GSI read fails with ClientError ... ValidationException: the Predict, confirmed by the API. AP4 counts a few hundred open orders from ten small Queries. The Mongo defaults show defaultWriteConcern: { w: 'majority', ... } and defaultReadConcern: { level: 'local' }, both with source implicit.5. Ask a question nobody listed. Finance wants every order containing the product that sold most. Create adhoc.py:
import boto3, pymongo, psycopg, redis
from boto3.dynamodb.conditions import Attr
table = boto3.resource("dynamodb", endpoint_url="http://localhost:8000", region_name="eu-west-1",
aws_access_key_id="local", aws_secret_access_key="local").Table("shop")
mongo = pymongo.MongoClient("mongodb://localhost:27017/?directConnection=true").shop
pid = int(redis.Redis(port=6390).zrevrange("product:revenue", 0, 0)[0])
print("product", pid)
scanned = matched = 0; units = 0.0; kw = {}
while True: # a Scan is paginated at 1 MB
page = table.scan(FilterExpression=Attr("product_id").eq(pid), ReturnConsumedCapacity="TOTAL", **kw)
scanned += page["ScannedCount"]; matched += page["Count"]
units += (page.get("ConsumedCapacity") or {}).get("CapacityUnits", 0)
if "LastEvaluatedKey" not in page: break
kw = {"ExclusiveStartKey": page["LastEvaluatedKey"]}
print(f"dynamodb scan: read {scanned} items to return {matched}; {units} read units")
mongo.orders.create_index("items.product_id") # multikey index, online
plan = mongo.orders.find({"items.product_id": pid}).explain()["queryPlanner"]["winningPlan"]
print("mongodb:", mongo.orders.count_documents({"items.product_id": pid}), "orders via", plan)
pg = psycopg.connect("postgres://atlas:atlas@localhost:5432/shop")
print("postgres:", pg.execute("SELECT count(DISTINCT order_id) FROM order_items i JOIN orders o "
"ON o.id = i.order_id WHERE i.product_id = %s AND o.customer_id <= 1000", (pid,)).fetchone()[0])python adhoc.pyIXSCAN on items.product_id (nested under a FETCH stage); the new question cost one command. In DynamoDB the equivalent is a GSI on product_id, which you would add with update_table and wait for the backfill.6. Lose data in Redis by crashing it. Recreate both Redis containers so the save-point clocks start at zero, write a thousand carts into each within the first minute, and kill them:
docker rm -f d3-redis d3-redis-aof
docker run -d --name d3-redis -p 6390:6379 redis:8.6.8
docker run -d --name d3-redis-aof -p 6391:6379 redis:8.6.8 redis-server --appendonly yes
sleep 2
for port in 6390 6391; do
python -c "import redis; r = redis.Redis(port=$port); [r.set(f'cart:{i}', 'x') for i in range(1000)]; print($port, 'before crash:', r.dbsize())"
done
sleep 2
docker kill d3-redis d3-redis-aof # SIGKILL: no clean shutdown, no final save
docker start d3-redis d3-redis-aof && sleep 2
for port in 6390 6391; do python -c "import redis; print($port, 'after crash:', redis.Redis(port=$port).dbsize())"; donebefore crash: 1000. After the crash, 6390 after crash: 0: a thousand changes in the first minute trips none of the save points (3600 1 needs an hour, 300 100 five minutes, 60 10000 ten thousand changes), so no snapshot was ever written. 6391 after crash: 1000: the AOF was fsynced within a second and replayed on start. On a long-running default instance you lose whatever arrived since the last snapshot, which redis-cli LASTSAVE dates for you. That is the gap between Redis’s defaults and the durability most teams assume. (The recreated d3-redis no longer holds the shop slice; re-run python load.py if you want to repeat step 4.)docker exec d3-redis redis-cli CONFIG SET maxmemory 3mb, then python -c "import redis; r = redis.Redis(port=6390); [r.hset(f'cart:{i}', mapping={'sku': 'SKU-1', 'qty': 1}) for i in range(100000)]". With the default maxmemory-policy noeviction it stops with OOM command not allowed when used memory > 'maxmemory': writes fail loudly, reads keep working. Now run docker exec d3-redis redis-cli CONFIG SET maxmemory-policy allkeys-lru and the same Python again. It completes without an error, and docker exec d3-redis redis-cli DBSIZE shows far fewer than 100 000 keys: Redis deleted the oldest carts to make room for new ones, and nobody was told. For a cache that is the right behaviour; for carts or orders it is silent loss, which is why Redis holding data of record needs its own instance with noeviction and an alert on used_memory. Clean up with docker rm -f d3-redis d3-redis-aof d3-dynamo d3-mongo.The shop's orders live in one Postgres 17 primary: 2 million orders, 300 writes per second at peak, the primary at 20% CPU. A new lead proposes moving orders to a NoSQL store 'before we hit the wall', citing a conference talk. Product also wants carts that survive a page refresh and a 'trending now' widget. What do you do?
- PAPER Dynamo: Amazon's Highly Available Key-value Store DeCandia et al., 2007
The design that Cassandra and Riak inherited and DynamoDB did not. Read it to recognise leaderless replication and vector-clock siblings when you meet them; skip the related-work survey. Read: sections 4.1 to 4.6 (partitioning, replication, versioning, sloppy quorums) and section 6 (lessons).
- PAPER Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service Elhemali et al., 2022
How DynamoDB actually works: Multi-Paxos replication groups per partition, the per-partition throughput limits and how adaptive capacity evolved. Explains every number in this chapter's DynamoDB section. Read: sections 2 to 5: architecture, partitions and admission control, durability, availability.
- BOOK The DynamoDB Book Alex DeBrie, 2020
The working manual for single-table design: overloaded keys, sparse indexes, write sharding and migrations. Skip the SDK walkthroughs if you already use one. Read: the strategy chapters on one-to-many and many-to-many relationships, filtering and sorting, then one worked example.
- DOC Best practices for modelling relational data in DynamoDB
AWS's own worked example of turning a normalised schema into an access-pattern-driven table, with the GSI overloading this chapter uses. Short; read alongside the quotas page.
- DOC MongoDB data modelling
The embed-versus-reference rules and the named schema patterns (extended reference, bucket, subset) in MongoDB's own words. Read the patterns; skip the Atlas UI material.
- DOC Redis persistence
The precise durability contract of RDB, AOF and the fsync policies, including the warning about enabling AOF on a live server without updating the config file. Required before you trust Redis with anything.
- POST Jepsen: MongoDB 4.2.6 Kyle Kingsbury, 2020
What weak defaults and misunderstood read and write concerns do under failure, measured. The defaults have changed since; the method and the failure shapes have not. Read the summary and the transaction section.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.