Skip to content
Visual explainer 3h to learn 5 steps

Design a DynamoDB table from its access patterns

Model a table around listed queries, use condition writes, and choose indexes, TTL, consistency and capacity mode.

By Invicly Tech, , in AWS Cloud Engineering. About 11 minutes to read.

Topic 17 of 38

In short

DynamoDB is a key-value and document database that answers queries fast at any scale, but only for questions you design the keys for. You list your access patterns first, then choose a partition key and sort key so each pattern becomes one Query. Condition expressions protect writes, and indexes, TTL, read consistency and capacity mode finish the design.

Think of it like this: Designing a DynamoDB table is like labelling filing-cabinet drawers by how you will look things up, not by what the papers are about.

Explained simply

DynamoDB is a database where each item is found by its key. It can answer millions of requests a second with steady speed, and there are no servers to manage. The catch is that it only answers fast the questions you planned for when you chose the keys.

So you start by writing a list of questions the app will ask. In our file service: get one job by its ID, list a user's jobs newest first, and find jobs that failed. Each question is an access pattern. You then choose keys so each pattern becomes a single Query call.

Every item has a partition key, which decides where it is stored, and often a sort key, which orders items that share a partition key. For example, partition key USER#42 and sort key JOB#2026-11-30T10:00#a1 keeps all of a user's jobs together, sorted by time.

A few more settings finish the design. Condition expressions stop a write if something unexpected is true, like the item already existing. A secondary index gives a second way to look things up. TTL deletes old items automatically, and the capacity mode decides how you pay.

Press Play on a diagram to walk through it one step at a time.

FlowDesigning from access patterns
  1. 1
    List the questions

    Get job by id, list a user's jobs by date

  2. 2
    Choose keys

    PK = USER#42, SK = JOB#2026-11-30T10:00#id

  3. 3
    Map each question to a Query

    No Scan in the hot path

  4. 4
    Add an index if needed

    GSI for status lookups

  5. 5
    Set TTL and capacity

    Expire old rows, on-demand or provisioned

CompareQuery vs Scan
Query
  • Needs one partition key value
  • Can narrow with the sort key
  • Reads only matching items
  • Cost grows with result size
Scan
  • Reads every item in the table
  • Filters apply after reading
  • Cost grows with table size
  • Fine for rare admin jobs only

In depth

From access patterns to keys

Write each pattern with its inputs, sort order and rough volume, such as: list jobs for a user, newest first, 20 per page, 50 requests per second. Group patterns that share an input. Patterns that start from a user point to a partition key of USER# followed by the user ID. Ordering by time points to a sort key that begins with a timestamp. Generic attribute names such as pk and sk let one table hold several item types, a style called single-table design, but separate tables are fine when the entities are not read together. Check every pattern again: if any needs a Scan, change the keys or add an index. A good partition key has many distinct values with even traffic, so a user ID is good and a status field is bad.

  • Write patterns before keys
  • One pattern, one Query
  • High-variety partition keys
  • Sort key prefixes such as JOB# allow begins_with

Condition expressions and safe updates

DynamoDB has no locks, but each write can carry a condition checked atomically against the current item. attribute_not_exists(pk) on a PutItem means create only if new, which blocks duplicate jobs when a queue delivers a message twice. A condition like #s = :queued on an UpdateItem moves a job from QUEUED to RUNNING only if nobody else did first. Optimistic locking uses a version number: read version 3, write with condition version = 3 and set version to 4. If the condition fails, the write is rejected with ConditionalCheckFailedException and nothing changes; your code decides whether to retry, skip or report. Failed conditional writes still consume write capacity.

SequenceTwo workers race for the same job
Worker A
DynamoDB
Worker B
  1. 1Update status to RUNNING if status = QUEUED
    Worker A to DynamoDB: Update status to RUNNING if status = QUEUED
  2. 2Same update, a moment later
    Worker B to DynamoDB: Same update, a moment later
  3. 3Success, item updated
    DynamoDB to Worker A: Success, item updated
  4. 4ConditionalCheckFailedException
    DynamoDB to Worker B: ConditionalCheckFailedException
  5. 5Skip: someone else owns the job
    Worker B to Worker B: Skip: someone else owns the job

Secondary indexes

A global secondary index (GSI) copies chosen attributes into a structure with a different partition and sort key, kept up to date asynchronously. It can be added at any time, has its own capacity and supports only eventually consistent reads. It is sparse: items without the index key attributes do not appear, which is handy for patterns like failed jobs only, if you set a gsi1pk attribute only on failed items. A local secondary index (LSI) shares the table's partition key with a different sort key, must be created with the table, supports strongly consistent reads and limits each partition key value to 10 GB of data. Every index adds storage and write cost, so add one only for a listed pattern.

TTL, consistency and capacity mode

TTL uses a number attribute holding an expiry time in epoch seconds. A background process deletes expired items, usually within a few days, at no write cost, and the deletes appear in DynamoDB Streams if you need to react. Until then, expired items can still be returned, so filter them in queries. Reads are eventually consistent by default and cost half as much as strongly consistent reads, which you request with ConsistentRead on the base table. On-demand capacity charges per request and suits new or spiky workloads. Provisioned capacity sets read and write units, with optional auto scaling, and is cheaper for steady, predictable traffic. One read unit covers one strongly consistent read per second of up to 4 KB; one write unit covers one write of up to 1 KB. Items can be at most 400 KB.

  • TTL: epoch seconds, deletes within days, free
  • Eventually consistent reads cost half
  • On-demand for unknown or spiky load
  • Provisioned plus auto scaling for steady load
  • Item size limit 400 KB

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    List access patterns first~35m
  2. 2
    Pick partition and sort keys~35m
  3. 3
    Write with condition expressions~35m
  4. 4
    Add a secondary index~35m
  5. 5
    Choose TTL, consistency and capacity mode~35m

