xiaohongshu
xiaohongshu
creating-client-singletons
Prevent 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.
Full skill instructions
Teaches global singleton pattern to prevent multiple PrismaClient instances from exhausting database connection pools.
Role: Teach proper PrismaClient instantiation and export via global singleton pattern to prevent connection pool exhaustion, P1017 errors, and serverless deployment failures.
When to Activate: Creating PrismaClient instances, setting up database clients/exports, encountering P1017 errors, working with serverless environments (Next.js, Lambda, Vercel), or reviewing @prisma/client code.
Problem: Creating multiple new PrismaClient() instances (the #1 Prisma violation) creates separate connection pools causing: pool exhaustion/P1017 errors, performance degradation, serverless failures (Lambda instances × pool size = disaster), and memory waste. Critical: 80% of AI agents in testing created multiple instances causing production failures.
Solution: Use global singleton pattern with module-level export: (1) check if PrismaClient exists globally, (2) create if none exists, (3) export for module reuse, (4) never instantiate in functions/classes. Supports module-level singletons (Node.js), global singletons (serverless/hot-reload), test patterns, and pool configuration.
Phase 1 — Assess: Grep for @prisma/client imports and new PrismaClient() calls; identify environment type (hot-reload vs. serverless vs. traditional Node.js vs. tests).
Phase 2 — Implement: Choose pattern based on environment; create/update client export (lib/db.ts or lib/prisma.ts) using global singleton check; update all imports to use singleton; remove duplicate instantiations.
Phase 3 — Validate: Grep for new PrismaClient() (
should appear once only); test hot reload; verify no P1017 errors; check database connection count; monitor production deployment and logs.
File: lib/db.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export default prisma;
Usage: import prisma from '@/lib/db' — works because module loads once in Node.js, creating single shared instance.
File: lib/prisma.ts
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined };
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
Why: globalThis survives hot module reload; development reuses client across reloads; production creates clean instance per deployment; prevents "too many clients" during development.
WRONG:
async function getUsers() {
const prisma = new PrismaClient(); // ❌ New pool every call
const users = await prisma.user.findMany();
await prisma.$disconnect();
return users;
}
Problems: New connection pool per function call; connection overhead kills performance; pool never warms up; exhausts connections under load.
Fix: import prisma from '@/lib/db' and use it directly without creating new instances.
references/serverless-pattern.md — Next.js App Router, Vercel, AWS Lambda configurationsreferences/test-pattern.md — test setup, mocking, isolation strategiesreferences/common-scenarios.md — codebase conversion, P1017 troubleshooting, configurationLoad when working with serverless, writing tests, or troubleshooting specific issues.
MUST: Create PrismaClient exactly
once; export from centralized module (lib/db.ts); use global singleton in hot-reload environments; import singleton in all database-access files; never instantiate inside functions or classes.
SHOULD: Place in lib/db.ts, lib/prisma.ts, or src/db.ts; configure logging based on NODE_ENV; set connection pool size for deployment; use TypeScript; document connection configuration.
NEVER: Create PrismaClient in route handlers, API endpoints, service functions, test files, utility functions; create multiple instances "just to be safe"; disconnect/reconnect repeatedly.
After implementing:
| Check | Command/Method | Expected | Issue |
|---|---|---|---|
| Multiple instances | grep -r "new PrismaClient()" --include="*.ts" --include="*.js" | Exactly one occurrence (singleton file only) | Consolidate to single singleton |
| Import patterns | grep -r "from '@prisma/client'" | Most imports from singleton module; only singleton imports from @prisma/client | Update imports to use singleton |
| Connection pool | Monitor during development hot reload | Connection count stays constant (not growing) | Global singleton pattern not working |
| Production errors | Check logs for P1017 | Zero connection pool errors | Check serverless connection_limit config |
| Test isolation | Run test suite | Tests pass; no connection errors | Ensure tests import singleton |
TypeScript:
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined };
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
JavaScript:
const { PrismaClient } = require('@prisma/client');
const globalForPrisma = globalThis;
const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
module.exports = prisma;
Setup Checklist:
lib/db.ts or lib/prisma.ts; use global singleton pattern (hot reload environments); export single instance; configure logging by NODE_ENV; set connection_limit for serverless; import singleton in all files; never create PrismaClient elsewhere; validate with grep (one instance); test hot reload; monitor production connectionsRed Flags (Implement Singleton Immediately):
new PrismaClient() in grep results; P1017 errors in logs; growing connection count during development; different files importing from @prisma/client; PrismaClient creation inside functions; test files creating own clientsTypeScript Type Safety:
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience