AWS Builder Center

Amazon DynamoDB for Beginners: Your First Serverless NoSQL Table

A beginner-friendly guide to Amazon DynamoDB: tables, items, partition and sort keys, capacity modes, and how to create a table and read and write data with the console, the AWS CLI, and Python (boto3), staying inside the free tier.

Developer at Itaú
In the last article we ran code with AWS Lambda without managing servers. Sooner or later that code needs to store something: a user profile, an order, a to-do item. Amazon DynamoDB is the database that pairs most naturally with Lambda. There is no server to start, no version to patch, and no connection pool to babysit. You create a table, and you read and write items through an API.

What DynamoDB is

DynamoDB is AWS's fully managed, serverless NoSQL database. It stores data as key-value and document items and delivers consistent single-digit millisecond performance whether the table holds a hundred items or billions. AWS replicates the data across multiple Availability Zones in a Region for you.
The big mental shift for anyone coming from SQL: in DynamoDB you design the table around how you will read the data, not around normalized entities. There are no joins. You decide your access patterns first and pick keys that serve them.

When to use it

  • serverless backends with Lambda and API Gateway;
  • user profiles, sessions, shopping carts, game state;
  • data you always fetch by a known key (an ID, a user plus a date);
  • workloads with unpredictable traffic that need to scale without planning.
It is not the best fit when you need ad-hoc queries, complex joins, or reporting across many fields. For those, a relational database like Amazon RDS (our next article) is usually easier.

Key concepts

  • Table: a collection of items. You don't define a schema beyond the primary key.
  • Item: a single record, similar to a row. An item can be at most 400 KB.
  • Attribute: a field of an item. Different items in the same table can have different attributes.
  • Partition key: the required part of the primary key. DynamoDB hashes it to decide where the item is physically stored. With only a partition key, every value must be unique.
  • Sort key (optional): together with the partition key it forms a composite primary key. Items with the same partition key are stored together, ordered by sort key, so you can query "all orders of user 42" or "orders of user 42 in October".
  • Secondary indexes: a global secondary index (GSI) lets you query by a different partition and sort key; a local secondary index (LSI) keeps the same partition key with a different sort key.
  • Capacity modes: on-demand bills per request and scales automatically (AWS recommends it for most workloads); provisioned means you set read and write capacity units (RCUs and WCUs) up front.
  • Query vs. Scan:  Query  reads items by key and is efficient.  Scan  reads the whole table and gets slow and expensive as the table grows. Prefer  Query .

Getting started

1. Create a table in the console

Open DynamoDB > Tables > Create table. Name it  studies-tasks , set the partition key to  user_id  (String) and the sort key to  task_id  (String). Keep the default settings and click Create table. When the status changes to Active, open Explore items > Create item, add an item with  user_id = vitor ,  task_id = 001 , and an attribute  title = Learn DynamoDB , and save it.

2. Or with the AWS CLI

Using the  studies  profile from the IAM article. This command uses provisioned mode with 5 RCUs and 5 WCUs, which stays inside the free tier (more on that below):
aws sso login --profile studies

aws dynamodb create-table --table-name studies-tasks \
--attribute-definitions AttributeName=user_id,AttributeType=S AttributeName=task_id,AttributeType=S \
--key-schema AttributeName=user_id,KeyType=HASH AttributeName=task_id,KeyType=RANGE \
--billing-mode PROVISIONED \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--region sa-east-1 --profile studies

aws dynamodb wait table-exists --table-name studies-tasks \
--region sa-east-1 --profile studies

aws dynamodb put-item --table-name studies-tasks \
--item '{"user_id": {"S": "vitor"}, "task_id": {"S": "001"}, "title": {"S": "Learn DynamoDB"}}' \
--region sa-east-1 --profile studies

aws dynamodb query --table-name studies-tasks \
--key-condition-expression "user_id = :u" \
--expression-attribute-values '{":u": {"S": "vitor"}}' \
--region sa-east-1 --profile studies
Notice the type descriptors ( "S"  for string,  "N"  for number). The low-level API always uses them. In Python, the higher-level resource interface hides them for you.

3. A Python example (boto3)

import boto3
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError

session = boto3.Session(profile_name="studies", region_name="sa-east-1")
table = session.resource("dynamodb").Table("studies-tasks")


def main() -> None:
try:
table.put_item(
Item={"user_id": "vitor", "task_id": "002", "title": "Build an API", "done": False},
ConditionExpression="attribute_not_exists(task_id)",
)

item = table.get_item(Key={"user_id": "vitor", "task_id": "002"}).get("Item")
print(f"Fetched: {item}")

response = table.query(KeyConditionExpression=Key("user_id").eq("vitor"))
for task in response["Items"]:
print(f"{task['task_id']}: {task['title']}")
except ClientError as error:
code = error.response["Error"]["Code"]
if code == "ConditionalCheckFailedException":
print("Task already exists, nothing written.")
else:
print(f"DynamoDB error: {code}")


if __name__ == "__main__":
main()
The  ConditionExpression  makes the write fail instead of silently overwriting an existing item, a simple habit that prevents a lot of bugs. When your code runs inside Lambda, drop  profile_name : the function's execution role provides the credentials, and it needs permissions such as  dynamodb:PutItem ,  dynamodb:GetItem , and  dynamodb:Query  on this table only.

Costs and caveats

  • Free tier: each month, per Region and per payer account, DynamoDB includes 25 GB of storage, 25 WCUs and 25 RCUs. The throughput part applies to provisioned capacity on the DynamoDB Standard table class, which is why the CLI example uses provisioned mode. On-demand is billed per request, which is still cheap for study usage, but it isn't covered by those 25 units.
  • Avoid Scan in loops: a  Scan  reads (and bills) every item. Design keys so you can  Query .
  • Hot partitions: if almost every request uses the same partition key value, that partition becomes a bottleneck. Choose keys with many distinct values, like a user ID.
  • Least privilege: grant access to specific tables, not  dynamodb:*  on everything.
  • Backups: turn on point-in-time recovery for anything that matters. It has its own cost, so check the pricing page first.
  • Clean up:  aws dynamodb delete-table --table-name studies-tasks , and keep that budget alert from AWS Budgets active.

Next steps

  1. Write a Lambda function that saves an item to this table when invoked.
  1. Add a GSI to query tasks by  done  status.
  1. Try TTL to expire old items automatically.
  1. In the next article: Amazon RDS, for when you do need a relational database.

Official documentation

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article