You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Timescaledb连接报错:剩余连接槽保留给超级用户角色,求解决方案

问题

尝试连接带会话级连接池的TimescaleDB时,持续收到错误:

FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute

我查了资料,但对node-postgres的Pool用法感到困惑,当前连接代码如下:

import type { Connection } from './postgres.connection';
import type { Options } from 'postgres';
import postgres from 'postgres';

export const timescaleConnection = async <T extends Connection = Connection>(
  options?: Options<T>,
) => {
  const databaseUrl = process.env['TIMESCALE_DATABASE_URL'] ?? '';
  return postgres<T>(databaseUrl, {
    idle_timeout: 20, // 20 seconds
    ...options,
  });
};

请问应该用Pool还是其他配置方法解决这个问题?

解决方案

首先明确:你当前用的是postgres.js库(不是传统的pg包),它的postgres()函数本身就会创建并返回一个连接池,不需要额外使用Pool类。你的问题核心是重复创建了多个连接池实例,导致总连接数超出PostgreSQL的max_connections限制,普通用户的连接槽耗尽后,剩下的都留给超级用户,就触发了这个错误。

1. 改为单例连接池

确保整个应用生命周期内只创建一个连接池实例,避免重复创建:

import type { Connection } from './postgres.connection';
import type { Options } from 'postgres';
import postgres from 'postgres';

// 缓存单例连接池
let pool: ReturnType<typeof postgres<Connection>> | null = null;

export const timescaleConnection = async <T extends Connection = Connection>(
  options?: Options<T>,
) => {
  if (!pool) {
    const databaseUrl = process.env['TIMESCALE_DATABASE_URL'] ?? '';
    pool = postgres<T>(databaseUrl, {
      idle_timeout: 20, // 20秒
      max: 10, // 关键:限制池的最大连接数,根据你的数据库配置调整
      ...options,
    });
  }
  return pool;
};

2. 关键配置说明

  • max参数:设置连接池允许的最大连接数,必须小于PostgreSQL的max_connections减去superuser_reserved_connections(默认是3)。比如数据库默认max_connections是100,那max设为95左右比较合理,避免占满所有连接槽。
  • 检查应用其他代码:确认没有其他地方直接创建数据库连接,导致总连接数超标。
  • 排查当前连接数:可以在PostgreSQL中执行SELECT count(*) FROM pg_stat_activity;,查看当前所有活跃连接,定位是否有其他进程在占用连接。

3. 数据库层面的补充调整

如果应用确实需要更多连接,可以修改PostgreSQL的配置文件(postgresql.conf):

  • 增大max_connections:注意这个参数会消耗更多内存,需根据服务器配置调整。
  • 调整superuser_reserved_connections:如果不需要预留太多给超级用户,可以适当减小这个值,但不建议设为0。

内容的提问来源于stack exchange,提问作者PlayMa256

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:23:23