Too Many MySQL Connections: Which Metrics to Check First
Compare current connections, active threads, and the server limit to identify the cause of failures before increasing the connection limit.

In this article
Ошибка о превышении числа соединений часто провоцирует простое решение: увеличить лимит. Но каждое подключение потребляет ресурсы, а причина может быть в зависших запросах или неверном пуле приложения. Сначала нужно понять, сколько соединений открыто и какую работу они выполняют.
Снимите показатели в одном контексте
Примеры SQL рассчитаны на MySQL 8.x и выполняются в уже открытом сеансе с разрешениями на просмотр необходимых переменных. Они не меняют данные и настройки. Если доступ ограничен, запросите у администратора эти показатели, не расширяя права прикладного аккаунта автоматически.
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Threads_running';
SHOW GLOBAL VARIABLES LIKE 'max_connections';
Первый показатель относится к текущим открытым соединениям. Второй помогает оценить потоки, которые не спят. Настройка лимита показывает разрешённую границу обычных подключений. Это разные величины, и сравнивать их нужно с учётом времени измерения.
Посмотрите накопленные признаки
Полезны ещё два запроса:
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
SHOW GLOBAL STATUS LIKE 'Connection_errors_max_connections';
Пиковое число соединений и счётчик отказов помогают понять, наблюдалась ли проблема раньше. Но накопленное значение не описывает текущую секунду. Учитывайте перезапуски сервера и сброс статистики, если они были между сравниваемыми замерами.
Отличайте открытые подключения от полезной работы
Большой пул может держать множество ожидающих соединений. В другой ситуации соединений немного, но каждый запрос выполняется долго. Увеличение лимита во втором случае способно усилить конкуренцию за CPU и диск, не устранив узкое место.
Пример: после развёртывания приложения число экземпляров выросло, а размер пула в каждом остался прежним. Общая потенциальная потребность стала выше лимита сервера. Здесь важен расчёт по всем приложениям, фоновым задачам и административным подключениям, а не настройка одного контейнера.
Когда нужен список процессов
Для дальнейшего разбора администратор может посмотреть текущие соединения и запросы. Такой вывод способен содержать SQL с данными клиентов. Его не нужно целиком публиковать в общем чате: обычно достаточно длительности, состояния, приложения-источника и обезличенного примера.
Не завершайте все ожидающие соединения массово. Часть относится к штатному пулу, а некоторые выполняют значимые операции. Если требуется вмешательство, оно должно быть привязано к конкретному владельцу и сценарию.
Как проверить решение
Сопоставьте момент отказа с ростом трафика, развёртыванием или запуском импорта. Затем оцените длительность запросов и настройки пулов. Изменение лимита рассматривают вместе с ресурсами сервера и ожидаемой конкуренцией.
После исправления повторите замеры в период сопоставимой нагрузки и проверьте, растёт ли счётчик отказов. Сохраните исходное и итоговое состояние. Устойчивый результат — отсутствие отказов при приемлемом времени запросов и понятном числе соединений, а не просто более высокий предел в конфигурации.
The error about exceeding the number of connections often triggers a simplistic solution: increase the limit. However, each connection consumes resources, and the cause may lie in hung queries or an incorrect application pool. First, you must determine how many connections are open and what work they are performing.
Capture metrics in a single context
The SQL examples are for MySQL 8.x and run in an already open session with permissions to view the necessary variables. They do not change data or settings. If access is restricted, request these metrics from the administrator without automatically expanding the application account's permissions.
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Threads_running';
SHOW GLOBAL VARIABLES LIKE 'max_connections';
The first metric refers to currently open connections. The second helps evaluate threads that are not sleeping. The limit setting shows the allowed boundary for standard connections. These are different values, and they must be compared with consideration for the measurement time.
Look for accumulated signs
Two more queries are useful:
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
SHOW GLOBAL STATUS LIKE 'Connection_errors_max_connections';
Peak connection counts and failure counters help determine if the issue occurred previously. However, accumulated values do not describe the current second. Consider server restarts and statistics resets if they occurred between the measurements being compared.
Distinguish between open connections and productive work
A large pool can hold many waiting connections. In another scenario, there are few connections, but each request takes a long time to execute. Increasing the limit in the second case may intensify competition for CPU and disk without resolving the bottleneck.
Example: after deploying the application, the number of instances increased, but the pool size in each remained the same. The total potential demand now exceeds the server limit. Here, calculations must account for all applications, background tasks, and administrative connections, not just a single container configuration.
When a process list is needed
For further analysis, an administrator can view current connections and queries. Such output may contain SQL with customer data. It should not be published in full in a general chat; typically, duration, status, source application, and an anonymized example are sufficient.
Do not terminate all waiting connections en masse. Some belong to the standard pool, while others perform significant operations. If intervention is required, it must be tied to a specific owner and scenario.
How to Verify the Solution
Correlate the moment of failure with traffic spikes, deployments, or import launches. Then evaluate request duration and pool settings. Adjusting the limit must be considered alongside server resources and expected contention.
After applying the fix, repeat measurements during comparable load and check if the failure counter is increasing. Save both the initial and final states. A stable result means no failures within acceptable request times and a clear number of connections, not merely a higher limit in the configuration.

Discussion0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.