Exercise 2: "Too Many Connections" on Serverless — Possible Solution ====================================================================== Diagnosis: Each serverless instance creates its own PrismaClient, and each client has its own connection pool. In testing there are only a handful of instances, so the total stays small. During a spike the platform starts many instances at once: 200 instances x pool of 10 = up to 2,000 connections against a database that allows perhaps 100. New connections are refused and requests fail. It can be even worse if the client is created INSIDE the handler, because then every invocation opens a new pool. Fixes, in order of preference: 1. Create the client outside the handler (once per instance), so warm instances reuse it instead of opening new connections per request. 2. Set the pool size to 1 per instance on the adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL, max: 1 }) This caps connections at one per instance. Only increase it if a single request genuinely runs queries in parallel. 3. Put an external connection pooler between the functions and the database (PgBouncer, your cloud provider's pooler, or a hosted option such as Prisma Accelerate). Hundreds of functions share a small, fixed number of real database connections. Point the app at the pooler (DATABASE_URL) and migrations at the database (DIRECT_URL). 4. Limit concurrency on the platform (a maximum number of instances) so it can't scale past what the database can handle. 5. Reduce database work per request (Chapter 7: fewer queries, less data, caching), so each connection is held for less time. WHY THIS WORKS AS AN ANSWER ------------------------------ It explains why the failure only appears under load — connections multiply with instances, which testing never creates — and orders the fixes from cheapest and most certain (code changes) to those needing new infrastructure. It also connects back to Chapter 7: in every deployment model, total connections are pool size multiplied by every process that holds a pool.