AWS from zero · Part 3: Storage and data · Lesson 18 of 38 · about 45 minutes

DynamoDB

A database with no servers, no sizes and no SQL. The bakery's orders become items in a table designed around the questions the shop asks, and the lab measures what each way of reading costs: a query that reads only what it returns, and a scan that reads everything to find two orders. Writes that check before they change anything, a question the table can't answer, and the same accidental delete as Lesson 17, back in about three minutes. Well under a cent.

By the end you'll know

  • How DynamoDB differs from RDS, and when each is the right choice
  • What partition keys, sort keys and items are, and why you design the table from the questions first
  • The difference between get, query and scan, measured in what each one costs
  • How indexes answer questions the keys can't
  • How conditional writes stop two changes clobbering each other
  • How point-in-time recovery works here, and what a restored table leaves behind

Before you start

  • You need: the juniper-rye profile from Lesson 4, signed in. No VPC and no server: your machine talks to DynamoDB directly.
  • The script: ddb-lab.sh from the practice folder's lesson-18. Everything it creates is named jr-lesson18-*, and its delete step removes it.
  • How the script talks to AWS: only through the AWS CLI. The few lines of Python in it just turn the CLI's JSON into readable tables and never connect to AWS; boto3, AWS's Python library, comes in Lesson 20.
  • To see every call the script makes, put SHOW=1 in front of any step, such as SHOW=1 ./ddb-lab.sh data. The lesson's "By hand" section lists them all too.
  • Where you run things: your own machine, labeled (Your machine).
  • Every output below is from a real run on November 11, 2026. Amaka, Ben and Chloe are made-up customers.

A scan reads the whole table, and you pay for all of it

A scan with a filter still reads every item, and is charged for every item it reads, not just the ones it returns. The lab's scan read 10 items to return 2. On a table of a million orders, a dashboard that scans every few seconds becomes the biggest line on the bill. Design keys and indexes so the questions you ask often are queries.

The short version

  • DynamoDB is a key-value and document database AWS runs entirely: no servers to size, no patching, and it scales from nothing to millions of requests a second.
  • Every item has a partition key, and usually a sort key. Fast questions are the ones those keys can answer.
  • Design the table from the questions you'll ask, not from the shape of the data. There are no joins, and no new questions without new keys or indexes.
  • Query reads only matching items; scan reads everything. Indexes add new ways to query.
  • Conditional writes check before changing, and point-in-time recovery restores to any second, as a new table.

What this lesson costs

PartCost, in us-east-2
Writes, on demand$0.625 per million
Reads, on demand$0.125 per million
Storage25 GB free, then $0.25 per GB a month
Point-in-time recovery$0.20 per GB a month: the table is a few KB
This lessonA few hundred reads and writes: well under 1 cent

A different kind of database

Lesson 17's PostgreSQL stores rows in tables you can ask anything of, joining them however a question needs. DynamoDB gives that up to get something else:

RDS (PostgreSQL)DynamoDB
ServersOne you size, in a VPCNone. A table, reached over HTTPS.
QuestionsAny, with SQL, joins and allThe ones its keys and indexes allow
Shape of the dataFixed columns, set up in advanceEach item can have different attributes
ScaleAs big as the server, plus read replicasEffectively unlimited, at the same speed
SpeedDepends on the querySingle-digit milliseconds, at any size
PayingEvery hour it existsPer request and per GB; nothing when idle
FitsData with many relationships, reports, questions you can't predictKnown questions at any scale: sessions, carts, orders by customer, game scores
Think of a filing cabinet in the bakery's office. Each drawer has a customer's name on it: that's the partition key. Inside, folders are kept in date order: that's the sort key. Asking for "Amaka's orders" or "Amaka's November orders" is quick: open one drawer, flip to the right place. Asking "who ordered rye?" means opening every drawer and reading every folder, unless someone keeps a second index cabinet sorted by item.

The SQL track's Not everything is a table covers the wider family of databases DynamoDB belongs to.

Is it allowed, and what does it cost?

