MySQL ERROR 1040 Too many connections 해결
MySQL ERROR 1040 Too many connections 는 연결이 max_connections 에 닿았다는 뜻입니다. 남겨 둔 관리자 자리로 들어가 새는 연결을 찾아 끊고 한도를 맞춥니다.
ERROR 1040 (08004): Too many connections연결 수가 max_connections(8.4 기본값 151)에 닿아 서버가 새 연결을 받지 않는다는 뜻입니다. 대개 앱이 연결을 닫지 않고 쌓아 두는 것이 원인이므로, 먼저 관리자로 들어가 누가 연결을 잡고 있는지 보고, 끊은 뒤에 한도를 손봅니다. 한도만 올리면 같은 일이 조금 늦게 다시 납니다.
같은 오류가 ERROR 1040 (HY000): Too many connections 로도 찍힙니다. 시험에서는 일반 계정이 막힐 때 08004, 관리자 몫까지 찬 뒤에 막힐 때 HY000 이 나왔습니다. 오류 참조 문서의 SQLSTATE 는 08004 입니다.
[1] 관리자 계정으로 접속해 봅니다. mysqld 는 max_connections + 1 개까지 받고, 그 한 자리는 CONNECTION_ADMIN(또는 옛 SUPER) 권한 계정 몫입니다(Too many connections). 아래는 max_connections=5 에 앱 연결 5개가 쉬고 있는 상태입니다.
$ mysql -h 127.0.0.1 -uapp -p'<비밀번호>' appdb -e "SELECT 1;"mysql: [Warning] Using a password on the command line interface can be insecure.ERROR 1040 (08004): Too many connections$ mysql -uroot -p'<비밀번호>' -e "SELECT CURRENT_USER();"mysql: [Warning] Using a password on the command line interface can be insecure.CURRENT_USER()root@localhost$ mysql -uroot -p'<비밀번호>' -e "SELECT 1;"mysql: [Warning] Using a password on the command line interface can be insecure.ERROR 1040 (HY000): Too many connections[2] 다음 장애를 위해 관리 전용 포트를 열어 둡니다. 시작 옵션에 admin_address 를 주면 별도 주소·포트(기본 33062)에서 관리 연결을 받고, 이 인터페이스는 연결 수 제한이 없으며 SERVICE_CONNECTION_ADMIN 권한 계정만 들어옵니다(Administrative Connection Management). 시작할 때만 켜지므로 지금 막힌 서버에는 쓸 수 없고 다음 재시작부터 적용됩니다.
[mysqld]admin_address=127.0.0.1admin_port=33062시험 서버는 같은 값을 시작 옵션 --admin-address=127.0.0.1 --admin-port=33062 로 주고 띄웠고, root 몫 한 자리까지 찬 상태에서도 관리 포트로는 들어갔습니다.
$ mysql -h 127.0.0.1 -P 33062 -uroot -p'<비밀번호>' -e "SELECT CURRENT_USER(), @@admin_port;"mysql: [Warning] Using a password on the command line interface can be insecure.CURRENT_USER() @@admin_portroot@% 33062[3] 연결 수를 숫자로 확인합니다. Max_used_connections 가 max_connections 와 같거나 넘었고 Connection_errors_max_connections 가 늘고 있으면 이 오류가 실제로 난 것입니다. 이하 A 는 위 관리 포트 접속 옵션입니다.
$ A="-h 127.0.0.1 -P 33062 -uroot -p<비밀번호>"$ mysql $A -e "SHOW GLOBAL STATUS WHERE Variable_name IN ('Threads_connected','Max_used_connections','Connection_errors_max_connections');"mysql: [Warning] Using a password on the command line interface can be insecure.Variable_name ValueConnection_errors_max_connections 2Max_used_connections 7Threads_connected 7Threads_connected 7 은 앱 5 + root 1 + 지금 관리 포트로 붙은 연결 1 입니다. 관리 포트 연결은 한도 바깥에서 셉니다.
[4] 누가 연결을 잡고 있는지 계정·클라이언트 주소별로 묶어 봅니다. Sleep 이 많고 max_idle_s 가 크면 쓰지 않는 연결을 닫지 않고 있는 것입니다.
$ mysql $A -e "SELECT user, SUBSTRING_INDEX(host,':',1) AS client, command, COUNT(*) AS conns, MAX(time) AS max_idle_s FROM information_schema.processlist GROUP BY user, client, command ORDER BY conns DESC;"mysql: [Warning] Using a password on the command line interface can be insecure.user client command conns max_idle_sapp 127.0.0.1 Sleep 5 6root localhost Sleep 1 2event_scheduler localhost Daemon 1 14root 127.0.0.1 Query 1 0실제 서버에서는 client 열이 앱 서버 주소로 나뉘므로, 어느 서버의 어느 계정이 자리를 차지하는지 여기서 갈립니다. Query 가 많고 time 이 길면 새는 연결이 아니라 느린 쿼리가 줄을 선 것이니 쿼리 쪽을 봅니다.
[5] 쉬고 있는 연결을 끊어 자리를 비웁니다. 먼저 KILL 문을 만들어 눈으로 확인한 뒤 실행합니다. 진행 중인 트랜잭션이 있는 연결을 끊으면 그 트랜잭션은 롤백되므로, Sleep 이고 그 계정의 것만 고릅니다.
$ mysql $A -N -e "SELECT CONCAT('KILL ', id, ';') FROM information_schema.processlist WHERE user='app' AND command='Sleep' AND time >= 3;" 2>/dev/null > kill.sql$ cat kill.sqlKILL 11;KILL 12;KILL 13;KILL 14;KILL 15;$ mysql $A < kill.sqlmysql: [Warning] Using a password on the command line interface can be insecure.$ mysql -h 127.0.0.1 -uapp -p'<비밀번호>' appdb -e "SELECT 1 AS ok;"mysql: [Warning] Using a password on the command line interface can be insecure.ok1실제 서버에서는 time >= 3 대신 정상 요청보다 확실히 긴 값(예 300)을 씁니다. 끊어도 앱이 곧 다시 채우면 원인은 앱의 연결 풀 설정입니다. 풀 최대 크기 × 앱 서버 대수가 max_connections 를 넘지 않는지 계산합니다.
[6] 버려진 연결이 오래 남지 않게 wait_timeout 을 봅니다. 기본값은 28800초(8시간)라, 닫지 않은 연결이 8시간 동안 자리를 차지합니다.
$ mysql $A -e "SHOW VARIABLES WHERE Variable_name IN ('wait_timeout','interactive_timeout');"mysql: [Warning] Using a password on the command line interface can be insecure.Variable_name Valueinteractive_timeout 28800wait_timeout 28800줄이면 연결 풀이 쉬게 둔 연결도 그 시간이 지나 서버 쪽에서 먼저 끊깁니다. 풀의 유휴 시간을 wait_timeout 보다 짧게 맞춘 뒤 줄입니다.
[7] 계산해 보고 정말 모자라면 한도를 올립니다. SET PERSIST 는 즉시 적용되고 재시작 뒤에도 남습니다. 새는 연결을 막지 않고 올리면 다시 찰 때까지 시간만 늘어나므로 [5] 의 계산값에 여유를 조금 더하는 정도로 잡습니다.
$ mysql $A -e "SET PERSIST max_connections = 300; SHOW VARIABLES LIKE 'max_connections';"mysql: [Warning] Using a password on the command line interface can be insecure.Variable_name Valuemax_connections 300$ mysql $A -e "RESET PERSIST max_connections;"mysql: [Warning] Using a password on the command line interface can be insecure.$ mysql $A -e "SELECT COUNT(*) FROM performance_schema.persisted_variables WHERE variable_name='max_connections';"mysql: [Warning] Using a password on the command line interface can be insecure.COUNT(*)0root 로 아예 들어가지 못하는 것이 문제라면 MySQL ERROR 1698 Access denied root를 봅니다. 연결이 잠금을 기다리며 쌓이다가 ERROR 1205 Lock wait timeout exceeded 가 함께 보이면 MySQL 1205 Lock wait timeout exceeded에서 잠금을 쥔 연결을 찾습니다. PostgreSQL 에서 같은 상황은 sorry, too many clients already 로 나옵니다 — PostgreSQL too many clients already 해결.
max_connections 를 올리기 전에 버퍼 풀이 메모리를 얼마나 차지하는지는 MySQL 8.4 innodb_buffer_pool_size 튜닝에서 봅니다.
MySQL slow log 로그를 브라우저에서 바로 분석 ↗ — 아무것도 올라가지 않습니다.