<< back to Guides

โšก Deep Dive into DynamoDB: Design, Modeling, and Best Practices

Amazon DynamoDB is a fully managed NoSQL key-value and document database that delivers single-digit millisecond performance at any scale. It is serverless, supports automatic scaling, built-in security, and multi-region replication.


๐Ÿง  Core Concepts

๐Ÿ”น Tables, Items, and Attributes

// Sample item in DynamoDB (JSON format)
{
  "UserId": "user-123",
  "Name": "Alice",
  "Age": 30,
  "Email": "alice@example.com"
}

๐Ÿ”น Primary Key

Every item must have a primary key, which can be:

The partition key determines the data distribution across storage partitions.

// Example composite key
Partition Key: "UserId" = "user-123"
Sort Key: "OrderDate" = "2024-10-10"

๐Ÿ”น Secondary Indexes

Indexes must be defined at table creation (LSI) or can be added later (GSI).


๐Ÿ”น Read and Write Capacity Modes

  1. On-Demand: Auto-scales based on usage (pay per request)
  2. Provisioned: Manually set read/write units (cheaper with predictable load)
// Provisioned example
Read Capacity Units (RCU) = 5
Write Capacity Units (WCU) = 10

Use DAX (DynamoDB Accelerator) to cache reads and improve performance.


๐Ÿ“Š Data Modeling in DynamoDB

DynamoDB is not relational โ€” it's designed for access patterns.

โœ… Design Principles

// Example item with embedded data
{
  "UserId": "user-123",
  "Type": "Profile",
  "Profile": {
    "Name": "Alice",
    "Email": "alice@example.com"
  }
}

โš ๏ธ Avoid joins. You query based on access patterns, not relations.


๐Ÿงช Querying & Scanning

๐Ÿ“Œ Query

Efficient โ€” uses partition key and optional sort key conditions.

aws dynamodb query \
  --table-name Users \
  --key-condition-expression "UserId = :uid" \
  --expression-attribute-values '{":uid":{"S":"user-123"}}'

๐Ÿ“Œ Scan

Inefficient โ€” reads all items. Use only for small datasets or batch jobs.


๐Ÿ” Security & Access Control

// IAM example: Allow read-only access
{
  "Effect": "Allow",
  "Action": [
    "dynamodb:GetItem",
    "dynamodb:Query",
    "dynamodb:Scan"
  ],
  "Resource": "arn:aws:dynamodb:region:acct-id:table/Users"
}

โ™ป๏ธ Streams and Triggers

Enable DynamoDB Streams to capture item changes (insert, update, delete).

// Event structure (example)
{
  "eventName": "INSERT",
  "dynamodb": {
    "Keys": { "UserId": { "S": "user-123" } },
    "NewImage": { "Name": { "S": "Alice" } }
  }
}

๐Ÿšฆ Best Practices

Practice Reason
Design access patterns first Helps with schema design in NoSQL
Prefer Query over Scan Better performance and cost
Avoid hot partitions Use high-cardinality partition keys
Use DAX for heavy-read workloads In-memory caching layer
Use TTL Automatically delete expired data
Monitor with CloudWatch Track latency, throttles, WCU/RCU usage

๐Ÿ”ฅ When to Use DynamoDB


๐Ÿ›‘ When Not to Use


๐Ÿ“š Resources


<< back to Guides