Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 70 ยท Databases

DynamoDB Fundamentals

Learn Amazon DynamoDB basics: tables, items, partition and sort keys, Query versus Scan, on-demand and provisioned capacity, and eventual versus strong consistency.

Amazon DynamoDB is a fully managed key-value and document database designed for single-digit-millisecond responses at any scale. There are no servers to size, no connections to pool and no query planner: you declare how items are addressed, and DynamoDB spreads them over as many machines as it needs. The price of that predictability is a stricter way of thinking. You cannot ask arbitrary questions of the data after the fact; you design the table around the questions you will ask.

DynamoDB cannot run on this site, so the SDK code is read-only. A Python emulator lets you feel the core rules: how keys place items, why Query is cheap and Scan is expensive, and how capacity units are counted. It is a teaching model of the semantics, not the real engine, and it ignores replication, indexes and many API details.

Tables, items and attributes

A table is a collection of items (rows). An item is a set of attributes (fields) with a name and a typed value: string, number, binary, boolean, null, set, list or map. Besides the key attributes, DynamoDB has no schema, so two items in one table may have entirely different attributes. An item can be at most 400 KB, counting attribute names and values.

Every item is identified by its primary key, chosen when you create the table and impossible to change later:

  • Simple primary key: a partition key only. Each item has a unique partition key value.
  • Composite primary key: a partition key plus a sort key. Many items can share a partition key as long as their sort keys differ, and they are stored together, ordered by the sort key.

DynamoDB passes the partition key through a hash function to decide which physical partition stores the item. That is why the partition key spreads data and load, and why a good choice has many distinct values (a customer ID, not a country code).

flowchart LR
    R["Request<br/>customer_id = c42"] --> H["hash(c42)"]
    H --> P2["Partition 2"]
    P2 --> I1["c42 | 2026-03-01#1001"]
    P2 --> I2["c42 | 2026-03-14#1002"]
    P2 --> I3["c42 | 2026-04-02#1003"]

The partition key's hash selects a partition; items with that key sit together in sort-key order.

Creating a table and writing data look like this in the AWS CLI and boto3 (read-only here):

Terminal
aws dynamodb create-table \
  --table-name Orders \
  --attribute-definitions AttributeName=customer_id,AttributeType=S AttributeName=order_sk,AttributeType=S \
  --key-schema AttributeName=customer_id,KeyType=HASH AttributeName=order_sk,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST
Python
import boto3
from boto3.dynamodb.conditions import Key

table = boto3.resource("dynamodb").Table("Orders")

table.put_item(Item={"customer_id": "c42", "order_sk": "2026-03-14#1002", "total": 4999, "status": "shipped"})
item = table.get_item(Key={"customer_id": "c42", "order_sk": "2026-03-14#1002"}).get("Item")

resp = table.query(
    KeyConditionExpression=Key("customer_id").eq("c42") & Key("order_sk").begins_with("2026-03"),
    ScanIndexForward=False,        # newest first
    Limit=10,
)

With the boto3 resource interface, numbers must be int or Decimal, not float. put_item replaces a whole item, while update_item changes selected attributes, and a ConditionExpression such as attribute_not_exists(customer_id) turns a write into "create only if it does not exist", the building block for locks and idempotency.

The core operations

  • GetItem: read one item by its full primary key. The fastest, cheapest operation.
  • PutItem / UpdateItem / DeleteItem: write one item. Transactions (TransactWriteItems, up to 100 items) apply several writes atomically.
  • BatchGetItem / BatchWriteItem: up to 100 reads or 25 writes in one call, each item handled independently.
  • Query: read items that share one partition key value, optionally narrowed by a sort key condition (=, <, >, between, begins_with). Results come in sort-key order, and the cost depends only on the data read from that one partition.
  • Scan: read the entire table (or index) and optionally filter afterwards. A filter removes items from the response but not from the bill, because capacity is charged for everything scanned.

A single Query or Scan call returns at most 1 MB of data. If more matches exist you receive a LastEvaluatedKey and pass it back as ExclusiveStartKey to continue, which SDK paginators do for you.

The rule of thumb: Query for access patterns you know, Scan for rare administrative jobs. Because a table's key design fixes what Query can do, you should write down your access patterns before creating the table. DynamoDB Data Modeling turns that idea into a method with secondary indexes.

