- AWS
- Engineering
Modeling DynamoDB Many to Many Relationships with Adjacency Lists
Learn how to structure many-to-many relationships in DynamoDB using single-table design and adjacency lists for fast, dual-direction querying.
DynamoDB Many to Many Relationships: The Adjacency List Pattern in Single Table Design
Moving from PostgreSQL to DynamoDB means changing how you think about data. In SQL, linking two entities is easy: you add a join table with two foreign keys and move on. DynamoDB has no foreign keys and no runtime JOINs. A DynamoDB many to many relationship only works well if you plan around your exact access patterns before you create a single index.
I reach for DynamoDB a lot when I build serverless APIs on AWS Lambda. The same problem comes up every time. Two entities, like Users and Organizations or Students and Courses, need to point at each other in both directions, and you do not want scans or huge duplicated records. This post walks through the fix I use: the adjacency list pattern inside a DynamoDB single table design, with a Global Secondary Index (GSI) to flip the lookup.
The Problem with Many to Many in DynamoDB
In a relational database you would create a users table, an organizations table, and a user_organizations membership table. Need every organization for a user? Query the join table one way. Need every member of an organization? Query it the other way.
DynamoDB will not join tables for you. If you copy the relational layout into three DynamoDB tables, you run into the N+1 query problem. Your code fetches a list, then makes one more request per item. On a busy API that means extra latency, more read capacity units (RCUs) burned, and a bigger AWS bill.
The better approach in NoSQL data modeling is to keep related items in one table, give them generic partition and sort keys, and use a GSI for the reverse direction.
What Is the DynamoDB Adjacency List Pattern?
An adjacency list stores a graph in a key-value store. Every node is an item (a user, an organization). Every edge is its own item too (a membership). Because each relationship is a separate record, you never embed a growing list inside a parent item, and you stay far away from the 400 KB item size limit.
Take a SaaS app where Users belong to many Organizations and Organizations have many Users. We need to:
- Fetch an organization profile and all of its members in one query.
- Fetch a user profile and all of their organizations in one query.
- Add, update, or remove a membership without rewriting the user or organization record.
The base table uses two generic string keys, PK and SK. We add one GSI, called GSI1, with GSI1PK and GSI1SK as its keys. For membership items, the GSI keys are the base keys swapped around.
Designing Partition Keys and Sort Keys for Bidirectional Lookups
The whole thing depends on consistent prefixes. Every item type gets its own namespace so keys never collide and are easy to read in the console.
| Item | PK | SK | GSI1PK | GSI1SK |
|------|----|----|--------|--------|
| User profile | `USER#<userId>` | `PROFILE#<userId>` | `USER#<userId>` | `#PROFILE` |
| Organization profile | `ORG#<orgId>` | `PROFILE#<orgId>` | none | none |
| Membership edge | `ORG#<orgId>` | `USER#<userId>` | `USER#<userId>` | `ORG#<orgId>` |Look at the membership row. Its partition key is the organization and its sort key is the user, so one query on PK = ORG#123 returns the org profile plus every member edge. The GSI attributes run the other way: GSI1PK is the user and GSI1SK is the org. One query on GSI1PK = USER#abc returns every organization that user belongs to.
One detail that is easy to miss: for the user profile query to return the profile and the memberships together, the user profile also needs GSI1PK = USER#<userId>. I give it a GSI1SK of #PROFILE. The # character sorts before letters, so the profile always comes back first, followed by the ORG# edges.
Setting Up the Client with AWS SDK v3
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
DynamoDBDocumentClient,
QueryCommand,
BatchGetCommand,
BatchWriteCommand,
TransactWriteCommand,
} from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({});
export const ddb = DynamoDBDocumentClient.from(client, {
marshallOptions: { removeUndefinedValues: true },
});
export const TABLE = process.env.TABLE_NAME!;
export const GSI1 = "GSI1";Creating a Membership with TransactWriteCommand
When a user joins an organization, I write the edge and bump a member counter on the org in one transaction. The condition on the Put stops duplicate memberships, so calling the endpoint twice is safe.
type Role = "owner" | "admin" | "member";
export async function addMember(orgId: string, userId: string, role: Role) {
const now = new Date().toISOString();
await ddb.send(
new TransactWriteCommand({
TransactItems: [
{
Put: {
TableName: TABLE,
Item: {
PK: `ORG#${orgId}`,
SK: `USER#${userId}`,
GSI1PK: `USER#${userId}`,
GSI1SK: `ORG#${orgId}`,
type: "MEMBERSHIP",
role,
joinedAt: now,
},
ConditionExpression: "attribute_not_exists(PK)",
},
},
{
Update: {
TableName: TABLE,
Key: { PK: `ORG#${orgId}`, SK: `PROFILE#${orgId}` },
UpdateExpression: "ADD memberCount :one",
ConditionExpression: "attribute_exists(PK)",
ExpressionAttributeValues: { ":one": 1 },
},
},
],
})
);
}
Querying Both Directions in TypeScript
With this layout, both lookups are a single Query. No scans, no filters over the whole table.
// 1. Organization profile + all members (base table)
export async function getOrgWithMembers(orgId: string) {
const res = await ddb.send(
new QueryCommand({
TableName: TABLE,
KeyConditionExpression: "PK = :pk",
ExpressionAttributeValues: { ":pk": `ORG#${orgId}` },
})
);
const items = res.Items ?? [];
return {
org: items.find((i) => i.SK.startsWith("PROFILE#")),
members: items.filter((i) => i.SK.startsWith("USER#")),
nextToken: res.LastEvaluatedKey, // keep paging if the org is large
};
}
// 2. User profile + all organizations (GSI1)
export async function getUserWithOrgs(userId: string) {
const res = await ddb.send(
new QueryCommand({
TableName: TABLE,
IndexName: GSI1,
KeyConditionExpression: "GSI1PK = :pk",
ExpressionAttributeValues: { ":pk": `USER#${userId}` },
})
);
const items = res.Items ?? [];
return {
user: items.find((i) => i.GSI1SK === "#PROFILE"),
memberships: items.filter((i) => i.GSI1SK.startsWith("ORG#")),
nextToken: res.LastEvaluatedKey,
};
}
Both calls hit one partition and usually return in single-digit milliseconds. That matters when traffic spikes, because slow queries tie up Lambda concurrency and back up downstream queues such as background jobs with BullMQ and Redis.
Two things to remember. A single Query returns at most 1 MB, so loop on LastEvaluatedKey for big partitions. And GSI reads are eventually consistent, so a membership you just wrote can take a moment to show up in the user-side query.
Data Duplication vs Second-Hop Queries
The edge item only holds relationship data like role and joinedAt. What if your UI needs each member's name and avatar? You have two options: denormalize or batch fetch.
Option 1: Denormalize onto the edge
Copy rarely changing fields, such as userName and userEmail, onto the membership item. Reads get faster and cheaper. The cost is upkeep: if a user renames themselves, you must update their profile and every membership they own. For fields that almost never change, that is usually a fair trade.
Option 2: Batch fetch the profiles
If the data changes often, do not copy it. Query the edges, collect the user IDs, then call BatchGetItem to load current profiles in parallel.
export async function getMemberProfiles(userIds: string[]) {
const profiles: Record<string, any>[] = [];
// BatchGetItem accepts at most 100 keys per call
for (let i = 0; i < userIds.length; i += 100) {
let keys: Record<string, any>[] = userIds.slice(i, i + 100).map((id) => ({
PK: `USER#${id}`,
SK: `PROFILE#${id}`,
}));
// retry anything DynamoDB did not process
while (keys.length > 0) {
const res = await ddb.send(
new BatchGetCommand({
RequestItems: { [TABLE]: { Keys: keys } },
})
);
profiles.push(...(res.Responses?.[TABLE] ?? []));
keys = (res.UnprocessedKeys?.[TABLE]?.Keys as any[]) ?? [];
}
}
return profiles;
}It costs one extra round trip, but you get fresh data and no sync bugs. You can also pass ConsistentRead: true on the batch request when you need it.
Removing Memberships and Cleaning Up Deleted Users
DynamoDB has nothing like ON DELETE CASCADE. If you delete a user profile, their membership edges stay in the table until you remove them yourself. Revoking one membership is another transaction:
export async function removeMember(orgId: string, userId: string) {
await ddb.send(
new TransactWriteCommand({
TransactItems: [
{
Delete: {
TableName: TABLE,
Key: { PK: `ORG#${orgId}`, SK: `USER#${userId}` },
ConditionExpression: "attribute_exists(PK)",
},
},
{
Update: {
TableName: TABLE,
Key: { PK: `ORG#${orgId}`, SK: `PROFILE#${orgId}` },
UpdateExpression: "ADD memberCount :minus",
ExpressionAttributeValues: { ":minus": -1 },
},
},
],
})
);
}
For a full user delete, use the GSI to find every edge, then remove them in chunks. This is a good job for a DynamoDB Streams trigger or a queued worker, so the user-facing request stays fast.
export async function deleteAllMembershipsForUser(userId: string) {
let lastKey: Record<string, any> | undefined;
do {
const page = await ddb.send(
new QueryCommand({
TableName: TABLE,
IndexName: GSI1,
KeyConditionExpression: "GSI1PK = :pk AND begins_with(GSI1SK, :org)",
ExpressionAttributeValues: { ":pk": `USER#${userId}`, ":org": "ORG#" },
ExclusiveStartKey: lastKey,
})
);
const edges = page.Items ?? [];
for (let i = 0; i < edges.length; i += 25) {
await ddb.send(
new BatchWriteCommand({
RequestItems: {
[TABLE]: edges.slice(i, i + 25).map((e) => ({
DeleteRequest: { Key: { PK: e.PK, SK: e.SK } },
})),
},
})
);
}
lastKey = page.LastEvaluatedKey;
} while (lastKey);
}If your service also reacts to events or webhooks, pair this with the retry and signature checks from FastAPI webhook HMAC verification and retries so your async sync stays reliable. Note that this simple version does not decrement each org's memberCount. If you rely on that counter, use a transaction per edge instead.
Common Mistakes to Avoid
- Hot partitions. A giant organization puts all its members under one partition key. If one org can reach hundreds of thousands of members, shard the key (for example
ORG#123#1,ORG#123#2) or move members to their own partition. - Using Scan as a shortcut. If you need a Scan, your access pattern was not mapped to a key yet.
- Forgetting the GSI attributes. A GSI only indexes items that have its key attributes. Skip them on an edge and that edge is invisible from the reverse side.
- Unbounded arrays. Never store a growing
members: []list inside a profile. Use edge items.
Key Takeaways for DynamoDB Relationship Design
- Model each relationship as its own item. Do not embed unbounded arrays in a parent record.
- Invert the partition and sort keys on a GSI so you can query in both directions.
- Denormalize only static or rarely changed fields. Use
BatchGetItemfor anything that changes often. - Use
TransactWriteCommandto update edges and parent counters together. - Write down your access patterns first. Once every query maps to a partition key and sort key, DynamoDB data modeling gets predictable.
FAQ
How do you model a many to many relationship in DynamoDB?
Store each relationship as a separate item using the adjacency list pattern. Put the two entity IDs in the partition and sort keys, then add a GSI that swaps them so you can query from either side.
Is single table design required for many to many in DynamoDB?
No, but it helps. Keeping entities and edges in one table lets you load a profile and its relationships in a single Query instead of several requests.
How many items can a DynamoDB transaction touch?
A TransactWriteItems call supports up to 100 items. Transactions cost roughly double the write capacity of normal writes, so use them where you need atomicity, not everywhere.
Can I use a GSI for strongly consistent reads?
No. Global secondary indexes only support eventually consistent reads. If you need strong consistency, read from the base table.
Related posts
Verifying Shopify Session Tokens in FastAPI
Learn how to validate JWT session tokens from Shopify App Bridge inside a Python FastAPI backend.
Read articleRotating Secrets in AWS Secrets Manager FastAPI Services
Learn how to fetch, cache, and rotate database credentials dynamically in FastAPI using AWS Secrets Manager and SQLAlchemy without application downtime.
Read articleS3 Presigned URL FastAPI: Secure Client-Side Uploads
Offload file handling from your API. Learn how to generate secure, time-limited S3 presigned URLs in FastAPI using boto3 for direct client uploads.
Read article