Skip to main content

连接池

快速概览

本页解释了 Prisma ORM 如何使用连接池管理数据库连接,以及如何配置连接数限制和超时时间以获得最佳性能。

¥This page explains how Prisma ORM manages database connections using a connection pool, and how you can configure limits and timeouts for optimal performance.

查询引擎管理数据库连接的连接池。当 Prisma 客户端打开与数据库的第一个连接时,会创建该池,这可以通过以下两种方式之一发生:

¥The query engine manages a connection pool of database connections. The pool is created when Prisma Client opens the first connection to the database, which can happen in one of two ways:

关系数据库连接器使用 Prisma ORM 自己的连接池,MongoDB 连接器使用 MongoDB 驱动连接池

¥Relational database connectors use Prisma ORM's own connection pool, and the MongoDB connectors uses the MongoDB driver connection pool.

Questions answered in this page
  • 如何调整 Prisma 连接池的大小?

    ¥How do I size Prisma's connection pool?

  • 如何设置池超时和限制?

    ¥How do I set pool timeouts and limits?

  • 我应该何时将 PgBouncer 与 Prisma 一起使用?

    ¥When should I use PgBouncer with Prisma?

关系数据库

¥Relational databases

从 Prisma ORM v7 开始,关系数据源默认使用 驱动适配器 实例化 Prisma 客户端。驱动程序适配器依赖于你提供的 Node.js 驱动程序,因此连接池默认值(和配置)现在来自驱动程序本身。

¥Starting with Prisma ORM v7, relational datasources instantiate Prisma Client with driver adapters by default. Driver adapters rely on the Node.js driver you supply, so connection pooling defaults (and configuration) now come from the driver itself.

使用下表将 Prisma ORM v6 连接 URL 参数转换为 Prisma ORM v7 驱动程序适配器字段及其默认值。

¥Use the tables below to translate Prisma ORM v6 connection URL parameters to the Prisma ORM v7 driver adapter fields alongside their defaults.

Prisma ORM v7 驱动程序适配器默认值

¥Prisma ORM v7 driver adapter defaults

下表记录了每个驱动程序适配器的默认连接池设置。

¥The following tables document the default connection pool settings for each driver adapter.

Prisma 超时

Prisma ORM 拥有独立于数据库驱动程序超时的可配置超时机制。如果你看到超时错误,并且不确定错误是来自驱动程序还是 Prisma Client,请参阅 Prisma 客户端超时和事务选项文档

¥Prisma ORM also has its own configurable timeouts that are separate from the database driver timeouts. If you see a timeout error and are unsure whether it comes from the driver or from Prisma Client, see the Prisma Client timeouts and transaction options documentation.

PostgreSQL(使用 pg 驱动程序)适配器)

¥PostgreSQL (using the pg driver adapter)

以下是 pg 驱动程序适配器的默认连接池设置:

¥Here are the default connection pool settings for the pg driver adapter:

行为v6 URL 参数v6 默认值v7 pg 配置字段v7 默认值
连接池大小connection_limitnum_cpus::get_physical() * 2 + 1max10
获取超时pool_timeout10sconnectionTimeoutMillis0(无超时)
连接超时connect_timeout5sconnectionTimeoutMillis0(无超时)
空闲超时max_idle_connection_lifetime300sidleTimeoutMillis10s
连接生命周期max_connection_lifetime0(无超时)maxLifetimeSeconds0(无超时)
Example: Matching Prisma ORM v6 defaults with the pg driver adapter

如果你希望保留与 Prisma ORM v6 中相同的超时行为,请在实例化驱动程序适配器时传递以下配置:

¥If you want to preserve the same timeout behavior you had in Prisma ORM v6, pass the following configuration when instantiating the driver adapter:

import { PrismaPg } from '@prisma/adapter-pg'

