How to Find Long-Running Transactions in MySQL 8.4 Without Terminating Connections
Transaction age and lock wait duration are distinct metrics. Two read-only queries help identify old InnoDB transactions and gather data for further investigation.

In this article
Обмен с 1С завершился, а база магазина продолжает испытывать задержки. Один из возможных следов — транзакция, которая началась давно и ещё не закончилась. Её возраст не равен времени выполнения текущего запроса: между SQL-операциями приложение может ожидать внешний ответ, сохраняя незавершённую транзакцию.
Руководство рассчитано на MySQL 8.4 с InnoDB и уже открытый разрешённый сеанс для диагностики. Это не инструкция для MariaDB. Синтаксис и значения полей сверены с официальным руководством MySQL 8.4 26 сентября 2026 года. Запросы только читают сведения; на стенде MySQL 8.4 они в рамках подготовки материала не выполнялись. Завершение соединений, изменение параметров и исправление приложения сюда не входят.
Для чтения INFORMATION_SCHEMA.INNODB_TRX требуется уже предоставленная привилегия PROCESS. Используйте предназначенную для диагностики учётную запись. Не расширяйте права обычного аккаунта магазина ради этой проверки. Если доступ запрещён, передайте запрос администратору; ошибка доступа не означает отсутствие долгих транзакций.
Сначала подтвердите сервер и место наблюдения
В SQL-сеансе выполните:
SELECT VERSION();
Нужна версия сервера MySQL 8.4, а не установленного на рабочем компьютере клиента. Если подключение ведёт на реплику, наблюдение относится к ней. Оно не описывает транзакции приложения на другом узле. В управляемой базе часть диагностических возможностей может ограничиваться провайдером; эти ограничения не следует обходить.
Перед сбором данных запишите время инцидента и роль узла. Сеанс диагностики должен использовать согласованный режим подключения; не открывайте специально длительную транзакцию для наблюдения. Внешние признаки задержки также сохраните: какой этап обмена или действие покупателя ожидало ответа и когда это происходило.
Выберите самые старые видимые транзакции
Следующий запрос возвращает до двадцати строк, начиная с самых ранних по времени начала. Он не читает содержимое заказов и не выводит текст выполняемого SQL:
SELECT TRX_ID, TRX_MYSQL_THREAD_ID, TRX_STATE, TRX_STARTED, TIMESTAMPDIFF(SECOND, TRX_STARTED, NOW()) AS age_seconds, TRX_WAIT_STARTED FROM INFORMATION_SCHEMA.INNODB_TRX ORDER BY TRX_STARTED LIMIT 20;
Поле TRX_STARTED содержит время начала транзакции. Выражение TIMESTAMPDIFF(SECOND, TRX_STARTED, NOW()) вычисляет разницу в секундах на момент запроса; age_seconds — заданное нами имя этого столбца. Сохраняйте исходное время вместе с рассчитанным возрастом. При сопоставлении с журналами приложения учитывайте часовые пояса, а при аномальных отрицательных значениях проверьте время и контекст наблюдения, прежде чем делать выводы.
TRX_MYSQL_THREAD_ID связывает транзакцию с соединением MySQL. Это не номер процесса Linux и не номер заказа. TRX_ID относится к транзакции; внутренние оптимизации чтения влияют на назначение её идентификатора, поэтому не следует превращать его в универсальный счётчик всей активности базы.
Ограничение LIMIT 20 сокращает результат, а не гарантирует просмотр только двадцати внутренних объектов. Для сортировки серверу может понадобиться обработать больше диагностических сведений. На перегруженной базе не запускайте запрос в частом бесконечном цикле. Начните с одного снимка и повторите его через осмысленный интервал, если это допускает состояние сервера.
Разделите возраст и ожидание блокировки
В TRX_STATE возможны состояния RUNNING, LOCK WAIT, ROLLING BACK и COMMITTING. Они описывают разные этапы. Значение RUNNING само по себе не доказывает, что соединение всё это время непрерывно выполняло один SQL-запрос. Для поиска текущей операции администратору может понадобиться дополнительная информация о соединении.
При LOCK WAIT поле TRX_WAIT_STARTED показывает начало ожидания блокировки. Оно может быть существенно позже TRX_STARTED. Условный пример: транзакция существует 600 секунд, а блокировку ждёт последние 20. Приписывать все десять минут одной блокировке было бы ошибкой. Обратный вывод тоже неверен: старая транзакция без текущего ожидания не обязательно безвредна для остальных.
Наличие LOCK WAIT ещё не показывает, кто удерживает нужный ресурс. Для установления связи ожидающего и блокирующего MySQL 8.4 предоставляет таблицы Performance Schema data_lock_waits и data_locks. Это следующий этап расследования. Не назначайте виновником просто первую строку с наибольшим возрастом.
Старая транзакция может быть ожидаемой частью разрешённой обработки, а может остаться открытой из-за ошибки приложения. Длительное чтение также способно удерживать старое представление данных и мешать очистке ненужных версий строк. Поэтому отсутствие изменения заказов в текущий момент не исключает влияния на работу InnoDB. Однако один возраст не определяет ни ущерб, ни способ вмешательства.
Повторный снимок помогает найти продолжение истории
Повторите тот же запрос через согласованный интервал и сравните связь с соединением, время начала и состояние. Если строка исчезла, транзакция могла завершиться между измерениями. Если сохранилась с тем же началом, её возраст должен увеличиться примерно на длительность интервала. Не объединяйте записи только по номеру соединения после его разрыва и нового подключения.
Сведения о транзакциях и отдельный список соединений не образуют гарантированно единый неподвижный снимок. Документация MySQL предупреждает об их возможной несогласованности во времени. Пока вы переходите от одного источника к другому, запрос уже может закончиться. Отсутствие строки во втором источнике требует проверки времени, а не немедленного вывода о повреждении базы.
Пустой результат говорит лишь о том, что в момент наблюдения в доступной таблице не найдено соответствующих транзакций. Он не доказывает отсутствие блокировок ранее, медленных запросов вне интервала или проблем другого движка. Инструкция ограничена текущим состоянием InnoDB на выбранном сервере.
Сопоставьте находку с операцией приложения
Для ответственного разработчика подготовьте время снимков, версию и роль сервера, идентификатор соединения, начало транзакции, её состояние и момент начала ожидания. Добавьте обезличенное описание операции: например, импорт определённой группы товаров. Пароли, полный заказ и рабочие токены в этот пакет не входят.
Таблица транзакций содержит и поле TRX_QUERY, но приведённая выборка намеренно его не запрашивает. Текст SQL может включать значения из данных покупателей. Если без него нельзя продолжить расследование, администратор собирает нужный фрагмент разрешённым способом и ограничивает круг получателей. Сначала полезно понять, какое приложение владеет соединением и чего оно ожидало.
Не завершайте соединение только потому, что оно оказалось старейшим. Прерывание может запустить длительный откат, затронуть обмен и вызвать повтор операции на стороне приложения. Решение о вмешательстве принимают после выяснения владельца, незавершённых изменений и плана восстановления. Результат этого руководства — подтверждённый след для диагностики, а не автоматически выбранная цель для остановки.
The exchange with 1C has completed, yet the store database continues to experience delays. One possible culprit is a transaction that started long ago and remains unfinished. Its age does not equal the duration of the current query: between SQL operations, the application may be waiting for an external response while keeping the transaction open.
This guide targets MySQL 8.4 with InnoDB and assumes an existing, authorized session for diagnostics. It is not intended for MariaDB. Syntax and field values have been verified against the official MySQL 8.4 documentation as of September 26, 2026. The queries read only; they were not executed on a MySQL 8.4 testbed during material preparation. Terminating connections, modifying parameters, or fixing application code are outside the scope of this guide.
Reading INFORMATION_SCHEMA.INNODB_TRX requires the already granted privilege PROCESS. Use the dedicated diagnostic account. Do not elevate the permissions of a standard store account for this check. If access is denied, forward the request to an administrator; an access error does not indicate the absence of long-running transactions.
First, confirm the server and observation point
In the SQL session, execute:
SELECT VERSION();
You need the MySQL 8.4 server version, not the one installed on the client's local machine. If the connection points to a replica, the observation applies to that replica. It does not describe application transactions on another node. In a managed database, some diagnostic capabilities may be restricted by the provider; these restrictions must not be bypassed.
Before collecting data, record the incident time and the node role. The diagnostic session must use a consistent connection mode; do not intentionally open a long-running transaction for observation. Also preserve external signs of latency: which exchange stage or buyer action was waiting for a response, and when this occurred.
Select the oldest visible transactions
The following query returns up to twenty rows, starting with the earliest by start time. It does not read order contents and does not output the executing SQL text:
SELECT TRX_ID, TRX_MYSQL_THREAD_ID, TRX_STATE, TRX_STARTED, TIMESTAMPDIFF(SECOND, TRX_STARTED, NOW()) AS age_seconds, TRX_WAIT_STARTED FROM INFORMATION_SCHEMA.INNODB_TRX ORDER BY TRX_STARTED LIMIT 20;
The field TRX_STARTED contains the transaction start time. The expression TIMESTAMPDIFF(SECOND, TRX_STARTED, NOW()) calculates the difference in seconds at the moment of the query; age_seconds is the name of this column as defined by us. Preserve the original timestamp alongside the calculated age. When correlating with application logs, account for time zones, and before drawing conclusions regarding anomalous negative values, verify the time and observation context.
TRX_MYSQL_THREAD_ID links a transaction to a MySQL connection. This is not a Linux process ID or an order number. TRX_ID refers to the transaction; internal read optimizations affect how its identifier is assigned, so do not treat it as a universal counter for all database activity.
The limit LIMIT 20 reduces the result set, but does not guarantee that only twenty internal objects are viewed. For sorting, the server may need to process more diagnostic data. Do not run a query in a frequent infinite loop on an overloaded database. Start with a single snapshot and repeat it after a meaningful interval, if the server state allows.
Separate transaction age from lock wait time
In TRX_STATE, states such as RUNNING, LOCK WAIT, ROLLING BACK, and COMMITTING are possible. They describe different stages. The value of RUNNING alone does not prove that the connection continuously executed a single SQL query throughout. To find the current operation, an administrator may need additional information about the connection.
During LOCK WAIT, the field TRX_WAIT_STARTED shows the start of the lock wait. It can be significantly later than TRX_STARTED. A conditional example: a transaction has existed for 600 seconds, but the lock has been waited for only in the last 20 seconds. Attributing all ten minutes to a single lock would be an error. The reverse is also incorrect: an old transaction without a current wait is not necessarily harmless to others.
The presence of LOCK WAIT does not yet indicate who holds the required resource. To establish a connection between the waiting and blocking processes, MySQL 8.4 provides the Performance Schema tables data_lock_waits and data_locks. This is the next stage of the investigation. Do not simply assign blame to the first row with the highest age.
An old transaction may be an expected part of allowed processing, or it may remain open due to an application error. Long-running reads can also hold an old data snapshot and hinder the cleanup of unnecessary row versions. Therefore, the absence of order changes at the current moment does not rule out an impact on InnoDB operations. However, age alone does not determine the damage or the intervention method.
A repeat snapshot helps find the continuation of the history
Repeat the same query at a consistent interval and compare the connection ID, start time, and state. If the row is missing, the transaction may have completed between measurements. If it persists with the same start time, its age should have increased by approximately the interval duration. Do not merge records solely based on the connection ID after a disconnect and reconnection.
Transaction data and a separate list of connections do not form a guaranteed consistent, static snapshot. MySQL documentation warns of potential temporal inconsistencies between them. By the time you switch from one source to another, the query may already have finished. A missing row in the second source requires a time check, not an immediate conclusion about database corruption.
An empty result only indicates that no matching transactions were found in the accessible table at the moment of observation. It does not prove the absence of prior locks, slow queries outside the interval, or issues with other storage engines. The guidance is limited to the current InnoDB state on the selected server.
Correlate the finding with the application operation
For a responsible developer, prepare the snapshot time, server version and role, connection ID, transaction start time, its state, and the moment the wait began. Add an anonymized description of the operation, such as importing a specific group of products. Passwords, full order details, and active tokens are not included in this package.
The transaction table contains the TRX_QUERY field, but the provided query intentionally does not request it. The SQL text may include values from customer data. If the investigation cannot proceed without it, the administrator collects the necessary fragment using an authorized method and restricts the recipient list. First, it is useful to understand which application owns the connection and what it was waiting for.
Do not terminate a connection simply because it is the oldest. An abrupt termination can trigger a lengthy rollback, disrupt the exchange, and cause the application to retry the operation. The decision to intervene must be made only after identifying the owner, any uncommitted changes, and the recovery plan. The outcome of this guidance is a verified trail for diagnostics, not an automatically selected target for termination.





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