(Your machine)

BASH
cd ~/Apps/aws-practice/lesson-18
chmod +x ddb-lab.sh
./ddb-lab.sh fence
OUTPUT
== Is this allowed in us-east-2? (DynamoDB has no dry run, so this reads instead)
  DynamoDB: allowed
== What it costs, in us-east-2, on demand (no capacity to choose)
  writes:   $0.625 per million
  reads:    $0.125 per million
  storage:  25 GB free, then $0.25 per GB a month
  point-in-time recovery: $0.20 per GB a month: this table is a few KB
  this lab: a few hundred reads and writes: well under 1 cent

The table

In the console: DynamoDB > Tables > Create table, with the partition and sort keys. Then the table > Indexes > Create index.

(Your machine)

BASH
./ddb-lab.sh build
OUTPUT
== The orders table: partition key pk, sort key sk, on demand, with an index by status
  active after 21 seconds
  table jr-lesson18-orders: ACTIVE
  keys: pk (partition key), sk (sort key)
  billing: PAY_PER_REQUEST
  index by-status: status (partition), placedAt (sort), ACTIVE
  items: 0, size: 0 bytes
BASH
aws dynamodb create-table --table-name jr-lesson18-orders --billing-mode PAY_PER_REQUEST \
  --attribute-definitions AttributeName=pk,AttributeType=S AttributeName=sk,AttributeType=S \
                          AttributeName=status,AttributeType=S AttributeName=placedAt,AttributeType=S \
  --key-schema AttributeName=pk,KeyType=HASH AttributeName=sk,KeyType=RANGE \
  --global-secondary-indexes file://by-status.json

Twenty-one seconds, and nothing to size. Compare Lesson 17's seven and a half minutes. The table only declares its keys: every other attribute is up to each item.

PartIsIn the lab
ItemOne record, up to 400 KB, like a rowAn order, or a customer's profile
AttributeOne named value in an itemitem, qty, status
Partition keyDecides which partition, which slice of storage, holds the item. Called HASH in the API.pk, like CUSTOMER#amaka
Sort keyOrders items within a partition. Called RANGE.sk, like ORDER#2026-11-10#1001
Global secondary index (GSI)A copy of the table, kept up to date, with different keysby-status: by status, then time placed
Capacity modeOn demand pays per request; provisioned pays per hour for a set rateOn demand: right for unpredictable or small loads

The partition key matters for speed as well as questions. DynamoDB spreads partitions over many machines; if every item shared one partition key, say today's date, every request would land on one machine, a hot partition, and requests would be throttled. Keys with many different values, like customers, spread the load.

Designing from the questions

With SQL, you design tables around the data and work out the questions later. With DynamoDB, you list the questions first, then choose keys that answer them:

The shop asksAnswered by
A customer's profile and every orderQuery: pk = CUSTOMER#amaka
A customer's orders in one monthQuery: that pk, and sk begins with ORDER#2026-11
One particular orderGet: the full pk and sk
Every order that's baking, oldest firstQuery the by-status index
Who ordered rye?Nothing. It would need another index, keyed on the item.

Two habits from that table are common DynamoDB practice. The keys are generic, pk and sk, with prefixes like CUSTOMER# and ORDER#, so one table can hold profiles and orders side by side: that's called single-table design. And the sort key starts with the date, so "orders in November" is just "starts with ORDER#2026-11", because sort keys are kept in order.

Reading: get, query and scan

In the console: the table > Explore table items, then Scan or Query at the top.

(Your machine)

BASH
./ddb-lab.sh data
OUTPUT
== Writing 3 customers and 7 orders in one batch
  10 items written (3 profiles, 7 orders); ben's order 1005 has a note no other item has
== 1. Get one item, by its full key (eventually consistent, then strongly consistent)
    CUSTOMER#amaka    ORDER#2026-11-10#1001       sourdough    2     ready    
    (capacity used: 0.5 read units)
    CUSTOMER#amaka    ORDER#2026-11-10#1001       sourdough    2     ready    
    (capacity used: 1.0 read units)
