Encore.ts is a TypeScript backend framework that defines infrastructure (databases, queues, pub/sub) declaratively alongside service code. UUID v7 pairs well with Encore: generate IDs server-side, store them as PostgreSQL primary keys, and use them as correlation IDs across Encore’s typed inter-service calls. See UUID in Databases for storage patterns.
Setup
npm install uuid
npm install --save-dev @types/uuid
Encore’s PostgreSQL database is provisioned automatically — no connection string needed.
Encore database with UUID v7 schema
// orders/db.ts
import { SQLDatabase } from 'encore.dev/storage/sqldb';
export const db = new SQLDatabase('orders', {
migrations: './migrations',
});
-- orders/migrations/1_create_orders.up.sql
CREATE TABLE orders (
id TEXT PRIMARY KEY, -- UUID v7, generated in service
customer_id TEXT NOT NULL,
total NUMERIC(10, 2) NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX orders_customer_idx ON orders (customer_id);
-- No created_at index needed for time sort — ORDER BY id works
Encore service with UUID v7
// orders/orders.ts
import { api } from 'encore.dev/api';
import { v7 as uuidv7 } from 'uuid';
import { db } from './db';
interface CreateOrderRequest {
customerId: string;
total: number;
correlationId?: string; // UUID v7 from the caller for tracing
}
interface CreateOrderResponse {
id: string; // UUID v7 primary key
customerId: string;
total: number;
status: string;
correlationId: string;
}
export const createOrder = api(
{ expose: true, method: 'POST', path: '/orders' },
async (req: CreateOrderRequest): Promise<CreateOrderResponse> => {
const id = uuidv7();
// Correlation ID: use caller's if provided, otherwise generate a new one
const correlationId = req.correlationId ?? uuidv7();
await db.exec`
INSERT INTO orders (id, customer_id, total)
VALUES (${id}, ${req.customerId}, ${req.total})
`;
console.log(`[${correlationId}] Created order ${id}`);
return { id, customerId: req.customerId, total: req.total, status: 'pending', correlationId };
}
);
Cursor pagination
interface ListOrdersRequest {
cursor?: string; // UUID v7 cursor
limit?: number;
}
interface ListOrdersResponse {
orders: { id: string; customerId: string; total: number; status: string }[];
nextCursor: string | null;
}
export const listOrders = api(
{ expose: true, method: 'GET', path: '/orders' },
async (req: ListOrdersRequest): Promise<ListOrdersResponse> => {
const limit = Math.min(req.limit ?? 20, 100);
const rows = req.cursor
? await db.query<{ id: string; customer_id: string; total: number; status: string }>`
SELECT id, customer_id, total, status FROM orders
WHERE id > ${req.cursor}
ORDER BY id
LIMIT ${limit}
`
: await db.query<{ id: string; customer_id: string; total: number; status: string }>`
SELECT id, customer_id, total, status FROM orders
ORDER BY id
LIMIT ${limit}
`;
const orders = rows.map((r) => ({
id: r.id,
customerId: r.customer_id,
total: r.total,
status: r.status,
}));
const nextCursor = orders.length === limit ? orders[orders.length - 1].id : null;
return { orders, nextCursor };
}
);
UUID v7 lexicographic order equals chronological order — WHERE id > cursor ORDER BY id gives correct time-ordered pagination. See UUID v7 for Cursor Pagination.
Idempotency with UUID v7
interface ProcessPaymentRequest {
idempotencyKey: string; // UUID v7 from the client
orderId: string;
amount: number;
}
export const processPayment = api(
{ expose: true, method: 'POST', path: '/payments' },
async (req: ProcessPaymentRequest): Promise<{ paymentId: string; status: string }> => {
// Check for an existing payment with this idempotency key
const existing = await db.queryRow<{ id: string; status: string }>`
SELECT id, status FROM payments WHERE idempotency_key = ${req.idempotencyKey}
`;
if (existing) {
return { paymentId: existing.id, status: existing.status };
}
const paymentId = uuidv7();
await db.exec`
INSERT INTO payments (id, order_id, amount, idempotency_key)
VALUES (${paymentId}, ${req.orderId}, ${req.amount}, ${req.idempotencyKey})
`;
return { paymentId, status: 'pending' };
}
);
See UUID as Idempotency Keys for the full pattern.
Service-to-service calls with correlation ID
// shipping/shipping.ts — calls the orders service
import { createOrder } from '~encore/clients';
import { v7 as uuidv7 } from 'uuid';
export const fulfillOrder = api(
{ expose: false },
async (req: { customerId: string; items: string[] }) => {
const correlationId = uuidv7(); // Root trace ID for this operation
// Pass correlation ID through typed Encore API call
const order = await createOrder({
customerId: req.customerId,
total: calculateTotal(req.items),
correlationId,
});
console.log(`[${correlationId}] Fulfilling order ${order.id}`);
// UUID v7 timestamp in correlationId tells you when this chain started
}
);
Timestamp extraction
// Extract creation time from a UUID v7 (millisecond precision)
function extractTimestamp(id: string): Date {
const hex = id.replace(/-/g, '').slice(0, 12);
return new Date(parseInt(hex, 16));
}
// Log analysis: determine when a correlation ID chain started
const start = extractTimestamp('018fbe3a-4c5d-7b12-8f3e-1a2b3c4d5e6f');
See UUID Bit Fields for the 48-bit timestamp layout.
Further reading
- PostgreSQL 18 Native UUID v7
- UUID in Databases — Storage and Indexing
- UUID v7 in Microservices — Trace IDs and Correlation
- UUID v7 for Cursor Pagination
- UUID as Idempotency Keys
External references
Frequently asked questions
How do I use UUID v7 as a primary key in Encore.ts?
Encore uses PostgreSQL for its SQL database. Define your table with a UUID primary key and generate UUID v7 in your service before insertion: import { v7 as uuidv7 } from 'uuid' then const id = uuidv7(). Pass the ID in the INSERT statement. With PostgreSQL 18 you can use gen_random_uuid_v7() as a column default. See PostgreSQL 18 Native UUID v7.
Can I use UUID v7 as a correlation ID in Encore.ts service calls?
Yes. Generate a UUID v7 at the API gateway entry point and pass it through Encore's typed API calls as a field in your request type. Because Encore services call each other with typed interfaces, the correlation ID flows through the call graph without HTTP header manipulation. UUID v7's timestamp lets you extract when a request chain started from the correlation ID alone.
How does UUID v7 help with Encore's distributed tracing?
Encore has built-in distributed tracing. Adding UUID v7 correlation IDs to your API types supplements Encore's tracing with application-level IDs that survive log aggregation, client callbacks, and webhook payloads. The UUID v7 timestamp prefix lets you correlate log entries across services even without a central tracing backend.