0Pricing
PostgreSQL Performance & Query Optimization · Aula

Diagnosticando atividades em tempo real com pg_stat_activity

Aprenda a usar a visão pg_stat_activity para ver o que cada conexão está fazendo agora, encontrar consultas demoradas ou bloqueadas e cancelar ou encerrar sessões problemáticas com segurança.

Diagnosticando atividades em tempo real com pg_stat_activity é uma aula grátis de PostgreSQL Performance & Query Optimization no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de PostgreSQL Performance & Query Optimization, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Your Window into Live Sessions

The pg_stat_activity view has one row per server connection. It is the first place to look when the database feels slow or stuck, showing what each session is doing this instant.

The Key Columns

The most useful columns are:

  • pid: the backend process id
  • state: active, idle, idle in transaction
  • query: the current or last SQL text
  • wait_event: what the session is waiting on

A Basic Look

Select the essentials for all active sessions.

SELECT pid, usename, state, wait_event, query
FROM pg_stat_activity
WHERE state <> 'idle';

Finding Long-Running Queries

Compute how long each active query has been running by subtracting query_start from now.

SELECT pid, now() - query_start AS runtime, query
FROM pg_stat_activity
WHERE state = 'active'
ORDER BY runtime DESC;

Idle in Transaction Danger

A session in idle in transaction holds locks and pins the oldest XID without doing work. These can block vacuum and other sessions. Hunt them down.

SELECT pid, now() - xact_start AS tx_age, query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY tx_age DESC;

Seeing What a Session Waits On

The wait_event_type and wait_event columns reveal whether a session is waiting on a lock, on I/O, or on a client. This pinpoints the bottleneck.

SELECT pid, wait_event_type, wait_event, query
FROM pg_stat_activity
WHERE wait_event IS NOT NULL;

Finding Who Blocks Whom

Combine activity with pg_blocking_pids to see which sessions are blocking others.

SELECT pid, pg_blocking_pids(pid) AS blocked_by, query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;

Cancelling a Query

pg_cancel_backend stops the current query in a session but leaves the connection open. Try this first — it is the gentler option.

SELECT pg_cancel_backend(12345);

Terminating a Connection

If cancelling is not enough, pg_terminate_backend closes the whole connection, rolling back its transaction. Use it for stuck idle-in-transaction sessions.

SELECT pg_terminate_backend(12345);

Building a Monitoring Habit

Good practice:

  • Set idle_in_transaction_session_timeout to auto-kill stragglers
  • Set statement_timeout to bound runaway queries
  • Watch pg_stat_activity during incidents before reaching for the kill switch

Counting Connections by State

To gauge overall pressure, summarize how many connections sit in each state. A pile of idle-in-transaction or active sessions hints at pooling or query problems.

SELECT state, count(*)
FROM pg_stat_activity
GROUP BY state
ORDER BY count(*) DESC;

Quick Check

Test your live-monitoring knowledge.

Recap

You learned live diagnosis with pg_stat_activity:

  • One row per connection with state, query, and wait info
  • Find long queries via now() - query_start
  • Hunt idle-in-transaction sessions that block vacuum
  • pg_blocking_pids reveals who blocks whom
  • Cancel a query or terminate a backend when needed

Perguntas Frequentes

A aula “Diagnosticando atividades em tempo real com pg_stat_activity” é grátis?

Sim — o texto completo de “Diagnosticando atividades em tempo real com pg_stat_activity” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de PostgreSQL Performance & Query Optimization, atualize para CoddyKit PRO. O curso de PostgreSQL Performance & Query Optimization inclui 4 aulas no total.

O que vou aprender em “Diagnosticando atividades em tempo real com pg_stat_activity”?

Aprenda a usar a visão pg_stat_activity para ver o que cada conexão está fazendo agora, encontrar consultas demoradas ou bloqueadas e cancelar ou encerrar sessões problemáticas com segurança. Você pratica PostgreSQL Performance & Query Optimization com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar PostgreSQL Performance & Query Optimization?

Nenhuma experiência prévia é necessária. PostgreSQL Performance & Query Optimization no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Diagnosticando atividades em tempo real com pg_stat_activity”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de PostgreSQL Performance & Query Optimization?

Sim. Cada aula de PostgreSQL Performance & Query Optimization inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Uso de pg_stat_statements e pg_buffercache
  2. Configuração de registros para análise
  3. Integração com ferramentas externas de monitoramento
  4. Diagnosticando atividades em tempo real com pg_stat_activity
← Voltar para PostgreSQL Performance & Query Optimization