GrepBoard/매뉴얼
605 편 ·

PostgreSQL too many clients already 해결

·시험 환경 PostgreSQL 17.11 (Docker postgres:17) · 2026-10·시험 범위 ↓·6 단계

PostgreSQL sorry, too many clients already 는 연결 자리가 다 찬 것입니다. 예약 자리로 들어가 pg_stat_activity 로 새는 연결을 끊고 시간 제한을 겁니다.

output
psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  sorry, too many clients already

서버의 연결 자리(max_connections, 기본 보통 100)가 모두 쓰여 새 연결을 받을 수 없다는 뜻입니다. 대개 트래픽보다 쉬고 있는 연결·트랜잭션을 연 채 멈춘 연결이 자리를 차지하고 있습니다. 관리자 역할로 들어가 pg_stat_activity 로 누가 자리를 쥐고 있는지 보고, 끊고, 같은 일이 다시 안 생기게 시간 제한과 풀 크기를 정합니다. max_connections 를 올리는 것은 마지막이고 재시작이 필요합니다.

[1] 문구로 어디까지 찼는지 가립니다. 일반 역할은 이 문구를 먼저 만납니다.

output
FATAL:  remaining connection slots are reserved for roles with the SUPERUSER attribute
문구상태
remaining connection slots are reserved for roles with the SUPERUSER attribute일반 역할 자리가 끝났고 슈퍼유저 예약 자리만 남음
sorry, too many clients already예약 자리까지 모두 참 — 슈퍼유저도 못 들어감

예약 자리 수는 superuser_reserved_connections(기본 3)입니다. 아래 시험 서버는 6개 중 2개를 예약해 일반 역할이 4개까지만 썼습니다.

console
$ psql -U postgres -c "SELECT name, setting FROM pg_settings WHERE name IN ('max_connections','superuser_reserved_connections','reserved_connections')"              name              | setting --------------------------------+--------- max_connections                | 6 reserved_connections           | 0 superuser_reserved_connections | 2(3 rows)

[2] 예약 자리가 남아 있을 때 슈퍼유저로 들어갑니다. sorry, too many clients already 까지 갔다면 관리자도 막히니, 연결을 쥔 애플리케이션 하나를 내리거나 잠시 기다려 자리를 만듭니다.

console
$ psql -U postgres -c 'SELECT 1'psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  sorry, too many clients already$ psql -U postgres -Atc 'SELECT 1'1

두 번째 명령은 슈퍼유저 연결 하나가 끝난 뒤입니다. 애플리케이션이 슈퍼유저로 접속하고 있으면 예약 자리도 그 애플리케이션이 다 써 버립니다. 애플리케이션 계정은 일반 역할로 둡니다.

[3] 누가 자리를 쥐고 있는지 봅니다. 역할·상태별로 세고, 가장 오래된 것을 봅니다.

console
$ psql -U postgres -c "SELECT usename, state, count(*), max(now() - state_change) AS longest FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY 1, 2 ORDER BY 3 DESC" usename  |        state        | count |     longest      ----------+---------------------+-------+------------------ appuser  | idle                |     2 | 00:00:20.000401 appuser  | active              |     1 | 00:00:19.724808 appuser  | idle in transaction |     1 | 00:00:19.814797 postgres | active              |     1 | -00:00:00.000002 postgres | idle                |     1 | 00:00:17.397643(5 rows)
state뜻
active질의를 실행 중
idle연결만 열어 두고 쉼 — 풀이 쥐고 있거나 닫지 않고 버린 연결
idle in transactionBEGIN 뒤 커밋·롤백 없이 멈춤 — 자리와 함께 잠금도 쥘 수 있음

postgres | active 한 줄은 지금 이 질의를 돌리는 내 세션입니다. idle in transaction 은 어디서 왔는지까지 봅니다.

console
$ psql -U postgres -c "SELECT pid, usename, application_name, client_addr, state, now() - xact_start AS xact_age, left(query, 40) AS query FROM pg_stat_activity WHERE state = 'idle in transaction'" pid | usename | application_name | client_addr |        state        |    xact_age     |   query   -----+---------+------------------+-------------+---------------------+-----------------+----------- 143 | appuser | psql             |             | idle in transaction | 00:00:19.934335 | SELECT 1;(1 row)

query 는 그 세션이 마지막으로 실행한 질의라, 커밋을 빠뜨린 코드 위치를 찾는 단서가 됩니다. client_addr 가 비어 있으면 소켓 접속입니다.

[4] 문제 연결을 PID 하나씩 끊습니다. pg_terminate_backend(<pid>) 는 그 세션의 트랜잭션을 롤백하고 연결을 닫습니다.

아래는 같은 조건(자리 6 · 예약 2)으로 다시 띄운 시험 서버라 PID 가 [3] 과 다릅니다.

console
$ psql -U postgres -c "SELECT pid, usename, datname, application_name, state, now() - state_change AS idle_for FROM pg_stat_activity WHERE state = 'idle in transaction'" pid | usename | datname  | application_name |        state        |    idle_for     -----+---------+----------+------------------+---------------------+----------------- 118 | appuser | postgres | psql             | idle in transaction | 00:00:07.227024(1 row) $ psql -U postgres -Atc 'SELECT pg_terminate_backend(118)'t$ psql -U appuser -d postgres -Atc 'SELECT current_user'psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  remaining connection slots are reserved for roles with the SUPERUSER attribute

하나를 끊었는데도 일반 역할이 아직 못 들어옵니다. 남은 빈자리 2개가 예약 자리 수(2)와 같아서입니다. 슈퍼유저 세션도 일반 자리를 같이 씁니다. 쉬고 있던 슈퍼유저 연결도 같은 방법으로 확인해 끊자 들어왔습니다.