const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
// Match Prisma ORM v6 defaults:
connectionTimeoutMillis: 5_000, // v6 connect_timeout was 5s
idleTimeoutMillis: 300_000, // v6 max_idle_connection_lifetime was 300s
})
提示

有关每个可用选项的详细信息,请参阅 node-postgres 连接池文档

¥See the node-postgres pool documentation for details on every available option.

MySQL 或 MariaDB(使用 mariadb 驱动程序)

¥MySQL or MariaDB (using the mariadb driver)

以下是 mariadb 驱动程序适配器的默认连接池设置:

¥Here are the default connection pool settings for the mariadb driver adapter:

行为v6 URL 参数v6 默认值v7 mariadb 配置字段v7 默认值
连接池大小connection_limitnum_cpus::get_physical() * 2 + 1connectionLimit10
获取超时pool_timeout10sacquireTimeout10s
连接超时connect_timeout5sconnectTimeout1s
空闲超时max_idle_connection_lifetime300sidleTimeout1800s
Example: Matching Prisma ORM v6 defaults with the mariadb driver adapter

如果你希望保留与 Prisma ORM v6 中相同的超时行为,请在实例化驱动程序适配器时传递以下配置:

¥If you want to preserve the same timeout behavior you had in Prisma ORM v6, pass the following configuration when instantiating the driver adapter:

import { PrismaMariaDb } from '@prisma/adapter-mariadb'

const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
// Match Prisma ORM v6 defaults:
connectTimeout: 5_000, // v6 connect_timeout was 5s
idleTimeout: 300, // v6 max_idle_connection_lifetime was 300s (note: in seconds, not ms)
})
提示

有关配置和调优指南,请参阅 MariaDB 连接器/Node.js 连接池选项

¥Refer to the MariaDB Connector/Node.js pool options for configuration and tuning guidance.

SQL Server(使用 mssql 驱动程序)

¥SQL Server (using the mssql driver)

以下是 mssql 驱动程序适配器的默认连接池设置:

¥Here are the default connection pool settings for the mssql driver adapter:

行为v6 URL 参数v6 默认值v7 mssql 配置字段v7 默认值
连接池大小connection_limitnum_cpus::get_physical() * 2 + 1pool.max10
连接超时connect_timeout5sconnectionTimeout15s
空闲超时max_idle_connection_lifetime300spool.idleTimeoutMillis30s
Example: Matching Prisma ORM v6 defaults with the mssql driver adapter

如果你希望保留与 Prisma ORM v6 中相同的超时行为,请在实例化驱动程序适配器时传递以下配置:

¥If you want to preserve the same timeout behavior you had in Prisma ORM v6, pass the following configuration when instantiating the driver adapter:

import { PrismaMssql } from '@prisma/adapter-mssql'

const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
// Match Prisma ORM v6 defaults:
connectionTimeout: 5_000, // v6 connect_timeout was 5s
pool: {
idleTimeoutMillis: 300_000, // v6 max_idle_connection_lifetime was 300s
},
})
提示

有关这些字段的详细信息,请参阅 node-mssql 连接池文档

¥See the node-mssql pool docs for details on these fields.

MongoDB

MongoDB 连接器不使用 Prisma ORM 连接池。连接池由 MongoDB 驱动程序和 通过连接字符串参数配置 进行内部管理。

¥The MongoDB connector does not use the Prisma ORM connection pool. The connection pool is managed internally by the MongoDB driver and configured via connection string parameters.

外部连接池

¥External connection poolers

你不能将 connection_limit 增加到超出底层数据库可以支持的范围。这在无服务器环境中是一个特殊的挑战,其中每个功能都管理 PrismaClient 的一个实例 - 以及它自己的连接池。

¥You cannot increase the connection_limit beyond what the underlying database can support. This is a particular challenge in serverless environments, where each function manages an instance of PrismaClient - and its own connection pool.

考虑引入 外部连接池,例如 PgBouncer 以防止你的应用或函数耗尽数据库连接限制。

