F.50. pg_wait_sampling
pg_wait_sampling — это расширение Postgres Pro для периодического сбора статистики по событиям ожидания.
Начиная с версии 9.6, Postgres Pro Enterprise выдаёт информацию о текущих событиях ожидания для определённых процессов. Однако чтобы получить полезную общую статистику активности сервера, необходимо снимать показания по событиям ожидания неоднократно. Расширение pg_wait_sampling автоматизирует снятие показаний по событиям ожидания, запуская специальный рабочий процесс. Когда расширение pg_wait_sampling включено, вы можете получать следующую периодически собираемую информацию:
История ожиданий — список событий ожидания для недавних процессов, с отметками времени.
Профиль ожиданий — количество наблюдавшихся событий ожидания для всех процессов, в разрезе типов событий.
Текущие события ожидания для всех процессов, включая фоновые рабочие процессы.
Используя pg_wait_sampling, вы можете выявить проблемы зависимостей запросов, выполняющихся дольше чем ожидается. Вы можете видеть процессы в состоянии ожидания в каждый момент времени и проанализировать статистику событий ожидания. Список возможных событий ожидания приведён в Таблице 28.4.
См. также
Просмотр статистики по событиям ожидания
F.50.1. Установка
Расширение pg_wait_sampling входит в состав Postgres Pro Enterprise и не имеет особых требований.
Чтобы включить pg_wait_sampling, выполните следующее:
Добавьте
pg_wait_samplingв переменнуюshared_preload_librariesв файлеpostgresql.conf:shared_preload_libraries = 'pg_wait_sampling'
Создайте расширение
pg_wait_sampling, выполнив следующий запрос:CREATE EXTENSION pg_wait_sampling;
Перезапустите сервер. Так как расширению
pg_wait_samplingтребуется дополнительная разделяемая память и фоновый рабочий процесс, вы должны перезапустить сервер после добавления или удаленияpg_wait_sampling.
После создания расширения pg_wait_sampling начинает собирать статистику по событиям ожидания для каждого процесса. Вы можете по своему усмотрению изменить частоту снятия показаний и настроить режимы сбора статистики, используя переменные GUC.
Если вы хотите остановить сбор статистики, удалите расширение pg_wait_sampling, уберите pg_wait_sampling из переменной shared_preload_libraries и перезагрузите сервер.
F.50.2. Использование
F.50.2.1. Просмотр статистики по событиям ожидания
Когда pg_wait_sampling работает, показания снимаются по умолчанию каждые 10 мс. Обратиться к собранной статистике вы можете через набор функций и представлений. Если вы замечаете, что некоторые запросы «зависли» или выполняются дольше, чем ожидается, вы можете увидеть все текущие события ожидания в представлении pg_wait_sampling_current:
SELECT * FROM pg_wait_sampling_current;
Возвращаемая статистика охватывает все активные процессы, включая фоновые рабочие процессы. Чтобы отфильтровать это представление по одному процессу, воспользуйтесь функцией pg_wait_sampling_get_current() и передайте ей идентификатор интересующего процесса:
SELECT * FROM pg_wait_sampling_get_current(pid);Чтобы лучше понимать динамику недавних событий ожидания, можно обратиться к представлению pg_wait_sampling_history, показывающему историю событий ожидания для последних процессов:
SELECT * FROM pg_wait_sampling_history;
Это представление выдаёт показания по событиям ожидания с отметками времени. История ожиданий реализована как кольцевой буфер в памяти, размер которого по умолчанию ограничен 5000 показаниями. Чтобы сохранить историю за больший период времени, вы можете изменить переменную pg_wait_sampling.history_size либо подключить клиентское приложение, которое будет периодически считывать историю ожиданий и сохранять её в локальном хранилище.
Для отслеживания событий ожидания в вашей базе данных в течение длительного времени используйте представление pg_wait_sampling_profile:
SELECT * FROM pg_wait_sampling_profile;
Профиль ожиданий сохраняется как хеш-таблица в памяти, накапливающая показатели по отдельным процессам и по событиям ожидания. Вы можете сбросить профиль ожиданий, вызвав функцию pg_wait_sampling_reset_profile(). Если вы подключите к вашей базе данных клиента, который будет периодически сбрасывать данные событий ожидания и очищать профиль, вы можете сохранять и анализировать концентрацию событий ожидания во времени.
Важно
Так как статистика по событиям ожидания находится в ОЗУ, важно очищать профиль ожиданий время от времени во избежание переполнения памяти.
Если вас не интересует распределение событий ожидания по процессам, вы можете присвоить переменной pg_wait_sampling.profile_pid false. В этом случае значение pid для всех процессов считается равным нулю и показатели ожиданий для всех процессов аккумулируются вместе.
F.50.3. Справка
F.50.3.1. Переменные GUC
Поведение расширения pg_wait_sampling настраивается с помощью переменных GUC. Для изменения переменных GUC необходимо иметь права суперпользователя. Так как эти переменные находятся в разделяемой памяти, вы можете изменить их из любого подключения, и это повлияет на работу фонового рабочего процесса pg_wait_sampling.
pg_wait_sampling.history_size(int4)Размер буфера в памяти для истории показаний (максимальное число показаний).
По умолчанию: 5000
pg_wait_sampling.history_period(int4)Интервал снятия показаний для истории, в миллисекундах.
По умолчанию: 10
pg_wait_sampling.profile_period(int4)Интервал снятия показаний для профиля, в миллисекундах.
По умолчанию: 10
pg_wait_sampling.profile_pid(bool)Режим обработки показаний для профиля ожиданий. Если равняется
true, профиль ожиданий собирается по процессам. Если задать дляpg_wait_sampling.profile_pidзначениеfalse, профиль будет собираться по всем процессам сразу. В этом случае значениеpidдля всех процессов принимается равным нулю и соответствующая строка в профиле отражает события ожидания для всех процессов.По умолчанию:
truepg_wait_sampling.profile_queries(bool)Режим обработки показаний для профиля ожиданий. Если установлено значение
false, собирается общий профиль ожиданий для всех запросов. В этом случае значениеqueryidдля каждого запроса устанавливается равным нулю, а соответствующая строка содержит показания по событиям ожидания для всех запросов. Чтобы собирать профиль ожиданий для каждого запроса отдельно, загрузите расширение pg_stat_statements и установите для параметраpg_wait_sampling.profile_queriesзначениеtrue.По умолчанию:
true
F.50.3.2. Представления pg_wait_sampling
F.50.3.2.1. Представление pg_wait_sampling_current
Представление pg_wait_sampling_current выдаёт информацию о текущих событиях ожидания для всех процессов, включая фоновые рабочие процессы.
Таблица F.37. Представление pg_wait_sampling_current
| Имя столбца | Тип столбца | Описание |
|---|---|---|
pid | int4 | Идентификатор процесса |
event_type | text | Имя типа события ожидания |
event | text | Имя события ожидания |
queryid | int8 | Идентификатор запроса |
F.50.3.2.2. Представление pg_wait_sampling_history
Представление pg_wait_sampling_history содержит историю событий ожидания. Эти данные хранятся в кольцевом буфере в памяти.
Таблица F.38. Представление pg_wait_sampling_history
| Имя столбца | Тип столбца | Описание |
|---|---|---|
pid | int4 | Идентификатор процесса |
ts | timestamptz | Время снятия показания |
event_type | text | Имя типа события ожидания |
event | text | Имя события ожидания |
queryid | int8 | Идентификатор запроса |
F.50.3.2.3. Представление pg_wait_sampling_profile
Представление pg_wait_sampling_profile содержит профиль событий ожидания. Эти данные хранятся в виде хеш-таблицы в памяти.
Таблица F.39. Представление pg_wait_sampling_profile
| Имя столбца | Тип столбца | Описание |
|---|---|---|
pid | int4 | Идентификатор процесса |
event_type | text | Имя типа события ожидания |
event | text | Имя события ожидания |
queryid | int8 | Идентификатор запроса |
count | int8 | Число наблюдений |
F.50.3.3. Функции
pg_wait_sampling_get_current(pidint4)Возвращает представление
pg_wait_sampling_currentсо списком текущих событий ожидания. Если вы зададите аргументpid, представление будет отфильтровано по процессу с заданным идентификатором.Аргументы:
pid— Необязательный параметр. Идентификатор процесса, для которого будут выводиться текущие события ожидания.
pg_wait_sampling_reset_profile()Сбрасывает профиль ожиданий и очищает память.
F.50.4. Автор
Александр Коротков
F.50. pg_wait_sampling
pg_wait_sampling is a Postgres Pro extension for collecting sampling-based statistics on wait events.
Starting from the 9.6 version, Postgres Pro Enterprise provides information about the current wait events for particular processes. However, to get descriptive statistics of the server activity, you have to sample wait events multiple times. The pg_wait_sampling extension automates wait events sampling by launching a special background worker. With pg_wait_sampling enabled, you can get the following sampling-based data:
Waits history — the list of wait events for recent processes, with timestamps.
Waits profile — the number of wait event samples for all processes over time, per wait event type.
Current wait events for all processes, including background workers.
Using pg_wait_sampling, you can troubleshoot dependencies for queries that take longer than expected. You can see what a particular process is waiting for at each moment of time, and analyze wait events statistics. For the list of possible wait events, see Table 28.4.
See Also
Viewing Statistics on Wait Events
F.50.1. Installation
The pg_wait_sampling extension is included into Postgres Pro Enterprise and requires no special prerequisites.
To enable pg_wait_sampling, do the following:
Add
pg_wait_samplingto theshared_preload_librariesvariable in thepostgresql.conffile:shared_preload_libraries = 'pg_wait_sampling'
Create the
pg_wait_samplingextension using the following query:CREATE EXTENSION pg_wait_sampling;
Restart the server. Since
pg_wait_samplingrequires additional shared memory and launches a background worker, you must restart the server after adding or removingpg_wait_sampling.
Once the extension is created, pg_wait_sampling starts collecting statistics on wait events for each process. Optionally, you can change the sampling frequency and configure statistics collection modes using GUC variables.
If you want to stop collecting statistics, drop the pg_wait_sampling extension, remove the pg_wait_sampling from the shared_preload_libraries variable, and restart the server again.
F.50.2. Usage
F.50.2.1. Viewing Statistics on Wait Events
When pg_wait_sampling is enabled, wait events are sampled each 10ms by default. You can access the collected statistics through a set of functions and views. If some of your queries appear stalled or take longer than expected, you can review all the current wait events in the pg_wait_sampling_current view:
SELECT * FROM pg_wait_sampling_current;
The returned statistics covers all the active processes, including background workers. To filter the view for a single process, run pg_wait_sampling_get_current() function specifying the process ID:
SELECT * FROM pg_wait_sampling_get_current(pid);
To better understand the dynamics of the recent wait events, you can access the pg_wait_sampling_history view that provides the wait events history for the latest processes:
SELECT * FROM pg_wait_sampling_history;
The returned view displays wait samples per process, with event timestamps. Waits history is implemented as an in-memory ring buffer. By default, the history size is limited to 5000 samples. To save history for a longer period of time, you can modify the pg_wait_sampling.history_size variable, or connect a client application to periodically read waits history and dump it to a local storage.
To monitor wait events in your database over time, use the pg_wait_sampling_profile view:
SELECT * FROM pg_wait_sampling_profile;
Waits profile is stored as an in-memory hash table that accumulates samples per each process and each wait event. You can reset waits profile by calling the pg_wait_sampling_reset_profile() function. If you connect a client to your database that periodically dumps the wait events data and resets the profile, you can save and compare statistics of wait events intensity over time.
Important
Since wait sampling statistics is stored in RAM, make sure to reset the waits profile from time to time to avoid memory overflow.
If you are not interested in the distribution of wait events between processes, you can set the pg_wait_sampling.profile_pid variable to false. In this case, the pid value for each process is set to zero, and wait samples for all the processes are stored together.
F.50.3. Reference
F.50.3.1. GUC Variables
The pg_wait_sampling extension is configured with GUC variables. You must have superuser rights to change GUC variables. Since these variables are placed into shared memory, you can change them from any backend that affects the pg_wait_sampling background worker runtime.
pg_wait_sampling.history_size(int4)Size of in-memory ring buffer for history sampling, in the number of samples.
Default: 5000
pg_wait_sampling.history_period(int4)Time interval for history sampling, in milliseconds.
Default: 10
pg_wait_sampling.profile_period(int4)Time interval for waits profile sampling, in milliseconds.
Default: 10
pg_wait_sampling.profile_pid(bool)Sampling mode for waits profile. If set to
true, waits profile is collected per process. If you setpg_wait_sampling.profile_pidtofalse, waits profile is collected for all processes together. In this case, thepidvalue for each process is set to zero, and the corresponding row contains wait samples for all the processes.Default:
truepg_wait_sampling.profile_queries(bool)Sampling mode for waits profile. If set to
false, waits profile is collected for all queries together. In this case, thequeryidvalue for each query is set to zero, and the corresponding row contains wait samples for all the queries. To collect waits profile per query, ensure that the pg_stat_statements extension is configured and setpg_wait_sampling.profile_queriestotrue.Default:
true
F.50.3.2. pg_wait_sampling Views
F.50.3.2.1. pg_wait_sampling_current View
The pg_wait_sampling_current view provides the information about the current wait events for all processes, including background workers.
Table F.37. pg_wait_sampling_current View
| Column Name | Column Type | Description |
|---|---|---|
pid | int4 | Process ID |
event_type | text | Name of wait event type |
event | text | Name of wait event |
queryid | int8 | Query ID |
F.50.3.2.2. pg_wait_sampling_history View
The pg_wait_sampling_history view provides the history of wait events. This data is stored as an in-memory ring buffer.
Table F.38. pg_wait_sampling_history View
| Column Name | Column Type | Description |
|---|---|---|
pid | int4 | Process ID |
ts | timestamptz | Sample timestamp |
event_type | text | Name of wait event type |
event | text | Name of wait event |
queryid | int8 | Query ID |
F.50.3.2.3. pg_wait_sampling_profile View
The pg_wait_sampling_profile view provides the profile of wait events. This data is stored as an in-memory hash table.
Table F.39. pg_wait_sampling_profile View
| Column Name | Column Type | Description |
|---|---|---|
pid | int4 | Process ID |
event_type | text | Name of wait event type |
event | text | Name of wait event |
queryid | int8 | Query ID |
count | int8 | Number of samples |
F.50.3.3. Functions
pg_wait_sampling_get_current(pidint4)Returns the
pg_wait_sampling_currentview with the list of current wait events. If you set thepidargument, the view is filtered for the process with thispid.Arguments:
pid— Optional. The process ID for which to display the current wait events.
pg_wait_sampling_reset_profile()Resets the waits profile and clears the memory.
F.50.4. Author
Alexander Korotkov