console
$ psql -U postgres -c "SELECT pid, usename, application_name, state, now() - state_change AS idle_for FROM pg_stat_activity WHERE usename = 'postgres' AND state = 'idle' AND pid <> pg_backend_pid()" pid | usename  | application_name | state |    idle_for    -----+----------+------------------+-------+---------------- 135 | postgres | psql             | idle  | 00:00:05.52707(1 row) $ psql -U postgres -Atc 'SELECT pg_terminate_backend(135)'t$ psql -U appuser -d postgres -Atc 'SELECT current_user'appuser

실제 서버에서는 조회에 시간 조건(now() - state_change > interval '10 minutes' 등)과 usename·datname·application_name 을 더해 후보를 좁히고, 고른 PID 만 끊습니다.

[5] 같은 일이 반복되지 않게 시간 제한을 겁니다. idle_in_transaction_session_timeout 은 트랜잭션을 연 채 정한 시간 이상 쉬면 서버가 연결을 끊습니다. 역할 단위로 걸 수 있습니다.

console
$ psql -U postgres -c "ALTER ROLE appuser SET idle_in_transaction_session_timeout = '3s'"ALTER ROLE$ (echo 'BEGIN;'; echo 'SELECT 1;'; sleep 5; echo 'SELECT 2;') | psql -U appuser -d postgresBEGIN ?column? ----------        1(1 row) FATAL:  terminating connection due to idle-in-transaction timeoutserver closed the connection unexpectedly	This probably means the server terminated abnormally	before or while processing the request.connection to server was lost

실제로는 가장 긴 정상 트랜잭션보다 넉넉하게(분 단위) 잡습니다. 새로 건 설정을 되돌릴 때는 RESET 합니다. ALTER ROLE 문서대로 역할 설정은 그 뒤에 시작하는 세션의 기본값이 되므로, 걸 때도 되돌릴 때도 새로 맺는 연결부터 바뀝니다. 아래는 다시 띄운 시험 서버의 결과입니다.

console
$ psql -U postgres -Atc "SELECT rolconfig FROM pg_roles WHERE rolname = 'appuser'"{idle_in_transaction_session_timeout=3s}$ psql -U postgres -c 'ALTER ROLE appuser RESET idle_in_transaction_session_timeout'ALTER ROLE$ psql -U postgres -Atc "SELECT coalesce(rolconfig::text, '(none)') FROM pg_roles WHERE rolname = 'appuser'"(none)

원래 다른 값이 있었다면 RESET 대신 적어 둔 값으로 다시 SET 합니다. 그냥 쉬는 연결은 idle_session_timeout 으로 끊을 수 있지만, 커넥션 풀이 쥐고 있는 연결까지 끊기니 풀 쪽 유휴 제한을 먼저 맞춥니다.

[6] 애플리케이션 쪽 연결 수를 셉니다. 「서버 수 × 프로세스 수 × 풀 크기」가 max_connections 에서 예약 자리를 뺀 값보다 작아야 합니다. 앱 인스턴스가 늘어나면 풀 크기를 줄이거나 커넥션 풀러(PgBouncer 등)를 앞에 둡니다.

그래도 늘려야 하면 max_connections 를 바꾸고 재시작합니다. 공식 문서대로 이 값은 서버 시작 때만 정해져, 다시 읽기(reload)로는 적용되지 않습니다.

console
$ psql -U postgres -c 'ALTER SYSTEM SET max_connections = 20' -c 'SELECT pg_reload_conf()' -c "SELECT name, setting, pending_restart FROM pg_settings WHERE name = 'max_connections'"ALTER SYSTEM pg_reload_conf ---------------- t(1 row)       name       | setting | pending_restart -----------------+---------+----------------- max_connections | 6       | f(1 row)

setting 은 그대로 6 이고, 이 시험에서는 pending_restart 도 f 였습니다. 시험 서버를 -c max_connections=6 시작 옵션으로 띄웠기 때문으로 보입니다 — 공식 문서상 명령 줄 옵션은 postgresql.conf·ALTER SYSTEM 보다 우선하므로, 파일 쪽 값이 바뀌어도 재시작 뒤 적용될 값은 여전히 6 입니다. 설정 파일로만 정한 보통 서버라면 pending_restart 는 「설정 파일에서 값이 바뀌었지만 재시작해야 반영되는」 경우 t 가 된다고 문서가 설명합니다(이 경우는 시험하지 않았습니다). 시작 옵션으로 값을 주는 서버(일부 컨테이너·서비스 정의)는 그 옵션을 고쳐야 합니다.

연결마다 서버 프로세스와 메모리가 붙으므로 크게 올리기 전에 work_mem 등과 함께 메모리를 계산합니다. 되돌리려면 ALTER SYSTEM RESET max_connections 후 재시작합니다. PostgreSQL 16 부터는 reserved_connections 로 pg_use_reserved_connections 역할을 받은 모니터링·운영 계정에 자리를 따로 남겨 둘 수도 있습니다(이것도 재시작 필요). MySQL 에서 같은 일이 나면 MySQL ERROR 1040 Too many connections 해결을 봅니다.

연결 수를 늘리면서 메모리를 어떻게 나눌지는 PostgreSQL shared_buffers work_mem 튜닝에, 오래 열린 트랜잭션 때문에 죽은 행이 쌓이는 문제는 PostgreSQL autovacuum 튜닝과 n_dead_tup 보기에 있습니다.

공식 근거: Connection settings — max_connections · reserved_connections · superuser_reserved_connections · pg_stat_activity · pg_terminate_backend · idle_in_transaction_session_timeout · idle_session_timeout

#postgresql#max_connections#pg_stat_activity#connection-pool