Skip to content

DynamoDB Single-Table Design ​

Why Single-Table? ​

Traditional (SQL-style):

text
Users table      → Get user
Orders table     → Get orders (separate query)
Products table   → Get products (separate query)
→ 3 queries, 3 round-trips

Single-table design:

text
Main table (all entities)
→ Get user + orders (items sharing the same PK) in 1 query

Access Patterns First ​

CRITICAL: Design DynamoDB tables around access patterns, not entities.

Example access patterns:

  1. Get user by userId
  2. Get user's orders
  3. Get order by orderId
  4. Get product by productId
  5. Get user's recently viewed products
  6. Get orders by status

PK/SK Overloading Pattern ​

text
// minh hoạ hình dạng item (JSON-ish, không chạy độc lập); bản chạy được ở mục "Chạy thử" cuối phần DynamoDB
// Users
{
  PK: "USER#123",
  SK: "METADATA",
  email: "john@example.com",
  name: "John Doe"
}

// User's orders
{
  PK: "USER#123",
  SK: "ORDER#2025-01-09#001",
  orderId: "001",
  total: 99.99,
  status: "completed"
}

{
  PK: "USER#123",
  SK: "ORDER#2025-01-08#002",
  orderId: "002",
  total: 49.99,
  status: "shipped"
}

// Products
{
  PK: "PRODUCT#456",
  SK: "METADATA",
  name: "Laptop",
  price: 999
}

// Order items (many-to-many)
{
  PK: "ORDER#001",
  SK: "PRODUCT#456",
  quantity: 2,
  price: 999
}

Queries:

text
// minh hoạ tham số Query (Node.js SDK v3, QueryCommand input), không chạy độc lập; bản chạy được ở mục "Chạy thử"
// Access pattern 1: Get user by userId
{
  KeyConditionExpression: "PK = :pk AND SK = :sk",
  ExpressionAttributeValues: {
    ":pk": "USER#123",
    ":sk": "METADATA"
  }
}

// Access pattern 2: Get user's orders
{
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)",
  ExpressionAttributeValues: {
    ":pk": "USER#123",
    ":sk": "ORDER#"
  }
}
// → Returns all items with PK=USER#123 and SK starting with "ORDER#"

// Access pattern 6: Get orders by status → Need GSI (can't query by status on main table)

Global Secondary Index (GSI) for Inverted Queries ​

Main table:

text
PK           SK                     status      GSI1PK            GSI1SK
─────────────────────────────────────────────────────────────────────────
USER#123     ORDER#001              completed   STATUS#completed  ORDER#001
USER#123     ORDER#002              pending     STATUS#pending    ORDER#002
USER#456     ORDER#003              pending     STATUS#pending    ORDER#003

GSI1 (inverted for querying by status):

text
GSI1PK       GSI1SK           (projects all attributes)
────────────────────────────────────────────────
STATUS#pending   ORDER#002
STATUS#pending   ORDER#003
STATUS#completed ORDER#001

Query orders by status:

text
// minh hoạ tham số Query (Node.js SDK v3), không chạy độc lập; bản chạy được ở mục "Chạy thử"
{
  IndexName: "GSI1",
  KeyConditionExpression: "GSI1PK = :status",
  ExpressionAttributeValues: {
    ":status": "STATUS#pending"
  }
}

Composite Sort Key Pattern ​

Problem: Query orders by user and date range

Solution: Composite SK with date

text
// minh hoạ item + tham số Query (Node.js SDK v3), không chạy độc lập; bản chạy được ở mục "Chạy thử"
{
  PK: "USER#123",
  SK: "ORDER#2025-01-09#001",  // Date in SK for range queries
  total: 99.99
}

// Query: Orders for user in January 2025
{
  KeyConditionExpression: "PK = :pk AND SK BETWEEN :start AND :end",
  ExpressionAttributeValues: {
    ":pk": "USER#123",
    ":start": "ORDER#2025-01-01",
    ":end": "ORDER#2025-01-31#~"
  }
}

Sparse Index Pattern ​

Problem: Only 5% of users are "premium", but you need to query premium users frequently

Solution: GSI with sparse index (only items with attribute)

text
// minh hoạ hình dạng item + index (không chạy độc lập); bản chạy được ở mục "Chạy thử"
// Main table
{
  PK: "USER#123",
  SK: "METADATA",
  name: "John",
  GSI2PK: "PREMIUM",           // Only premium users have GSI2PK/GSI2SK
  GSI2SK: "USER#123"
}

{
  PK: "USER#456",
  SK: "METADATA",
  name: "Jane"
  // No GSI2PK/GSI2SK (free user) → not in GSI2
}

// GSI2 (sparse index)
// Only includes items that have BOTH GSI2PK and GSI2SK
GSI2PK                GSI2SK
──────────────────────────────
PREMIUM               USER#123  ← Only premium users

Benefit: GSI only stores 5% of items (cheaper, faster)

Adjacency List Pattern (Many-to-Many) ​

Problem: Model followers (User A follows User B)

text
// minh hoạ item + tham số Query (Node.js SDK v3), không chạy độc lập; bản chạy được ở mục "Chạy thử"
// User A follows User B
{
  PK: "USER#A",
  SK: "FOLLOWS#USER#B",
  followedAt: "2025-01-01"
}

// Inverted (User B is followed by User A)
{
  PK: "USER#B",
  SK: "FOLLOWER#USER#A",
  followedAt: "2025-01-01"
}

// Query: Who does User A follow?
{
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)",
  ExpressionAttributeValues: {
    ":pk": "USER#A",
    ":sk": "FOLLOWS#"
  }
}