¥Consider introducing an external connection pooler like PgBouncer to prevent your application or functions from exhausting the database connection limit.

手动数据库连接处理

¥Manual database connection handling

使用 Prisma ORM 时,数据库连接在 engine 级别上处理。这意味着它们不会向开发者公开,并且无法手动访问它们。

¥When using Prisma ORM, the database connections are handled on an engine-level. This means they're not exposed to the developer and it's not possible to manually access them.

Prisma ORM v6 及更早版本

¥Prisma ORM v6 and before

连接池的工作原理

¥How the connection pool works

以下步骤描述了查询引擎如何使用连接池:

¥The following steps describe how the query engine uses the connection pool:

  1. 查询引擎用 可配置池大小池超时 实例化一个连接池。

    ¥The query engine instantiates a connection pool with a configurable pool size and pool timeout.

  2. 查询引擎创建一个连接并将其添加到连接池中。

    ¥The query engine creates one connection and adds it to the connection pool.

  3. 当查询到来时,查询引擎会从池中保留一个连接来处理查询。

    ¥When a query comes in, the query engine reserves a connection from the pool to process query.

  4. 如果连接池中没有可用的空闲连接,则查询引擎会打开额外的数据库连接并将其添加到连接池中,直到数据库连接数达到 connection_limit 定义的限制。

    ¥If there are no idle connections available in the connection pool, the query engine opens additional database connections and adds them to the connection pool until the number of database connections reaches the limit defined by connection_limit.

  5. 如果查询引擎无法从池中保留连接,查询将添加到内存中的 FIFO(先进先出)队列中。FIFO 意味着查询按照进入队列的顺序进行处理。

    ¥If the query engine cannot reserve a connection from the pool, queries are added to a FIFO (First In First Out) queue in memory. FIFO means that queries are processed in the order they enter the queue.

  6. 如果查询引擎无法在 时限 之前处理队列中的查询,则会针对该查询引发错误代码为 P2024 的异常,并继续处理队列中的下一个查询。

    ¥If the query engine cannot process a query in the queue for before the time limit, it throws an exception with error code P2024 for that query and moves on to the next one in the queue.

如果你持续遇到池超时错误,则需要 优化连接池

¥If you consistently experience pool timeout errors, you need to optimize the connection pool .

连接池大小

¥Connection pool size

默认连接池大小

¥Default connection pool size

默认连接数(池大小)通过以下公式计算:

¥The default number of connections (pool size) is calculated with the following formula:

num_physical_cpus * 2 + 1

num_physical_cpus 代表运行应用的计算机上的物理 CPU 数量。如果你的计算机有四个物理 CPU,则你的连接池将包含 9 个连接 (4 * 2 + 1 = 9)。

¥num_physical_cpus represents the number of physical CPUs on the machine your application is running on. If your machine has four physical CPUs, your connection pool will contain nine connections (4 * 2 + 1 = 9).

尽管该公式代表了一个良好的起点,但 建议的连接限制 还取决于你的部署范例 - 特别是如果你使用无服务器。

¥Although the formula represents a good starting point, the recommended connection limit also depends on your deployment paradigm - particularly if you are using serverless.

设置连接池大小

¥Setting the connection pool size

你可以通过在数据库连接 URL 中显式设置 connection_limit 参数来指定连接数。例如,通过 Prisma 架构 中的以下 datasource 配置,连接池将恰好有 5 个连接:

¥You can specify the number of connections by explicitly setting the connection_limit parameter in your database connection URL. For example, with the following datasource configuration in your Prisma schema the connection pool will have exactly five connections:

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

查看连接池大小

¥Viewing the connection pool size

Prisma Client 使用的连接数可以通过 logging 和所用驱动程序适配器提供的内置 API 查看。

¥The number of connections Prisma Client uses can be viewed using logging and built-in APIs provided by the driver adapter being used.

使用 info 记录级别,你可以记录 Prisma 客户端实例化时打开的连接池中的连接数。