Capacity and billing

DynamoDB meters work in capacity units:

  • One read request unit (RCU) is one strongly consistent read of an item up to 4 KB. An eventually consistent read costs half of that, and a transactional read costs double. Larger items round up to the next 4 KB.
  • One write request unit (WCU) is one write of an item up to 1 KB, rounded up; a transactional write costs double.
  • For Query and Scan, the sizes of all items read are added and then rounded up to 4 KB, so scanning many small items is far cheaper than reading each one individually.

There are two capacity modes:

Mode How you pay Good for
On-demand Per read and write request actually made New, spiky or unpredictable workloads
Provisioned A rate of RCU and WCU per second you reserve, optionally with auto scaling Steady, predictable traffic, usually cheaper at high utilization

In provisioned mode, requests above the provisioned rate (plus some burst credit) are throttled with a ProvisionedThroughputExceededException, and the SDK retries with backoff. You can switch modes occasionally (at most once per 24 hours per table). Each partition also has its own ceiling of roughly 3,000 read and 1,000 write units per second, which is why a "hot" key can throttle a table even when overall capacity looks ample.

Consistency

DynamoDB stores each item on three replicas across Availability Zones. A write is acknowledged after a majority has it. Reads default to eventually consistent: they may hit a replica that has not yet seen the latest write, usually for a moment. Set ConsistentRead=True to get a strongly consistent read of the latest data at double the capacity cost, available on tables and local secondary indexes but not on global secondary indexes (which are always eventually consistent). Strongly consistent reads can also fail when a Region has a connectivity problem with the leader replica, while eventually consistent ones are more available.

An emulator to explore

The stand-in below stores items in a handful of partitions chosen by hash, supports put, get, query and scan, and reports the capacity each call would consume. The item sizes are computed from a JSON encoding, which only approximates DynamoDB's real size rules, so absolute numbers differ slightly from real service bills.

Python A DynamoDB-like table with capacity accounting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the numbers: the query for one customer's orders costs a fraction of the scan that finds pending orders, even though the scan returns only a few items. As the table grows, the scan's cost grows with it while the query's does not.

Throttling and capacity planning

Provisioned capacity is a rate, so the arithmetic is: items per second times units per item. A write of a 2.5 KB item takes 3 WCU; a strongly consistent read of a 9 KB item takes 3 RCU. The second stand-in turns that into a calculator and shows what happens when traffic exceeds a table's provisioned write rate. It ignores the burst capacity that real tables bank, so real throttling starts a little later.

Python Capacity math and throttling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The ! marks in the output are requests the SDK would retry with exponential backoff. If the peak is brief and unpredictable, on-demand mode removes the planning; if the load is steady, provisioned capacity with auto scaling costs less.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is Query usually preferable to Scan?

    Query goes straight to one partition key. Scan reads the whole table, and its cost grows with table size, even if a filter removes most results.
  2. 2. A Scan with a filter returns 3 of 10,000 items. For how many items are you charged read capacity?

    Filters run after items are read, so read capacity is charged for everything scanned, not only for what is returned.
  3. 3. Reading one 8 KB item with a strongly consistent GetItem consumes how many RCUs?

    8 KB is two 4 KB blocks, and a strongly consistent read costs 1 RCU per block, so 2 RCUs. An eventually consistent read would cost 1.
  4. 4. Which statement about primary keys is correct?

    You choose the key schema at creation and cannot change it. Good partition keys have many distinct values so data and traffic spread across partitions.
  5. 5. When is on-demand capacity mode a good fit?

    On-demand mode charges per request and adapts to traffic, which suits unpredictable workloads. Provisioned mode is often cheaper for steady traffic.

Summary

  • A DynamoDB table holds schemaless items identified by a partition key, optionally with a sort key; the key schema cannot change later.
  • The partition key's hash decides placement, so choose keys with many distinct values.
  • Query reads one partition key (with optional sort-key conditions); Scan reads everything and bills for all of it.
  • Capacity is counted in 4 KB read units and 1 KB write units, with eventual reads at half price; choose on-demand or provisioned mode.
  • Reads are eventually consistent by default; strongly consistent reads cost double and are not available on global secondary indexes.

Next: DynamoDB Data Modeling.