// Query: Who follows User B?
{
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)",
  ExpressionAttributeValues: {
    ":pk": "USER#B",
    ":sk": "FOLLOWER#"
  }
}

Trade-off:

  • ✅ Query in both directions (1 query each)
  • ❌ Mỗi quan hệ tốn 2 lần ghi (follow = 2 item; ghi bằng TransactWriteItems để hai chiều không lệch nhau)

Chạy thử (Node.js, SDK v3) ​

javascript
// Node.js (SDK v3): npm i @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
// DynamoDB Local: docker run -p 8000:8000 amazon/dynamodb-local
import { DynamoDBClient, CreateTableCommand } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand, QueryCommand, TransactWriteCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({
  endpoint: "http://localhost:8000",
  region: "us-east-1",
  credentials: { accessKeyId: "local", secretAccessKey: "local" },
});
const doc = DynamoDBDocumentClient.from(client);

const S = (n) => ({ AttributeName: n, AttributeType: "S" });
const gsi = (name, pk, sk) => ({
  IndexName: name,
  KeySchema: [{ AttributeName: pk, KeyType: "HASH" }, { AttributeName: sk, KeyType: "RANGE" }],
  Projection: { ProjectionType: "ALL" },
});
await client.send(new CreateTableCommand({
  TableName: "AppTable",
  BillingMode: "PAY_PER_REQUEST",
  AttributeDefinitions: [S("PK"), S("SK"), S("GSI1PK"), S("GSI1SK"), S("GSI2PK"), S("GSI2SK")],
  KeySchema: [{ AttributeName: "PK", KeyType: "HASH" }, { AttributeName: "SK", KeyType: "RANGE" }],
  GlobalSecondaryIndexes: [gsi("GSI1", "GSI1PK", "GSI1SK"), gsi("GSI2", "GSI2PK", "GSI2SK")],
}));

const items = [
  { PK: "USER#123", SK: "METADATA", name: "John Doe", GSI2PK: "PREMIUM", GSI2SK: "USER#123" },
  { PK: "USER#456", SK: "METADATA", name: "Jane" },
  { PK: "USER#123", SK: "ORDER#2025-01-09#001", total: 99.99, status: "completed",
    GSI1PK: "STATUS#completed", GSI1SK: "ORDER#2025-01-09#001" },
  { PK: "USER#123", SK: "ORDER#2025-01-08#002", total: 49.99, status: "pending",
    GSI1PK: "STATUS#pending", GSI1SK: "ORDER#2025-01-08#002" },
  { PK: "ORDER#001", SK: "PRODUCT#456", quantity: 2, price: 999 },
];
for (const Item of items) await doc.send(new PutCommand({ TableName: "AppTable", Item }));

// Adjacency list: một lần follow = 2 item, ghi trong một transaction
await doc.send(new TransactWriteCommand({ TransactItems: [
  { Put: { TableName: "AppTable", Item: { PK: "USER#A", SK: "FOLLOWS#USER#B", followedAt: "2025-01-01" } } },
  { Put: { TableName: "AppTable", Item: { PK: "USER#B", SK: "FOLLOWER#USER#A", followedAt: "2025-01-01" } } },
] }));

const keys = async (params) =>
  (await doc.send(new QueryCommand({ TableName: "AppTable", ...params }))).Items.map((i) => `${i.PK}|${i.SK}`);

console.log("user + metadata:", await keys({
  KeyConditionExpression: "PK = :pk AND SK = :sk",
  ExpressionAttributeValues: { ":pk": "USER#123", ":sk": "METADATA" } }));
console.log("user's orders:", await keys({
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)",
  ExpressionAttributeValues: { ":pk": "USER#123", ":sk": "ORDER#" } }));
console.log("orders in January:", await keys({
  KeyConditionExpression: "PK = :pk AND SK BETWEEN :start AND :end",
  ExpressionAttributeValues: { ":pk": "USER#123", ":start": "ORDER#2025-01-01", ":end": "ORDER#2025-01-31#~" } }));
console.log("pending (GSI1):", await keys({ IndexName: "GSI1",
  KeyConditionExpression: "GSI1PK = :s", ExpressionAttributeValues: { ":s": "STATUS#pending" } }));
console.log("premium (GSI2):", await keys({ IndexName: "GSI2",
  KeyConditionExpression: "GSI2PK = :t", ExpressionAttributeValues: { ":t": "PREMIUM" } }));
console.log("A follows:", await keys({
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)",
  ExpressionAttributeValues: { ":pk": "USER#A", ":sk": "FOLLOWS#" } }));
console.log("B followers:", await keys({
  KeyConditionExpression: "PK = :pk AND begins_with(SK, :sk)",
  ExpressionAttributeValues: { ":pk": "USER#B", ":sk": "FOLLOWER#" } }));

Phải nhớ:

  • Item tối đa 400 KB, tính cả tên thuộc tính; thiết kế item theo access pattern, tách phần lớn sang item khác cùng PK hoặc S3.
  • Item chỉ vào GSI khi có ĐỦ thuộc tính khoá của index (GSI1PK, GSI1SK): GSI overloading nghĩa là mỗi entity tự ghi các thuộc tính đó.
  • Bắt đầu thiết kế key từ danh sách access pattern (không từ sơ đồ entity); một giá trị GSI partition key ít biến thiên (STATUS#pending, PREMIUM) gom mọi item mang giá trị đó vào một item collection; một partition chịu tối đa 3.000 RCU và 1.000 WCU, nên item collection quá nóng dễ bị throttle (adaptive capacity có thể tách collection theo sort key nhưng không bảo đảm, và không tách khi bảng có LSI).