Solving Prisma ORM Performance and Query Problems
Query logging, select over include and connection pooling: the usual suspects behind slow Prisma code.
- prisma
- orm
- performance
- postgresql
On this page ยท 14 sections
Prisma makes database code pleasant to write, which is exactly why performance problems hide in it. A clean findMany can compile into one fast query, or into a hundred round trips, depending on how you shape it. This guide covers the usual causes of slow Prisma code (N+1 queries, over-fetching, missing indexes, connection pool exhaustion, slow transactions) and how to find and fix each one.
Prisma's API and connection handling have evolved across major versions, so check the documentation for your version where this guide mentions pool configuration.
Step 0: See what Prisma actually runs
You cannot fix what you cannot see. Turn on query logging and read the SQL and durations:
// src/db.tsimport { PrismaClient } from "@prisma/client";const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };export const prisma = globalForPrisma.prisma ?? new PrismaClient({ log: process.env.NODE_ENV === "development" ? [{ emit: "stdout", level: "query" }, "warn", "error"] : ["warn", "error"], });if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;The globalThis pattern also solves a classic development problem: hot reloading re-runs your module and would otherwise create a new PrismaClient (and a new connection pool) on every reload.
To log only slow queries, emit events and filter by duration (the event API can differ between versions, so verify against your version's docs):
const prisma = new PrismaClient({ log: [{ emit: "event", level: "query" }] });prisma.$on("query", (e) => { if (e.duration > 200) { console.warn(`[slow query] ${e.duration}ms ${e.query}`); }});Problem 1: N+1 queries
Symptom. One endpoint produces dozens or hundreds of nearly identical queries in the log.
Cause. A loop that fetches related data per item:
// Anti-pattern: 1 query for posts + 1 query per postconst posts = await prisma.post.findMany({ take: 50 });const withAuthors = [];for (const post of posts) { const author = await prisma.user.findUnique({ where: { id: post.authorId } }); withAuthors.push({ ...post, author });}Fix A: load the relation with the parent query.
const posts = await prisma.post.findMany({ take: 50, select: { id: true, title: true, author: { select: { id: true, name: true } }, },});Fix B: batch with in when you cannot use a relation.
const posts = await prisma.post.findMany({ take: 50 });const authorIds = [...new Set(posts.map((p) => p.authorId))];const authors = await prisma.user.findMany({ where: { id: { in: authorIds } } });const byId = new Map(authors.map((a) => [a.id, a]));const result = posts.map((p) => ({ ...p, author: byId.get(p.authorId) }));Two queries instead of fifty-one. In GraphQL resolvers, a batching layer such as DataLoader applies the same idea automatically.
Prisma also lets you choose how relations are loaded (separate queries versus a single joined query) through the relationLoadStrategy option in recent versions. Measure both for your data rather than assuming one is always better.
Problem 2: Over-fetching
findMany() without select returns every column, including large text or json fields you may never use. Select only what the caller needs:
// Returns every column of every rowconst users = await prisma.user.findMany();// Returns only what the list view displaysconst users = await prisma.user.findMany({ select: { id: true, name: true, avatarUrl: true }, orderBy: { createdAt: "desc" }, take: 20,});Always bound lists with take, and paginate. An unbounded findMany on a growing table is a production incident waiting for the right amount of data.
Problem 3: Missing indexes
Prisma does not create indexes for your filters. If you query by a column, index it in the schema:
model Order { id String @id @default(uuid()) customerId String status String createdAt DateTime @default(now()) customer Customer @relation(fields: [customerId], references: [id]) @@index([customerId, status, createdAt(sort: Desc)])}Apply it with a migration:
npx prisma migrate dev --name add_order_indexFor production databases, check how the migration creates the index. On large tables, building an index can lock writes, and you may want to create it manually with CREATE INDEX CONCURRENTLY (in PostgreSQL) and mark the migration as applied. Then confirm with EXPLAIN ANALYZE on the SQL from the query log that the database actually uses it.
Foreign key columns used in joins and filters usually deserve an index too. Some databases create one automatically and others do not.
Problem 4: Pagination that gets slower
skip with a large number forces the database to read and discard rows. Prefer cursor pagination:
async function listPosts(cursor?: string, take = 20) { const rows = await prisma.post.findMany({ take: take + 1, ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}), orderBy: [{ createdAt: "desc" }, { id: "desc" }], select: { id: true, title: true, createdAt: true }, }); const hasMore = rows.length > take; const items = hasMore ? rows.slice(0, take) : rows; return { items, nextCursor: hasMore ? items[items.length - 1]!.id : null };}Fetching take + 1 rows is a cheap way to know whether another page exists. Make sure the orderBy columns are covered by an index.
Problem 5: Connection pool exhaustion
Symptom. Errors such as "Timed out fetching a new connection from the connection pool", or the database reporting "too many connections".
Causes and fixes:
- Multiple clients. Creating
new PrismaClient()per request or per module opens many pools. Use one shared instance per process. - Many instances, small database. Total connections = pool size ร application instances. Serverless and autoscaling multiply this quickly. Put a pooler such as PgBouncer (or a managed pooling service) between the app and the database.
- Long transactions. A transaction holds a connection for its entire duration. Keep transactions short, and never make network calls inside them.
- Pool size. Pool configuration is set differently depending on your Prisma version (connection string parameters in some versions, driver or adapter options in newer setups). Check the current documentation and size the pool deliberately; a larger pool is not automatically faster.
Problem 6: Slow or oversized transactions
Prisma offers two styles. Use the right one:
// Batch transaction: a fixed list of independent operations, executed togetherconst [user, audit] = await prisma.$transaction([ prisma.user.update({ where: { id }, data: { credits: { decrement: 10 } } }), prisma.auditLog.create({ data: { userId: id, action: "SPEND_CREDITS" } }),]);// Interactive transaction: logic between queries. Keep it short.await prisma.$transaction( async (tx) => { const account = await tx.account.findUniqueOrThrow({ where: { id } }); if (account.balance < amount) throw new Error("Insufficient funds"); await tx.account.update({ where: { id }, data: { balance: { decrement: amount } } }); }, { maxWait: 2000, timeout: 5000 },);Interactive transactions hold a connection open while your code runs. Avoid HTTP calls, file operations or slow computation inside them. Use atomic operators (increment, decrement) instead of read-modify-write cycles where possible, and prefer a single updateMany with a condition over a read followed by a write.
Problem 7: Bulk operations done one row at a time
// Slow: one insert per iterationfor (const row of rows) await prisma.event.create({ data: row });// Fast: one batched insertawait prisma.event.createMany({ data: rows, skipDuplicates: true });For very large imports, process in chunks (for example 1,000 rows at a time) to keep statements and memory bounded.
When to use raw SQL
Use raw queries when you have measured that the generated SQL is the bottleneck, or when you need database features the client does not express (window functions, complex aggregations). Always use the parameterized tagged-template form:
const rows = await prisma.$queryRaw<{ day: Date; total: bigint }[]>` SELECT date_trunc('day', "createdAt") AS day, count(*) AS total FROM "Order" WHERE "customerId" = ${customerId} GROUP BY 1 ORDER BY 1 DESC LIMIT 30`;Never build SQL by concatenating user input into a string. Note that counts may come back as bigint, which JSON cannot serialize directly, so convert before returning them.
Common mistakes
- Querying inside loops.
- Returning whole models to the client when a few fields are needed.
- Forgetting indexes for filters and sorts.
- Creating
PrismaClientin many places. - Holding interactive transactions open across slow operations.
- Using
skipfor deep pagination. - Optimizing without reading the generated SQL.
Testing and validation
- Add a test that counts queries for critical endpoints (using the query log event) and fails if the count grows unexpectedly. This catches N+1 regressions in CI.
- Compare
EXPLAIN ANALYZEoutput for the logged SQL before and after adding an index. - Load-test the endpoint with realistic data volume, since performance on a tiny local database proves little.
Production considerations
Keep query logging for slow queries enabled in production (with a threshold) and ship it to your logs. Monitor connection counts on the database, set sensible statement timeouts, and review new migrations for locking behavior before applying them to large tables.
Best practices
- Read the SQL. Log queries and review them for new endpoints.
- Use
selectandtakeby default. - Index what you filter, join and sort by.
- Share one client per process.
- Keep transactions short and avoid I/O inside them.
- Prefer cursor pagination and batched writes.
Conclusion
Most Prisma performance problems are not Prisma problems; they are query-shape problems that the ORM makes easy to write by accident. Turn on query logging, hunt for N+1 patterns and over-fetching, add the indexes your queries need, and keep connections and transactions under control. Once you can see the SQL, the fixes are usually small.
Frequently asked questions
+What is the N+1 problem in Prisma?
It happens when you load a list with one query and then run an extra query per item to fetch related data, producing N+1 queries. Fix it by loading relations together with include or select, or by fetching related rows in one batched query with an in filter.
+Should I use include or select?
Use select when you only need some fields; it returns less data and is usually faster. Use include when you want all scalar fields of the model plus related records. You cannot use both at the same level of a query.
+How do I see the SQL Prisma generates?
Enable query logging when you create the client (the log option), or set it to emit query events and print the query text and duration. Reading the actual SQL is the fastest way to spot over-fetching and N+1 patterns.
+Why do I get 'Timed out fetching a new connection from the connection pool'?
All pooled connections are busy. Typical causes are long-running queries or transactions, too small a pool, too many application instances for the database's connection limit, or leaked work. Reduce query time, tune pool settings for your Prisma version, or use a connection pooler.
+When should I drop to raw SQL?
When a query is hard to express in the Prisma Client API, such as complex aggregations, window functions or database-specific features, and you have measured that the generated query is the bottleneck. Use parameterized $queryRaw to stay safe from SQL injection.
+Do I need to create indexes in Prisma?
Yes. Prisma does not guess indexes for your filters. Add @@index (or @unique) to the Prisma schema for columns you filter, join and sort by, then run a migration.
+How should I instantiate PrismaClient in Next.js or serverless?
Create one shared instance per process (for example stored on globalThis in development to survive hot reloads) so you do not open a new connection pool on every request or reload.