¥Using the info logging level, you can log the number of connections in a connection pool that are opened when Prisma Client is instantiated.

例如,考虑以下 Prisma 客户端实例和调用:

¥For example, consider the following Prisma Client instance and invocation:

import { PrismaClient } from '../prisma/generated/client'

const prisma = new PrismaClient({
log: ['info'],
})

async function main() {
await prisma.user.findMany()
}

main()
Show CLI results
prisma:info Starting a postgresql pool with 21 connections.

当实例化 PrismaClient 类时,日志记录通知 stdout 启动了一个具有 21 个连接的连接池。

¥When the PrismaClient class was instantiated, the logging notified stdout that a connection pool with 21 connections was started.

警告

请注意,log: ['info'] 生成的输出可能会在任何版本中发生更改,恕不另行通知。如果你依赖应用或正在构建的工具中的输出,请注意这一点。

¥Note that the output generated by log: ['info'] can change in any release without notice. Be aware of this in case you are relying on the output in your application or a tool that you're building.

如果你需要更多地了解连接池的大小以及使用中和空闲连接的数量,你可以使用 metrics 功能(当前处于预览版)。

¥If you need even more insights into the size of your connection pool and the amount of in-use and idle connection, you can use the metrics feature (which is currently in Preview).

考虑以下示例:

¥Consider the following example:

import { PrismaClient } from '../prisma/generated/client'

const prisma = new PrismaClient()

async function main() {
await Promise.all([prisma.user.findMany(), prisma.post.findMany()])

const metrics = await prisma.$metrics.json()
console.dir(metrics, { depth: Infinity })
}

main()
Show CLI results
{
"counters": [
// ...
{
"key": "prisma_pool_connections_open",
"labels": {},
"value": 2,
"description": "Number of currently open Pool Connections"
}
],
"gauges": [
// ...
{
"key": "prisma_pool_connections_busy",
"labels": {},
"value": 0,
"description": "Number of currently busy Pool Connections (executing a datasource query)"
},
{
"key": "prisma_pool_connections_idle",
"labels": {},
"value": 21,
"description": "Number of currently unused Pool Connections (waiting for the next datasource query to run)"
},
{
"key": "prisma_pool_connections_opened_total",
"labels": {},
"value": 2,
"description": "Total number of Pool Connections opened"
}
],
"histograms": [
/** ... **/
]
}
信息

有关指标输出中可用内容的更多详细信息,请参阅 关于指标 部分。

¥For more details on what is available in the metrics output, see the About metrics section.

连接池超时

¥Connection pool timeout

默认池超时

¥Default pool timeout

默认连接池超时时间为 10 秒。如果查询引擎在这段时间内没有从数据库连接池获取连接,它将引发异常并继续执行队列中的下一个查询。

¥The default connection pool timeout is 10 seconds. If the Query Engine does not get a connection from the database connection pool within that time, it throws an exception and moves on to the next query in the queue.

设置连接池超时时间

¥Setting the connection pool timeout

你可以通过在数据库连接 URL 中显式设置 pool_timeout 参数来指定池超时。在以下示例中,池在 2 秒后超时:

¥You can specify the pool timeout by explicitly setting the pool_timeout parameter in your database connection URL. In the following example, the pool times out after 2 seconds:

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

禁用连接池超时

¥Disabling the connection pool timeout

你可以通过将 pool_timeout 参数设置为 0 来禁用连接池超时:

¥You disable the connection pool timeout by setting the pool_timeout parameter to 0:

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

你可以选择 如果查询必须保留在队列中,请禁用连接池超时 - 例如,如果你正在并行导入大量记录,并且确信队列不会在作业完成之前耗尽所有可用 RAM。

¥You can choose to disable the connection pool timeout if queries must remain in the queue - for example, if you are importing a large number of records in parallel and are confident that the queue will not use up all available RAM before the job is complete.