Who Is Doing What
See exactly who is running what inside a live PostgreSQL — learn pg_stat_activity, pg_locks, and pg_blocking_pids so you can diagnose a blocked or slow database in seconds.
When something is slow or stuck in PostgreSQL the first question is always the same: who is doing what right now? This course gives you the two views that answer it — pg_stat_activity for the live process list and pg_locks for the lock table — and teaches you to read them on a real stand with real contention. We start by building a transactional shop database, then launch a background workload to fill the activity view with interesting states. We walk every useful field in pg_stat_activity — state, wait_event_type, wait_event, query_start — and write focused queries to find active sessions, long-running queries, and sessions stuck in idle in transaction. Then we create a genuine row-level lock conflict between two sessions and watch pg_locks record it. We finish with pg_blocking_pids and a joined blocked-vs-blocker query that shows the full picture in one row: who is waiting, who is holding, what each is trying to do, and for how long.
What you'll build
- Read pg_stat_activity: find an active query, an idle connection, and a long-running one
- Interpret state, wait_event_type, wait_event, and query_start
- Tell active, idle, and idle in transaction apart
- Read pg_locks: understand locktype, mode, and granted
- Find blocked and blocking sessions with pg_blocking_pids()
- Write a joined blocked-vs-blocker query using pid and query text
Contents
- A database to watch
- Wait for it to be ready
- One command to bring it up
- Start the server
- A short way into the database
- The users table
- The orders table
- The payments table
- The events table
- Create the tables
- Seed the users
- Seed orders and payments
- Seed the events
- Load the data
- Fresh statistics, single-threaded plans
- The full process list
- A background workload
- Start the workload
- Query the live process list
- Filter for active sessions only
- See who is running
- The idle state
- Spot idle sessions
- Find long-running queries
- Catch the slow query
- What is each session waiting for
- Read the wait events
- Session A: open a transaction and hold it
- Session B: try to write the same row
- Start the blocking session
- Start the waiting session
- The full lock table
- See the conflict in the lock table
- Filter to waiting locks only
- Isolate the waiting session
- Ask who is blocking each session
- Find the blocker
- The blocked-vs-blocker query
- Read the full picture
- A clean slate when you need one
- The complete diagnostic flow