Key points

  • A Query reads items with one partition key value, optionally narrowed by the sort key; a Scan reads the whole table.
  • Spread writes over many partition key values so no single key gets all the traffic.
  • Use condition expressions such as attribute_not_exists(pk) to stop duplicates and lost updates.
  • Global secondary indexes give another key to query by, but reads from them are eventually consistent.
  • TTL deletes expired items for free, usually within a few days, so filter them out in reads too.

Key terms

Tap a card to flip it. 0/6 known

Examples

bash
# create the job only if it does not already exist
aws dynamodb put-item --table-name Jobs \
  --item '{"pk":{"S":"USER#42"},"sk":{"S":"JOB#2026-11-30T10:00#a1"},"status":{"S":"QUEUED"}}' \
  --condition-expression "attribute_not_exists(pk)"
# list user 42's jobs, newest first
aws dynamodb query --table-name Jobs \
  --key-condition-expression "pk = :p AND begins_with(sk, :j)" \
  --expression-attribute-values '{":p":{"S":"USER#42"},":j":{"S":"JOB#"}}' \
  --no-scan-index-forward

Design the Jobs table for the file service

Patterns: P1 get job by ID, P2 list a user's jobs newest first, P3 list failed jobs across all users for an operator. Step 1: base table pk = USER#{userId}, sk = JOB#{isoTime}#{jobId}, which serves P2 with a Query and descending sort. Step 2: for P1, store a second small item pk = JOB#{jobId}, sk = META, or pass the user ID along with the job ID. Step 3: for P3, add a sparse GSI with gsi1pk = FAILED set only on failed jobs and gsi1sk = the failure time. Step 4: add expiresAt as TTL, 90 days after completion. Step 5: start with on-demand capacity. Local alternative: DynamoDB Local in Docker runs the same API for free.

bash
docker run -d -p 8000:8000 amazon/dynamodb-local
aws dynamodb create-table --endpoint-url http://localhost:8000 --table-name Jobs \
  --attribute-definitions AttributeName=pk,AttributeType=S AttributeName=sk,AttributeType=S \
  --key-schema AttributeName=pk,KeyType=HASH AttributeName=sk,KeyType=RANGE \
  --billing-mode PAY_PER_REQUEST

Claim a job exactly once from Python

Several workers may receive the same message. Each tries to move the job from QUEUED to RUNNING with a condition. Only one succeeds; the others catch ConditionalCheckFailedException and skip. Evidence: run two workers on the same job ID against DynamoDB Local and see one success and one skip in the logs.

python
import boto3
from botocore.exceptions import ClientError
table = boto3.resource("dynamodb").Table("Jobs")
def claim(pk: str, sk: str, worker: str) -> bool:
    try:
        table.update_item(Key={"pk": pk, "sk": sk},
            UpdateExpression="SET #s = :run, worker = :w",
            ConditionExpression="#s = :queued",
            ExpressionAttributeNames={"#s": "status"},
            ExpressionAttributeValues={":run": "RUNNING", ":queued": "QUEUED", ":w": worker})
        return True
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return False
        raise

Quick reference

  • List access patterns first; every hot-path pattern should be one Query
  • attribute_not_exists(pk) = create only if new
  • GSI: any time, own keys, eventually consistent only; LSI: at table creation, same partition key
  • TTL attribute = Number in epoch seconds; deletion usually within a few days
  • Strongly consistent read = 2x the cost of an eventually consistent read
  • Item size limit 400 KB; store big payloads in S3 and keep the key in DynamoDB
  • status is a reserved word: refer to it through ExpressionAttributeNames, such as #s

Common mistakes

  • Designing tables like SQL tables first and discovering later that the main screen needs a Scan.
  • Using a low-variety partition key such as status or date, which creates a hot partition.
  • Expecting TTL to delete items at the exact second they expire.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which partition key is most likely to cause a hot partition?

Question 2

2A worker must create a job item only if it does not exist yet. What do you add to PutItem?

Question 3

3Which statement about GSIs is correct?

Question 4

4An item's TTL time passed an hour ago but a Query still returns it. Why?

Question 5

5A new app has unknown, spiky traffic. Which capacity mode is the safer start?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the KeyConditionExpression and values to get user 7's jobs from November 2026 only.

  2. Exercise 2medium

    Add optimistic locking: update a job's result only if its version is still 3, and bump the version to 4.

  3. Exercise 3hard

    Design keys for a comments feature: list comments on a file newest first, list all comments by a user, and delete comments 1 year after creation. Name the base keys, any index and the TTL attribute.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is DynamoDB a replacement for SQL databases?
Not in general. It fits known, key-based access at scale. If you need ad hoc queries, joins or reporting across many fields, a relational database is usually easier.
What is single-table design?
Storing several item types in one table with generic key names so related items can be read in one Query. It is optional; use it when items are read together.
Can I run DynamoDB locally?
Yes. DynamoDB Local is a free downloadable version and Docker image that runs the same API on your machine for development and tests.

Go deeper

ShareXLinkedInWhatsApp