/prisma-6:managing-client-lifecyclefrom prisma-6
Manage PrismaClient lifecycle with graceful shutdown, proper disconnect timing, and logging configuration. Use when setting up application shutdown handlers, configuring logging for development or production, or implementing proper connection cleanup in Node.js servers, serverless functions, or test suites.
Ships in prisma-6. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Teaches proper PrismaClient lifecycle patterns for connection cleanup and logging following Prisma 6 best practices.
Activates when: Setting up shutdown handlers (SIGINT, SIGTERM), configuring PrismaClient logging, implementing connection cleanup in servers/serverless/tests, writing test teardown logic, or user mentions "shutdown", "disconnect", "cleanup", "logging", "graceful exit".
Why it matters: Proper lifecycle management ensures clean connection closure on shutdown, prevents hanging connections from exhausting database resources, provides development/production visibility through logging, and prevents connection leaks in tests.
import express from 'express'
import { prisma } from './lib/prisma'
const app = express()
const server = app.listen(3000)
async function gracefulShutdown(signal: string) {
console.log(`Received ${signal}, closing gracefully...`)
server.close(async () => {
await prisma.$disconnect()
process.exit(0)
})
setTimeout(() => { process.exit(1) }, 10000) // Force exit if hung
}
process.on('SIGINT', () => gracefulShutdown('SIGINT'))
process.on('
SIGTERM', () => gracefulShutdown('SIGTERM'))
Close HTTP server first (stops new requests), then $disconnect() database, add 10s timeout to force exit if cleanup hangs. Fastify simplifies this with fastify.addHook('onClose', () => prisma.$disconnect()).
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
afterAll(async () => {
await prisma.$disconnect();
});
beforeEach(async () => {
await prisma.user.deleteMany(); // Clean data, NOT connections
});
test('creates user', async () => {
const user = await prisma.user.create({
data: { email: '[email protected]', name: 'Test' },
});
expect(user.email).toBe('[email protected]');
});
Use single PrismaClient instance across all tests; $disconnect() only in afterAll(); clean database state between tests, not connections.
For Vitest setup configuration (setupFiles, global hooks), see vitest-4/skills/configuring-vitest-4/SKILL.md.
Do NOT disconnect in handlers — breaks warm starts (connection setup every invocation). Use global singleton pattern with connection pooling managed by CLIENT-serverless-config. Exception: RDS Proxy with specific requirements may benefit from explicit $disconnect().
Development: No explicit disconnect needed; Next.js manages lifecycle. Production: Depends on deployment—follow CLIENT-serverless-config for serverless, server pattern for traditional deployment.
| Environment | Config | Output |
|---|---|---|
| Development | log: ['query', 'info', 'warn', 'error'] | Every SQL query with parameters, connection events, warnings/errors |
| Production | `log: ['warn |
', 'error']| Only warnings and errors; reduced log volume, better performance | | **Environment-based** |log: process.env.NODE_ENV === 'production' ? ['warn', 'error'] : ['query', 'info', 'warn', 'error']` | Conditional verbosity |
Custom event handling:
const prisma = new PrismaClient({
log: [
{ emit: 'event', level: 'query' },
{ emit: 'event', level: 'error' },
{ emit: 'stdout', level: 'warn' },
],
});
prisma.$on('query', (e) => {
console.log(`Query: ${e.query} (${e.duration}ms)`);
});
prisma.$on('error', (e) => {
console.error('Prisma Error:', e);
});
MUST:
SHOULD:
NEVER:
Validation:
npm test — expect no "jest/vitest did not exit" warnings, no connection errors| Issue | Cause | Solution |
|---|---|---|
| "jest/vitest did not exit" warning | Missing $disconnect() in afterAll() | Add afterAll(async () => { await prisma.$disconnect() }) |
| "
Too many connections" in tests | New PrismaClient created per test file | Use global singleton pattern (see Vitest setup above) |
| Process hangs on shutdown | Forgot await on $disconnect() | Always await prisma.$disconnect() |
| Serverless cold starts very slow | Disconnecting in handler breaks warm starts | Remove $disconnect() from handler; use connection pooling |
| Connection pool exhausted after shutdown | $disconnect() called before server.close() | Reverse order: close server first, then disconnect |
Express.js: Use server.close() before $disconnect(); handle SIGINT + SIGTERM; add timeout for forced exit.
Fastify: Use onClose hook—framework handles signal listeners and ordering automatically.
NestJS: Implement onModuleDestroy lifecycle hook; use @nestjs/terminus for health checks; automatic cleanup via module system.
Next.js: Dev mode—no explicit disconnect needed. Production—depends on deployment (serverless: see CLIENT-serverless-config; traditional: use server pattern). Server Actions/API Routes—follow serverless pattern.
Serverless (Lambda, Vercel, Cloudflare): Default—do NOT disconnect in handlers. Exception—RDS Proxy with specific config. See CLIENT-serverless-config for connection management.
Test Frameworks: Jest—afterAll() in files or global teardown. Vitest—global setupFiles. Mocha—after() in root suite. Playwright—globalTeardown for E2E.
Next.js Integration:
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub djankies/claude-configs --plugin prisma-619 skills in this plugin
/configuring-connection-poolsConfigure connection pool sizing for optimal performance. Use when configuring DATABASE_URL or deploying to production./configuring-serverless-clientsConfigure PrismaClient for serverless (Next.js, Lambda, Vercel) with connection_limit=1 and global singleton pattern./configuring-transaction-isolationConfigure transaction isolation levels to prevent race conditions and handle concurrent access. Use when dealing with concurrent updates, financial operations, inventory management, or when users mention race conditions, dirty reads, phantom reads, or concurrent modifications./creating-client-singletonsPrevent multiple PrismaClient instances that exhaust connection pools causing P1017 errors. Use when creating PrismaClient, exporting database clients, setting up Prisma in new files, or encountering connection pool errors. Critical for serverless environments./deploying-production-migrationsDeploy migrations to production safely using migrate deploy in CI/CD. Use when setting up production deployment pipelines./ensuring-query-type-safetyUse Prisma's generated types, `Prisma.validator`, and `GetPayload` for type-safe queries.