Prisma Accelerate adds edge connection pooling and query result caching to Prisma ORM — critical for serverless deployments where each function invocation would otherwise open a new database connection. UUID v7 primary keys integrate seamlessly. See UUID in Prisma for the baseline Prisma setup.
Setup
npm install @prisma/client @prisma/extension-accelerate
npx prisma init
Prisma schema with UUID v7
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL") // Direct connection for migrations
directUrl = env("DIRECT_DATABASE_URL") // Accelerate URL for queries
}
model Order {
id String @id @default(dbgenerated("gen_random_uuid_v7()")) @db.Uuid
customerId String @db.Uuid
total Decimal @db.Decimal(10, 2)
status String @default("pending")
// No createdAt — UUID v7 id encodes creation time
@@index([customerId])
}
For PostgreSQL 15–17, use gen_random_uuid() with pg_uuidv7: replace gen_random_uuid_v7() with uuid_generate_v7() after installing the extension. See PostgreSQL 18 Native UUID v7.
Prisma client with Accelerate extension
// lib/db.ts
import { PrismaClient } from '@prisma/client';
import { withAccelerate } from '@prisma/extension-accelerate';
export const db = new PrismaClient().$extends(withAccelerate());
Create and query with caching
import { db } from './lib/db';
import { v7 as uuidv7 } from 'uuid';
// Create — UUID v7 generated by PostgreSQL DEFAULT
async function createOrder(customerId: string, total: number) {
return db.order.create({
data: { customerId, total },
// No id — PostgreSQL generates UUID v7 via gen_random_uuid_v7()
});
}
// List first page — cache aggressively (stable content)
async function listOrdersFirstPage(limit = 20) {
return db.order.findMany({
orderBy: { id: 'asc' }, // UUID v7 asc = chronological
take: limit,
cacheStrategy: {
ttl: 300, // 5 minutes
swr: 60, // Stale-while-revalidate: 1 minute
},
});
}
// Cursor pagination — shorter cache for later pages
async function listOrdersPage(cursor?: string, limit = 20) {
const orders = await db.order.findMany({
orderBy: { id: 'asc' },
take: limit,
...(cursor ? {
skip: 1, // Skip the cursor row
cursor: { id: cursor },
} : {}),
cacheStrategy: cursor
? { ttl: 60, swr: 30 } // Later pages: shorter cache
: { ttl: 300, swr: 60 }, // First page: longer cache
});
const nextCursor = orders.length === limit ? orders[orders.length - 1].id : null;
return { orders, nextCursor };
}
See UUID v7 for Cursor Pagination.
Application-side UUID v7 generation
If you prefer to generate UUID v7 in the application rather than using a database default:
import { v7 as uuidv7 } from 'uuid';
async function createOrderAppSide(customerId: string, total: number) {
const id = uuidv7(); // Generated before the query
return db.order.create({
data: { id, customerId, total },
});
}
Application-side generation is useful for knowing the ID before the database round-trip — e.g., for writing to an event log or cache simultaneously.
Time-bounded cache invalidation with UUID v7
// Extract the creation time from a UUID v7 to determine cache staleness
function uuidV7CreatedAt(id: string): number {
return parseInt(id.replace(/-/g, '').slice(0, 12), 16); // ms since epoch
}
// Check if a cached page needs refresh based on the last ID's age
function isCacheStale(lastId: string, maxAgeMs = 60_000): boolean {
return Date.now() - uuidV7CreatedAt(lastId) < maxAgeMs;
}
// Use in a server component to decide whether to use cached data
async function getOrdersWithSmartCache(cursor?: string) {
const cached = await listOrdersPage(cursor);
const lastId = cached.orders.at(-1)?.id;
if (lastId && isCacheStale(lastId, 30_000)) {
// Last record is very recent — high chance of new inserts, skip cache
return db.order.findMany({
orderBy: { id: 'asc' },
take: 20,
...(cursor ? { skip: 1, cursor: { id: cursor } } : {}),
});
}
return cached.orders;
}
See UUID Bit Fields for the 48-bit timestamp layout.
Zero-downtime migration from UUID v4 to v7
// Step 1: Add new UUID v7 column (nullable)
model Order {
id String @id @db.Uuid // existing UUID v4
idV7 String? @db.Uuid // new UUID v7 column
// ...
}
// Step 2: Backfill script — run as a standalone migration
import { db } from './lib/db';
import { v7 as uuidv7 } from 'uuid';
async function backfill() {
let cursor: string | undefined;
do {
const batch = await db.order.findMany({
take: 1000,
...(cursor ? { skip: 1, cursor: { id: cursor } } : {}),
where: { idV7: null },
});
if (batch.length === 0) break;
await db.$transaction(
batch.map((o) => db.order.update({
where: { id: o.id },
data: { idV7: uuidv7() },
}))
);
cursor = batch[batch.length - 1].id;
} while (true);
}
See UUID Zero-Downtime Migration for the complete pattern.
Further reading
- UUID in Prisma — v7 Setup, Migration, Typed IDs
- PostgreSQL 18 Native UUID v7
- UUID v7 for Cursor Pagination
- UUID Zero-Downtime Migration
- UUID v7 and Caching Strategies
External references
Frequently asked questions
Does UUID v7 work with Prisma Accelerate connection pooling?
Yes. Prisma Accelerate is transparent to UUID v7 — it pools connections and forwards queries to the underlying database unchanged. UUID v7 primary keys defined in your Prisma schema work identically with Accelerate as without it. The @default(dbgenerated("gen_random_uuid_v7()")) annotation causes PostgreSQL to generate UUID v7 values server-side, which works through Accelerate's connection pool. See UUID in Prisma.
How do I cache UUID v7 queries with Prisma Accelerate?
Use Prisma Accelerate's cacheStrategy option on read queries: findMany({ cacheStrategy: { ttl: 60, swr: 30 } }). For UUID v7 cursor pagination, cache the first page (no cursor) aggressively — it rarely changes. Cache subsequent pages with shorter TTLs since they may have new inserts. UUID v7's predictable timestamp structure lets you calculate whether a cached page is stale based on the last ID's timestamp.
How do I migrate from UUID v4 to UUID v7 with Prisma Accelerate in production?
Use Prisma's zero-downtime migration pattern: add a new nullable UUID v7 column, backfill with a generated UUID v7 for each existing row (using a migration script), make it non-nullable, then swap the primary key in a follow-up migration. Prisma Accelerate's connection pool automatically routes the multi-step migration queries without any special configuration. See UUID Zero-Downtime Migration.