Video in progress

Several services run on a single PostgreSQL cluster, and one service's heavy queries slow down the others. How do you detect the "noisy neighbor" and isolate it?

First I group pg_stat_statements and pg_stat_activity by role or application_name to see who takes how much CPU, I/O and connections. Then I use per-role limits (connections, timeouts, work_mem), move heavy reads to a replica, and eventually split the heavy service into its own cluster.

📖 Answer

PostgreSQL has no resource manager that divides CPU or I/O by role. So isolation is indirect.

Detection. Every service must connect with its own role and application_name; without that you can't separate anything.

SELECT r.rolname,
       sum(s.total_exec_time) / 1000 AS exec_sec,
       sum(s.shared_blks_read)       AS blks_read,
       sum(s.calls)                  AS calls
FROM pg_stat_statements s
JOIN pg_roles r ON r.oid = s.userid
GROUP BY r.rolname
ORDER BY exec_sec DESC;

The usual picture: one "reporting" or "batch" service takes 60% of the time.

Limiting:

ALTER ROLE billing_batch CONNECTION LIMIT 10;
ALTER ROLE billing_batch SET statement_timeout = '5min';
ALTER ROLE billing_batch SET max_parallel_workers_per_gather = 0;
ALTER ROLE api_service   SET statement_timeout = '3s';
  • In PgBouncer, a separate pool size for each service, so one service can't take all the server connections.
  • Batch jobs at night or with throttling (a pause after each batch).
  • Heavy reads go to a replica.

Separation. If the services' SLAs differ sharply (API 50 ms, report 10 minutes), they shouldn't sit in one cluster. A shared cluster is cheap, but on every incident there's the "who's to blame" question, and one service's migration is a risk to everyone. For each critical service I choose its own cluster, and for small, low-load services a shared cluster with separate databases and the role model.