Overview

Prisma Client connects and disconnects from your data sources using the following two methods:

  • connect(): Promise<void>
  • disconnect(): Promise<void>

Unless you want to employ a specific optimization, calling prisma.connect() is not necessary thanks to the lazy connect behavior: The PrismaClient instance connects lazily when the first request is made to the API (connect() is called for you under the hood).

If you need the first request to respond instantly and can't wait for the lazy connection to be established, you can explicitly call prisma.connect() to establish a connection to the Prisma data source:

const prisma = new PrismaClient()
// run inside `async` function
await prisma.connect()

Note: When deploying your application as a long-running process or when running a Node.js script that uses Prisma Client, it's recommended to always explicitly call prisma.disconnect() in your code even when an exception is thrown as shown below. Otherwise, the Node.js process will not exit automatically.

In serverless environments, there are nuances that make it sensible to reuse database connections, i.e. not call disconnect(). The deployment docs cover those cases in more detail.

Calling disconnect explicitly

main()
.catch(e => {
throw e
})
.finally(async () => {
await prisma.disconnect()
})

connect

The connect method establishes a physical connection to the database via Prisma's query engine.

Note that connect returns a Promise, so you shsould call it inside an async function with the await keyword.

disconnect

The disconnect method closes the database connections that were established when connect was called and stops the process that was running Prisma's query engine.

Note that connect returns a Promise, so you should call it inside an async function with the await keyword.

Connection pool

Once connect was called, the query engine immediately creates a connection pool with the amount of connections that were specified as the connection_limit parameter on your database connection URL.

For example, with the following datasource configuration in your Prisma schema the connection pool will have exactly five connections:

datasource postgresql {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?connection_limit=5"
}

If the connection_limit argument is omitted, the default number of connections is calculated according to this formula: num_physical_cpus * 2 + 1 where num_physical_cpus represents the number of physical CPUs on your machine.

datasource postgresql {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb"
}

If your machine four physical CPUs, your connection pool will contain nine connections (4 * 2 + 1 = 9).

Edit this page on Github