== 2. Query: everything for one customer
    CUSTOMER#amaka    ORDER#2026-10-28#0994       rye          1     collected
    CUSTOMER#amaka    ORDER#2026-11-10#1001       sourdough    2     ready    
    CUSTOMER#amaka    ORDER#2026-11-11#1006       croissant    6     baking   
    CUSTOMER#amaka    PROFILE                                                 
    (returned 4, read 4, capacity used: 0.5 read units)
== 3. Query: just their November orders (sort key begins with ORDER#2026-11)
    CUSTOMER#amaka    ORDER#2026-11-10#1001       sourdough    2     ready    
    CUSTOMER#amaka    ORDER#2026-11-11#1006       croissant    6     baking   
    (returned 2, read 2, capacity used: 0.5 read units)
== 4. Scan with a filter: every order that's ready
    CUSTOMER#amaka    ORDER#2026-11-10#1001       sourdough    2     ready    
    CUSTOMER#chloe    ORDER#2026-11-10#1002       baguette     3     ready    
    (returned 2, read 10, capacity used: 2.0 read units)
== 5. Query the by-status index: every order that's baking, oldest first
    CUSTOMER#ben      ORDER#2026-11-11#1004       rye          1     baking     2026-11-11T06:05      
    CUSTOMER#amaka    ORDER#2026-11-11#1006       croissant    6     baking     2026-11-11T06:30      
    (returned 2, read 2, capacity used: 0.5 read units)
BASH
aws dynamodb get-item --table-name jr-lesson18-orders \
  --key '{"pk":{"S":"CUSTOMER#amaka"},"sk":{"S":"ORDER#2026-11-10#1001"}}' --return-consumed-capacity TOTAL
aws dynamodb query --table-name jr-lesson18-orders \
  --key-condition-expression 'pk = :c AND begins_with(sk, :p)' \
  --expression-attribute-values '{":c":{"S":"CUSTOMER#amaka"},":p":{"S":"ORDER#2026-11"}}'
aws dynamodb scan --table-name jr-lesson18-orders --filter-expression '#s = :r' \
  --expression-attribute-names '{"#s":"status"}' --expression-attribute-values '{":r":{"S":"ready"}}'
aws dynamodb query --table-name jr-lesson18-orders --index-name by-status \
  --key-condition-expression '#s = :b' --expression-attribute-names '{"#s":"status"}' \
  --expression-attribute-values '{":b":{"S":"baking"}}'
ReadReadReturnedRead unitsMeans
Get, eventually consistent110.5The cheapest read there is
Get, strongly consistent111.0Twice the price, for a guaranteed latest copy
Query, one customer440.5One partition, read in order
Query, November only220.5The sort key narrowed it before reading
Scan with a filter1022.0Read everything, then threw away eight
Query the index220.5The same answer as a scan would need, read directly

The scan read all 10 items to return 2, and cost four times a query. A filter only removes items after they've been read and paid for. On this table the difference is cents of a cent; on a million orders, the query costs the same, and the scan reads all million.

A read unit covers up to 4 KB, read once with strong consistency, or twice with eventual consistency. Eventually consistent reads may miss a write from the last second; strongly consistent ones never do, at double the price. Indexes are always eventually consistent.

Two quieter things in the output. Amaka's PROFILE item printed with empty columns: it has a name and no item, qty or status, and DynamoDB doesn't mind. And the index query returned the baking orders oldest first, because the index's sort key is placedAt: the oven's to-do list, in order, without sorting anything.

Writes that check first

(Your machine)

BASH
./ddb-lab.sh rules
OUTPUT
== 1. Write order 1001 again, but only if it doesn't exist yet
  refused: (ConditionalCheckFailedException): The conditional request failed
== 2. Add one croissant to Chloe's order 1003, only while it's still just placed
  done: qty is now 5
== 3. The same, for Chloe's order 1002, which is already ready
  refused: (ConditionalCheckFailedException): The conditional request failed
== 4. A question the keys can't answer: who ordered rye? (query by item)
  refused: (ValidationException): Query condition missed key schema element: pk
  the only way without an index is a scan of the whole table:
    CUSTOMER#amaka    ORDER#2026-10-28#0994       rye          1     collected
    CUSTOMER#ben      ORDER#2026-11-11#1004       rye          1     baking   
    (returned 2, read 10, capacity used: 2.0 read units)
BASH
aws dynamodb put-item --table-name jr-lesson18-orders --item file://order-1001.json \
  --condition-expression 'attribute_not_exists(sk)'
aws dynamodb update-item --table-name jr-lesson18-orders \
  --key '{"pk":{"S":"CUSTOMER#chloe"},"sk":{"S":"ORDER#2026-11-11#1003"}}' \
  --update-expression 'ADD qty :one' --condition-expression '#s = :placed' \
  --expression-attribute-names '{"#s":"status"}' --expression-attribute-values '{":one":{"N":"1"},":placed":{"S":"placed"}}'

Without a condition, put-item silently replaces whatever had the same key. attribute_not_exists(sk) makes it refuse instead, so a second order with a reused number can't wipe out the first. The update added one croissant to an order still marked placed, and refused to touch one already ready: the check and the change happen together, so nothing can slip in between. ADD increases a number where it is, without reading it first: an atomic counter. When several items must change together, TransactWriteItems does up to 100 at once, all or nothing.

The last check is the cost of the design. Query only works on keys: asking by item was refused outright, because pk is required. The answer took a full scan, 10 items read for 2 returned. If the shop asks it often, the fix is a second index keyed on item.

Point-in-time recovery

In the console: the table > Backups > Point-in-time recovery > Edit > Turn on. To restore: Restore to point in time.

(Your machine)

BASH
./ddb-lab.sh restore
OUTPUT
== Turning on point-in-time recovery (off by default)
  point-in-time recovery: ENABLED, earliest restorable 2026-11-11T13:07:54-05:00
== 2026-11-11T18:08:15Z: the accident. A cleanup script deletes every item for CUSTOMER#amaka
  deleted ORDER#2026-10-28#0994
  deleted ORDER#2026-11-10#1001
  deleted ORDER#2026-11-11#1006
  deleted PROFILE
== Waiting until the table can be restored to 2026-11-11T18:08:15Z
  latest restorable: 2026-11-11T13:08:32.527000-05:00
== Restoring to 2026-11-11T18:08:15Z, as a new table: jr-lesson18-orders-restored
  active after 201 seconds
== Amaka's items in each table
  jr-lesson18-orders:          0 items
  jr-lesson18-orders-restored: 4 items
== What the restored table brought back, and what it didn't
  index by-status: by-status
  billing: PAY_PER_REQUEST
  point-in-time recovery on the copy: DISABLED
  tags on the copy: 0
BASH
aws dynamodb update-continuous-backups --table-name jr-lesson18-orders \
  --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
aws dynamodb restore-table-to-point-in-time --source-table-name jr-lesson18-orders \
  --target-table-name jr-lesson18-orders-restored --restore-date-time 2026-11-11T18:08:15Z

The pattern is Lesson 17's, faster. Point-in-time recovery is off by default: the lab turned it on first. The CLI reports some times in your own time zone, as here: 13:08:32-05:00 is 18:08:32Z, only 17 seconds behind the accident, where RDS trailed by minutes. The restore made a new table in 201 seconds, and it had all four of Amaka's items.

Then the part people miss. The copy came back with its index and billing mode, but without point-in-time recovery and without its tags. Restores also leave out auto scaling settings, time-to-live settings, streams, CloudWatch alarms and IAM policies that name the table. A team that swaps the copy in for the original, and forgets to switch recovery back on, has a table with no undo.

The recovery window is up to 35 days. For longer, DynamoDB also takes on-demand backups, kept until deleted, and AWS Backup can schedule them (Lesson 19).

Also worth knowing

FeatureDoes
Time to live (TTL)Deletes items after a time stored in them, free, usually within a few days of it. For sessions and old carts.
StreamsA feed of every change, in order, for 24 hours. A Lambda function can act on each one: Lesson 21.
Global tablesThe same table in several Regions, every copy writable, kept in step within about a second
DAXAn in-memory cache in front of the table, for reads in microseconds
Local secondary indexSame partition key, different sort key. Only at table creation, and at most five.
PartiQLSQL-like syntax for DynamoDB. It looks like SQL, but the same key rules apply underneath.
Export to S3Copies the table to S3 without using read capacity, for analysis

Take it down

In the console: the table > Actions > Delete table, for each table.

(Your machine)

BASH
./ddb-lab.sh delete
OUTPUT
== Deleting table jr-lesson18-orders-restored
== Deleting table jr-lesson18-orders
== Tables deleted (point-in-time recovery for each ends with it)
== Left over from this lab
  tables:       0
== Anywhere in us-east-2
  tables:       0
  backups:      0

A table deletes in seconds, with its indexes. Point-in-time recovery ends with the table; on-demand backups, if there were any, would stay until deleted.

By hand: every command the script runs

The same lab without the script, in order. SHOW=1 ./ddb-lab.sh data prints the exact calls as they run. (Your machine)

BASH
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2
T=jr-lesson18-orders

# The table and its index
aws dynamodb create-table --table-name $T --billing-mode PAY_PER_REQUEST \
  --attribute-definitions AttributeName=pk,AttributeType=S AttributeName=sk,AttributeType=S \
                          AttributeName=status,AttributeType=S AttributeName=placedAt,AttributeType=S \
  --key-schema AttributeName=pk,KeyType=HASH AttributeName=sk,KeyType=RANGE \
  --global-secondary-indexes '[{"IndexName":"by-status","KeySchema":[{"AttributeName":"status","KeyType":"HASH"},{"AttributeName":"placedAt","KeyType":"RANGE"}],"Projection":{"ProjectionType":"ALL"}}]'
aws dynamodb wait table-exists --table-name $T

# Ten items in one batch (up to 25 per call), from a JSON file
aws dynamodb batch-write-item --request-items file://batch.json

# Reading
aws dynamodb get-item --table-name $T --key '{"pk":{"S":"CUSTOMER#amaka"},"sk":{"S":"ORDER#2026-11-10#1001"}}'
aws dynamodb get-item --table-name $T --key '{"pk":{"S":"CUSTOMER#amaka"},"sk":{"S":"ORDER#2026-11-10#1001"}}' --consistent-read
aws dynamodb query --table-name $T --key-condition-expression 'pk = :c' \
  --expression-attribute-values '{":c":{"S":"CUSTOMER#amaka"}}'
aws dynamodb scan --table-name $T --filter-expression '#s = :r' \
  --expression-attribute-names '{"#s":"status"}' --expression-attribute-values '{":r":{"S":"ready"}}'
aws dynamodb query --table-name $T --index-name by-status --key-condition-expression '#s = :b' \
  --expression-attribute-names '{"#s":"status"}' --expression-attribute-values '{":b":{"S":"baking"}}'

# Conditional writes
aws dynamodb put-item --table-name $T --item file://order-1001.json --condition-expression 'attribute_not_exists(sk)'
aws dynamodb update-item --table-name $T --key '{"pk":{"S":"CUSTOMER#chloe"},"sk":{"S":"ORDER#2026-11-11#1003"}}' \
  --update-expression 'ADD qty :one' --condition-expression '#s = :placed' \
  --expression-attribute-names '{"#s":"status"}' --expression-attribute-values '{":one":{"N":"1"},":placed":{"S":"placed"}}'

# Point-in-time recovery, the accident, and the restore
aws dynamodb update-continuous-backups --table-name $T --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
aws dynamodb delete-item --table-name $T --key '{"pk":{"S":"CUSTOMER#amaka"},"sk":{"S":"PROFILE"}}'   # and each order
aws dynamodb describe-continuous-backups --table-name $T
aws dynamodb restore-table-to-point-in-time --source-table-name $T --target-table-name $T-restored \
  --restore-date-time 2026-11-11T18:08:15Z

# Taking it down
aws dynamodb delete-table --table-name $T-restored
aws dynamodb delete-table --table-name $T

"#s" stands in for status in every expression because status is one of DynamoDB's reserved words, as are name, date and hundreds more. The script uses a placeholder for item too, to be safe.

In real systems

  • Apps talk to DynamoDB through an SDK, like boto3 in Lesson 20, not the CLI, with a role allowed only the tables and actions it needs.
  • The access patterns are written down before the table is, and reviewed when a new question comes up, because a new question can mean a new index.
  • Point-in-time recovery is on for every table that matters, often enforced by AWS Config (Lesson 35), with AWS Backup for longer retention.
  • Streams drive the rest of the system: a new order triggers a Lambda function that notifies the kitchen (Lessons 21 and 23).
  • Big, steady workloads use provisioned capacity with auto scaling, which costs less than on demand once traffic is predictable.
  • Every table is Terraform, keys, indexes and recovery settings included.

Spot the problem

Work out what's wrong before you read the explanation.

"The orders screen is slow, and DynamoDB is our biggest bill." The bakery has grown to two million orders. The kitchen screen shows orders that are baking, refreshing every five seconds, with a scan filtered on status = baking. Each refresh returns about twenty orders. What's wrong? Every refresh reads all two million orders to return twenty, and pays for every item read, twelve times a minute, all day. The fix: query the by-status index for baking instead, which reads only the twenty. Then check: with --return-consumed-capacity TOTAL, does each refresh use under one read unit, instead of thousands?

Keep this

RememberWhy
List the questions, then choose the keysNo joins, and no new questions without new keys
Partition keys with many valuesOne busy key becomes a hot partition
Query, not scanThe scan read 10 to return 2, and pays for all of them
An index for each extra question"Who ordered rye?" needed one
Strong consistency costs doubleAnd indexes don't offer it
Conditional writes stop overwritesCheck and change happen together
Point-in-time recovery is off by defaultTurn it on; restores make a new table
A restored table loses its recovery and tagsSwitch them back on before it's trusted

Where you are now

The bakery has an orders table built in 21 seconds, designed around the questions the shop asks, with an index the kitchen can read oldest first. You measured a scan reading five times what it returned, saw writes refuse to overwrite and to change finished orders, met a question the table can't answer, and restored a customer's deleted orders in about three minutes. Next, Lesson 19 pulls Lessons 15 to 18 together: backups and disaster recovery, with recovery targets you set and a restore you test.

Check yourself

  1. The scan returned 2 items. How many did it read, and pay for?

  2. Why did querying by item fail?

  3. How did the kitchen get the baking orders oldest first, without sorting?

  4. Why was writing order 1001 again refused?

  5. What does a strongly consistent read cost, compared with an eventually consistent one?

  6. The restored table had the orders back. What did it not have?

  7. Which partition key would cause a hot partition for the orders table?

Key terms

  • DynamoDB: AWS's serverless key-value and document database.
  • Item and attribute: one record, and one named value in it.
  • Partition key: decides which partition holds an item; required in every query.
  • Sort key: orders items within a partition, and narrows queries.
  • Query: reads items with one partition key, optionally narrowed by the sort key.
  • Scan: reads every item in the table or index.
  • Global secondary index (GSI): a kept-in-step copy of the table with different keys.
  • Read and write units: how DynamoDB measures and charges reads and writes.
  • Eventually and strongly consistent reads: may miss the latest second of writes, or never does, at double the cost.
  • Hot partition: too much traffic on one partition key.
  • Conditional write: a change that only happens if a check passes.
  • Single-table design: several kinds of item in one table, told apart by key prefixes.
  • Point-in-time recovery (PITR): restoring a table to any second in the last 35 days, as a new table.

Go deeper