Database Connection and Connection Pools
Connecting Prisma to your database requires writing a database connection URL and configuring connection pools. Let us explore connection setups for postgresql and mysql.
1. Database Connection URL Formatting
Your database connection URL is defined in the .env file. The format varies depending on your database engine:
PostgreSQL Connection String
DATABASE_URL="postgresql://username:password@host:port/database_name?schema=public"- host: The server IP address or domain name (such as localhost or a cloud server endpoint).
- port: PostgreSQL defaults to 5432.
- schema: The target database schema (defaults to public).
MySQL Connection String
DATABASE_URL="mysql://username:password@host:port/database_name"- port: MySQL defaults to 3306.
2. Managing Connection Pooling
By default, Prisma Client maintains a local database connection pool. This pool keeps a set of database connections open and ready to use, which is much faster than opening a new connection for every request.
You can configure the pool size by appending the connection_limit parameter to your connection URL:
# Limit the pool size to a maximum of 20 concurrent connections
DATABASE_URL="postgresql://username:password@localhost:5432/mydb?connection_limit=20"The optimal pool size depends on:
- The maximum connections allowed by your database server.
- The number of application server instances running.
3. Connection Pooling in Serverless Environments
In serverless architectures (like Vercel, AWS Lambda, or Netlify Functions), functions scale dynamically on demand. If 100 functions spin up simultaneously, they can easily exhaust your database connection limits.
To address this, serverless environments should route requests through a connection proxy (such as Prisma Accelerate, PgBouncer, or Supabase Connection Pooler) to manage database connections efficiently.