Composite keys express real-world constraints — an order belongs to a tenant, an event belongs to a user. UUID v7 as the row-level component provides time ordering within each partition. See Surrogate Key for the single-column alternative.
PostgreSQL composite primary key with UUID v7
-- Multi-tenant orders table with composite primary key
CREATE TABLE orders (
tenant_id UUID NOT NULL,
id UUID NOT NULL, -- UUID v7 — time-ordered within tenant
customer_id UUID NOT NULL,
total NUMERIC(10,2) NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
PRIMARY KEY (tenant_id, id)
);
-- Composite index supports per-tenant cursor pagination
CREATE INDEX idx_orders_tenant_id ON orders (tenant_id, id);
Insert with UUID v7 record component
import { Pool } from 'pg';
import { v7 as uuidv7 } from 'uuid';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function createOrder(tenantId: string, customerId: string, total: number) {
const id = uuidv7(); // UUID v7 — time-ordered within this tenant's partition
await pool.query(
'INSERT INTO orders (tenant_id, id, customer_id, total) VALUES ($1, $2, $3, $4)',
[tenantId, id, customerId, total]
);
return { tenantId, id };
}
Cursor pagination on composite key
// Efficient range scan within a tenant partition using UUID v7 sort order
async function listTenantOrders(tenantId: string, cursor?: string, limit = 20) {
const { rows } = cursor
? await pool.query(
`SELECT id, total, status FROM orders
WHERE tenant_id = $1 AND id > $2
ORDER BY id LIMIT $3`,
[tenantId, cursor, limit]
)
: await pool.query(
`SELECT id, total, status FROM orders
WHERE tenant_id = $1
ORDER BY id LIMIT $2`,
[tenantId, limit]
);
return {
items: rows,
nextCursor: rows.length === limit ? rows.at(-1)?.id : null,
};
}
DynamoDB composite key with UUID v7 sort key
import { DynamoDBClient, PutItemCommand, QueryCommand } from '@aws-sdk/client-dynamodb';
import { v7 as uuidv7 } from 'uuid';
const ddb = new DynamoDBClient({ region: 'us-east-1' });
async function createOrder(tenantId: string, total: number) {
const id = uuidv7(); // UUID v7 sort key — chronological within partition
await ddb.send(new PutItemCommand({
TableName: 'Orders',
Item: {
pk: { S: `TENANT#${tenantId}` }, // partition key
sk: { S: id }, // sort key — UUID v7
total: { N: String(total) },
},
}));
return id;
}
async function listOrders(tenantId: string, cursor?: string) {
const params: any = {
TableName: 'Orders',
KeyConditionExpression: cursor
? 'pk = :pk AND sk > :cursor'
: 'pk = :pk',
ExpressionAttributeValues: {
':pk': { S: `TENANT#${tenantId}` },
...(cursor ? { ':cursor': { S: cursor } } : {}),
},
};
const result = await ddb.send(new QueryCommand(params));
return result.Items ?? [];
}
Composite key vs surrogate key
| Pattern | Uniqueness | Partition support | Cursor pagination |
|---|---|---|---|
| Surrogate key (UUID v7) | Global | None | Simple range on id |
| Composite (tenant_id, UUID v7) | Per-tenant | Per tenant | Range on (tenant_id, id) |
| Composite (type, UUID v7) | Per entity type | Per type | Range on (type, id) |
Further reading
- Surrogate Key
- UUID v7 for Cursor Pagination
- UUID v7 in Nile Postgres
- UUID in PostgreSQL
- UUID v4 vs UUID v7
Frequently asked questions
What is a composite key?
A composite key uses two or more columns together as a unique row identifier. Common patterns are (tenant_id, record_id) for multi-tenant systems, (partition_key, sort_key) for DynamoDB, and (user_id, event_id) for event tables. See Surrogate Key for the single-column alternative.
How does UUID v7 improve composite keys over UUID v4?
In a composite key like (tenant_id, record_id), the record_id component scans within a partition. UUID v4 is random — B-tree index scans within a partition are non-sequential. UUID v7's time-ordered prefix means new records land near the end of the B-tree within each partition, reducing page splits and improving range scan performance.
How do composite keys with UUID v7 work in DynamoDB?
DynamoDB uses a partition key (hash) and optional sort key. Use the tenant ID or entity type as the partition key and UUID v7 as the sort key. DynamoDB stores items in sort-key order within a partition — UUID v7 sort key gives chronological order. Use KeyConditionExpression: "pk = :pk AND sk > :cursor" for cursor pagination. See UUID v7 for Cursor Pagination.