DynamoDB single-table design by example
Single-table design makes sense once you do it with a real app. I model shorty's links and daily click counts in one DynamoDB table with one GSI, starting from the access patterns, and run every query in Go against DynamoDB Local.
Every DynamoDB talk ends up at "single-table design", and every time I read about it the example is an online store with customers, orders and order items. I understand the diagram and still don't know how I'd do it for my own app. So in this blog we will do it for shorty, the URL shortener this tutorial series builds on Postgres, and put its links and clicks in one DynamoDB table.
Level is advanced. You should know what a partition key and a sort key are, and it helps to have read SQL vs NoSQL: choosing a database by access pattern and the URL shortener design post. Everything here ran against DynamoDB Local 3.3.2 in Docker, from Go 1.27.3 with aws-sdk-go-v2 (service/dynamodb v1.74.1). No AWS account involved.
💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/AWS/DynamoDB/dynamodb-single-table-design-by-example. Clone it and run each step yourself.
Access patterns first
In Postgres I design tables, and the queries come later. In DynamoDB it's the other way round. You can only query by key, so you write down every question the app will ask before you draw a single key. For shorty that list is quite short.
- Resolve a code to its URL. This is the redirect, it's the hot path and must be one cheap read.
- Create a link, failing if the code is already taken.
- Add clicks to a link, both a running total and a count per day.
- Show the daily click counts of one link for a date range.
- List one user's links, newest first.
- Delete a link and everything that belongs to it.
The Postgres shorty has no users yet. I added an owner here because pattern 5 is the one that needs a secondary index, and without it the example would be too easy.
The keys
All items live in one table with generic key names, PK and SK. The values carry a type prefix.
PK SK other attributes
LINK#go-1-27 META url, owner, clicks, created_at, GSI1PK, GSI1SK
LINK#go-1-27 DAY#2026-11-17 clicks
LINK#go-1-27 DAY#2026-11-18 clicks
LINK#pg-18 META ...
Everything about one link shares a partition key, so it's one item collection. The META item holds the link. One DAY item per link per UTC day holds a counter. Because the dates are ISO strings, they sort in date order, and "clicks between the 1st and the 30th" becomes a range on the sort key.
For pattern 5 the META item also gets GSI1PK = USER#<owner> and GSI1SK = <created_at>#<code>. The DAY items don't have those attributes, so they never show up in the index at all. That's called a sparse index and it's half the trick of single-table design: only the items you want in an index carry its keys.
Here's the table in Go.
func (s *Store) CreateTable(ctx context.Context) error {
str := types.ScalarAttributeTypeS
_, err := s.db.CreateTable(ctx, &dynamodb.CreateTableInput{
TableName: aws.String(s.table),
BillingMode: types.BillingModePayPerRequest,
AttributeDefinitions: []types.AttributeDefinition{
{AttributeName: aws.String("PK"), AttributeType: str},
{AttributeName: aws.String("SK"), AttributeType: str},
{AttributeName: aws.String("GSI1PK"), AttributeType: str},
{AttributeName: aws.String("GSI1SK"), AttributeType: str},
},
KeySchema: []types.KeySchemaElement{
{AttributeName: aws.String("PK"), KeyType: types.KeyTypeHash},
{AttributeName: aws.String("SK"), KeyType: types.KeyTypeRange},
},
GlobalSecondaryIndexes: []types.GlobalSecondaryIndex{{
IndexName: aws.String("GSI1"),
KeySchema: []types.KeySchemaElement{
{AttributeName: aws.String("GSI1PK"), KeyType: types.KeyTypeHash},
{AttributeName: aws.String("GSI1SK"), KeyType: types.KeyTypeRange},
},
Projection: &types.Projection{
ProjectionType: types.ProjectionTypeInclude,
NonKeyAttributes: []string{"code", "url", "clicks"},
},
}},
})
if err != nil {
return err
}
return dynamodb.NewTableExistsWaiter(s.db).Wait(ctx,
&dynamodb.DescribeTableInput{TableName: aws.String(s.table)}, time.Minute)
}
On-demand billing, because I have no idea what shorty's traffic looks like. Remember that projection line, I'll discuss about it later.
Running DynamoDB Local
docker run -d --name ddb -p 127.0.0.1:18000:8000 amazon/dynamodb-local:latest -jar DynamoDBLocal.jar -inMemory
The client points at it only when DDB_ENDPOINT is set, with dummy keys. DynamoDB Local accepts any credentials, and I'd rather not have real ones anywhere near a test.
func newClient(ctx context.Context) (*dynamodb.Client, error) {
endpoint := os.Getenv("DDB_ENDPOINT") // e.g. http://localhost:8000 for dynamodb-local
opts := []func(*config.LoadOptions) error{config.WithRegion("ap-south-1")}
if endpoint != "" {
// dynamodb-local accepts any keys; never put real ones here.
opts = append(opts, config.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider("local", "local", "")))
}
cfg, err := config.LoadDefaultConfig(ctx, opts...)
if err != nil {
return nil, err
}
return dynamodb.NewFromConfig(cfg, func(o *dynamodb.Options) {
if endpoint != "" {
o.BaseEndpoint = aws.String(endpoint)
}
}), nil
}
Creating and resolving links
Creating is a PutItem with a condition, so a taken code fails instead of silently overwriting someone's link. That's the DynamoDB version of a unique constraint.
_, err = s.db.PutItem(ctx, &dynamodb.PutItemInput{
TableName: aws.String(s.table),
Item: item,
ConditionExpression: aws.String("attribute_not_exists(PK)"),
})
var ccf *types.ConditionalCheckFailedException
if errors.As(err, &ccf) {
return ErrCodeTaken
}
Resolving is a GetItem on LINK#<code> and META, asking only for the url attribute. I wasn't sure url was safe to use as is, so I tried it with the AWS CLI against the local table. It isn't, it's actually a reserved word in DynamoDB expressions.
Invalid ProjectionExpression: Attribute name is a reserved keyword; reserved keyword: url
So it goes through a placeholder. The reserved list is long (name, owner, type and data are on it too), so I just use placeholders by habit now.
out, err := s.db.GetItem(ctx, &dynamodb.GetItemInput{
TableName: aws.String(s.table),
Key: map[string]types.AttributeValue{
"PK": &types.AttributeValueMemberS{Value: linkPK(code)},
"SK": &types.AttributeValueMemberS{Value: "META"},
},
ProjectionExpression: aws.String("#u"),
ExpressionAttributeNames: map[string]string{"#u": "url"},
})
Counting clicks
The Postgres shorty doesn't run an UPDATE per click. It counts clicks in memory and flushes them every few seconds. I kept that. So AddClicks gets a number, not a single click, and adds it to the META total and to today's DAY item.
_, err := s.db.TransactWriteItems(ctx, &dynamodb.TransactWriteItemsInput{
TransactItems: []types.TransactWriteItem{
{Update: &types.Update{
TableName: aws.String(s.table),
Key: key("META"),
UpdateExpression: aws.String("ADD clicks :n"),
ConditionExpression: aws.String("attribute_exists(PK)"),
ExpressionAttributeValues: inc,
}},
{Update: &types.Update{
TableName: aws.String(s.table),
Key: key(dayKey(now)),
UpdateExpression: aws.String("ADD clicks :n"),
ExpressionAttributeValues: inc,
}},
},
})
ADD on a number creates the attribute at zero if it's missing, so the first click of the day creates the DAY item. No read-then-write. The condition on META makes the whole transaction fail for a code that doesn't exist, otherwise a click on a deleted link would create an orphan DAY item.
Transactions cost double, each write in one takes two write units. I'm fine paying that here to keep the total and the daily numbers in step. If I didn't care, two plain UpdateItem calls would be half the price.
The daily counts are one Query with BETWEEN on the sort key.
out, err := s.db.Query(ctx, &dynamodb.QueryInput{
TableName: aws.String(s.table),
KeyConditionExpression: aws.String("PK = :pk AND SK BETWEEN :from AND :to"),
ExpressionAttributeValues: map[string]types.AttributeValue{
":pk": &types.AttributeValueMemberS{Value: linkPK(code)},
":from": &types.AttributeValueMemberS{Value: dayKey(from)},
":to": &types.AttributeValueMemberS{Value: dayKey(to)},
},
})
And the user's links come from the GSI, with ScanIndexForward: false for newest first.
The run
The demo program creates three links, tries to reuse a code, clicks a bit over three days, reads things back and deletes a link.
DDB_ENDPOINT=http://127.0.0.1:18000 go run .
taken: code already taken
resolve go-1-27: https://go.dev/doc/go1.27 <nil>
resolve nope: link not found
clicks on a missing link: true
DAY#2026-11-17 12
DAY#2026-11-18 30
DAY#2026-11-19 12
u42: pg-18 clicks=0 https://www.postgresql.org/docs/18/
u42: go-1-27 clicks=54 https://go.dev/doc/go1.27
deleted items: 4 <nil>
resolve after delete: link not found
The 19th shows 12 because two flushes landed that day, 7 and 5. 54 is the total of all four. "deleted items: 4" is the META item plus three DAY items.
Deleting a whole item collection
There is no "delete where PK = ...". You query the keys and delete them in batches of 25, and you have to retry whatever comes back in UnprocessedItems.
for len(in) > 0 {
out, err := s.db.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{RequestItems: in})
if err != nil {
return deleted, err
}
in = out.UnprocessedItems
if len(in) > 0 {
time.Sleep(200 * time.Millisecond) // throttled, try the rest again
}
}
Forgetting that loop is a classic bug, BatchWriteItem returns success even when some items were throttled and never written. A link with a year of history is 365 DAY items, so this runs fifteen batches.
What I'd change for production
The projection. I put clicks into the GSI so the "my links" page can show counts without a second read. But now every click flush writes to the base table and to the index, because DynamoDB keeps the projected copy in sync. For a page that people open now and then, I'd rather drop clicks from the projection and do a BatchGetItem for the counts. Small detail, but it's exactly the kind of cost you see only on the bill.
Hot keys. All writes for one link land on one partition, and one partition takes about 1,000 write units a second. The in-memory batching is what saves shorty here, a viral link turns thousands of clicks into one write every few seconds per server. If you write every click as its own item, you'd need to spread them over several partition keys, like LINK#go-1-27#3, and add them up on read.
Raw clicks. I left out a per-click item with referrer and country on purpose. If you want them, give them a ttl attribute so DynamoDB deletes them after 90 days for free, and keep only the daily counters forever.
For how this table sits behind Lambda, see A serverless API in Go with Lambda, API Gateway and DynamoDB. And if writing the access pattern list at the start felt hard, that's the sign. Postgres would have let you skip it, and for a lot of apps that's the better deal.