Home›Operate›Database operations with AI agents
Operate · AI agents

Database operations with AI agents

Should an agent investigate your production database, or change it?

An agent that looks can save you the first twenty minutes of an incident. An agent that changes things can also make an incident worse, faster. This guide is for database engineers and the teams who decide: what an operations agent may observe, recommend and run, which actions need a person, and how to keep it to five connections so it can never become the load it was sent to fix.

The short answerLet the agent read first, through a read-only login with a hard connection cap. Let it recommend with evidence. Let a named person approve every change, shown as an exact command with its risk and undo. Keep failover, forced quorum and data deletion out of its hands. A diagnosis is not permission to change anything.
What is real today

What exists, and what is only a design

The DBA agent on this site is real, but it is private and has a waitlist. Some parts of this guide describe what it does today. Others are a design you can build. The table says which is which.

PartStatusWhat it means
DiagnosisWorks todayIt matches a symptom to a playbook and runs only that playbook's read-only steps. The session is read-only (default_transaction_read_only = on, a 5 second statement_timeout, a 1 second lock_timeout, application_name = dba-agent). The MongoDB user has only clusterMonitor and readAnyDatabase. A deny list blocks state-changing commands as a second check. You connect it with a read-only user. The scorecard shows the incidents it was tested on.
FixesWorks todayIt can propose four fixes: end an idle-in-transaction session, cancel a query, add an index, drop an inactive replication slot. Each is a change request with the command, risk, why, undo, precheck and verify step. A named person approves. On apply it re-checks the precheck and says "stale", running nothing, if the situation changed. It runs on a separate login with only the rights needed, verifies, and writes an audit line.
High availabilityWorks todaypython3 -m dbagent.ha manages Patroni, InnoDB Cluster (MySQL Shell), MongoDB replica sets, MySQL Orchestrator and Kubernetes (CloudNativePG; the Percona operators are untested). Reads run freely. Every change shows its command, why, undo and risk, and waits for a typed approval. A read-only check must pass after each change or it stops. Everything goes to a JSONL audit log. High-risk changes (failover or forced promotion, forced quorum, rebuilding a member, forcing a new replica set config, Orchestrator recover) are off by default: it refuses them unless the operator passes --allow-high-risk, and then each still needs the target's name typed back. --dry-run shows the whole plan.
Five-connection capA design you buildThe agent does not count its own connections. The cap is enforced at the database boundary: a role limit, a pooler and the network. Section 5 shows how, with a measurement.
Incident workspaceNot shippedThe timeline, evidence cards and next-action preview in section 6 are a design, and the interactive demo is a simulation with scripted data. No database is connected to it. The agent does not have this interface today.
Assistant and MCP serverLookup onlyThe site's MCP server looks up this site's own pages. It never connects to a database. It is built but not yet published for download.
1 · Two kinds of agent

An agent that remembers is not an agent that operates

Both are called "database agents", and they are different problems. Mixing them up is how a chat assistant ends up with a superuser login.

Application agentOperations agent
What it doesAnswers users, calls tools, runs for themInvestigates a database and may change it
What it storesConversations, checkpoints, tool calls, long-term memoriesEvidence, hypotheses, change requests, an audit trail
Its database roleIt is a client: it reads and writes its own tablesIt is an operator: it looks at other systems' sessions, locks and settings
What goes wrongLost state, a memory read for the wrong tenant, a slow vector searchA wrong kill, an index build at peak, a failover that loses writes
Read moreAgent memory and stateThis page

An operations agent also needs a place to keep its own incident notes. That store is small and lives apart from the databases it watches.

Diagnosis is not authorizationWhen the agent says "the cause is a session idle in a transaction", that is a claim with evidence. It is not an order to end the session. The step from "I think" to "do it" is a separate decision, made by a policy and, for anything that disrupts, by a person.
2 · Scope and boundaries

What it may observe, recommend and run

LevelThe agent mayExamples
ObserveRead through approved checks, in a read-only session, with timeouts and a connection capConnection counts by state, lock chains, top statements, plans from EXPLAIN, replication lag, cloud events and metrics, the deploy log, the playbooks
RecommendRank causes, name the safest next check, write a change request with a preview, write a handoff"Most likely a pool problem after the 14:02 deploy. This is the evidence. This is what would disprove it."
ExecuteRun one allowlisted, approved change through a narrow executor, then verify itEnd one named session, cancel one query, build one index, after a named person approved that exact command
Stays humanThe agent prepares. People decide and, for the highest risks, run itFailover, forced quorum, rebuilding a member, accepting a data-loss window, rolling back a deploy, granting access, telling customers, closing the incident
Out of scopeNot offered to the agent at allArbitrary SQL or shell on the database host, reading table contents beyond what a diagnosis needs, any environment other than the one it is configured for, changing its own permissions or limits

It never raises its own permissions. Rights live in the database and in your cloud's IAM, and people change them through review. If an action needs a right the agent does not have, it says "unavailable: needs this right" and stops. It does not look for another login, ask a human to paste a password into the chat, or try a different tool that happens to work.

3 · Reference architecture

From alert to audit trail

A reference design, not a product diagram. The approval and two-login parts match how the DBA agent works. The pooler and network rules are what you add at the database boundary. Step through it.

ConcernRule
IdentityOne identity per environment and per purpose. A read-only login for checks, a separate executor login per action type, none shared with an application or a DBA. Short-lived credentials where the platform issues them, such as IAM database authentication on RDS and Aurora.
SecretsHeld by the tools and the secrets manager, never in the model's context, the prompt, the logs or the incident record.
EnvironmentsStaging and production are separate agents, logins and networks. A tool built for one cannot be pointed at the other.
ObservabilityThe agent is monitored like any production service: its connection count, queue depth, rejected work, tool errors, and the age of the evidence it acts on.
The operatorSees the evidence behind every claim, can reject or edit a request, and has a stop control that halts all tools. The on-call person stays the owner of the incident.
4 · Action permission model

Five tiers, from "explain" to "never by the agent"

Every action the agent can take has a tier. The tier decides the login it uses, who approves and how it is verified. Scroll the table sideways on a phone.

TierExamplesPermissionsApprovalSafeguardsVerification
0 · ExplainSummarize pasted output, explain a symptom from the lessonsNone. No database login and no network pathNoneRemove secrets and personal data before pasting. Label the answer as uncheckedThe reader checks the claim in the docs or with a read-only check
1 · ReadConnection counts, lock chains, top statements, replication lag, cloud metrics and eventsA read-only login: pg_monitor, read-only session, timeouts. Read-only cloud roleNone per check. People approve the list of checks onceFixed, parameterized queries, no free SQL, row limits, the five-connection cap, a deny list as a second checkEach result shows the query and the time. Tests confirm a write attempt is refused
2 · Low-risk, reversiblePost a summary, open a ticket, pause your own batch job. Database changes only if a policy names themA separate login with the one right it needsOnly for actions a written policy allowlists in advance. Otherwise treat it as tier 3Rate limit, cooldown, one at a time, a hard ceiling on size, an alert on every runA read-only check shows the intended effect. Stop at the first miss
3 · DisruptiveCancel or end a session, take a replica out of a read pool, scale, change a setting, add an indexAn executor login with only the needed right. pg_signal_backend cannot signal superuser sessionsA named person approves the exact commandPreview with target, command, why, risk and undo. Precheck again at apply. One change at a time. A limit on how many sessions or objects one change may touch. A stop controlA read-only check must pass after the change. If not, the agent stops and escalates
4 · High consequenceFailover or promotion, forced quorum, rebuilding a member, deleting data or replication state, privilege changes, arbitrary SQL writesNot granted by defaultDisabled. A person runs it from a documented process, with a second personThe DBA agent refuses these unless the operator passes --allow-high-risk, and then each needs the target's name typed back. For a pilot, leave the flag offA person verifies against the runbook, not the agent
A tier is not a safety ratingRisk depends on the target, the workload, the platform, the time and what the business is doing. Ending an idle session left by a reporting tool at night is not the same as ending one in the middle of a payment at the end of the month, and both are "tier 3". Building an index is reversible and still can saturate a disk on a busy primary. Treat the tier as the minimum control. The preview, the precheck and the person decide whether this action, now, is safe.

How the DBA agent maps to the tiers today

What it doesTierControl
Playbook read steps, HA status reads1Read-only session, timeouts, deny list
End an idle-in-transaction session, cancel a query, add an index3Change request, named approver, precheck, separate login, verify, audit line
HA changes (switchover, rejoin a node)3Typed approval, read-only check after each change, JSONL audit log
Failover, forced quorum, rebuild, forced replica set config, Orchestrator recover4Off. Needs --allow-high-risk and the target's name typed back
Drop an inactive replication slot4 under this modelThe agent can propose it, with a named approver. It deletes replication state, so a pilot should leave it out of the allowed fixes, or require a second reviewer

The DBA agent asks a person for every fix. It does not use tier 2 for database changes. Tier 2 is a policy option for teams that choose it.

5 · A hard PostgreSQL connection limit

Five server connections for the agent, in total

The agent should be unable to take more than five PostgreSQL server connections, however many workers or replicas run, and unable to raise that number itself. A setting in the agent's own code or pool size does not do that: a bug, a second replica or a script that opens its own connection walks around it. The limit has to be enforced where the agent cannot reach it, at the database boundary. Four layers do that together.

  1. One dedicated login role, not a superuserNever reuse an application role or a DBA role. A superuser is exempt from CONNECTION LIMIT, so a superuser agent has no cap at all.
  2. CONNECTION LIMIT 5 on that role, as the backstopPostgreSQL refuses the sixth normal connection for the role, across all databases. The documentation says the limit is enforced only approximately: if two sessions start at the same moment with one slot left, both may fail. That fails closed, not open. Prepared transactions and background workers do not count. CREATE ROLE
  3. All agent traffic goes through a poolerPgBouncer with max_user_connections = 5 keeps the role at five server connections across all its pools and databases. Use a dedicated PgBouncer for agents, so its queue is the agent's queue only.
  4. The network refuses everything elseOnly the pooler's address may reach PostgreSQL as this role. A direct connection then fails at the network or in pg_hba.conf, and the role limit is the last line even if it does not.

Server limits and client limits are different things

PgBouncer has two kinds of limit, and mixing them up is the common mistake. A server connection is a real PostgreSQL backend. A client connection is a worker talking to PgBouncer. Many clients can share few servers: that is the point of a pooler. Queued clients wait inside PgBouncer and are not PostgreSQL connections.

SettingKindWhat it bounds
max_user_connectionsServerServer connections per user, across all databases. This is the cap
default_pool_sizeServerServer connections per user and database pair. Alone it is not the cap: two databases mean two pairs
max_db_connectionsServerServer connections per database, whatever the user. Useful when the agent has its own database
max_client_connClientClient connections the whole PgBouncer process accepts, any user. This bounds the queue. A dedicated PgBouncer makes it the agent's queue
max_user_client_connectionsClientClient connections per user. Added in PgBouncer 1.24.0, so it is not in 1.22
query_wait_timeoutQueueSeconds a query waits for a server connection. After that, PgBouncer disconnects the client. The default is 120, and 0 means wait forever, so set it

Checked against the PgBouncer configuration reference and the changelog, Nov 30, 2026.

Set it up

state-changing Run once by a DBA. PostgreSQL 16. Self-managed, and on RDS, Aurora and Cloud SQL as the admin user the service gives you, which is not a true superuser there.

CREATE ROLE dba_agent LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION
  CONNECTION LIMIT 5;                          -- set the password from your secrets manager
GRANT pg_monitor TO dba_agent;                 -- statistics and settings views, no table data
ALTER ROLE dba_agent SET default_transaction_read_only = on;
ALTER ROLE dba_agent SET statement_timeout = '5s';
ALTER ROLE dba_agent SET lock_timeout = '1s';

Impact: only affects the new role. default_transaction_read_only is a guard rail, not a lock: a session can switch it back. The real limit is that the role owns nothing and holds no write privileges. The executor login is a second role with its own limit, covered below. Docs: predefined roles.

state-changing Self-managed only: pg_hba.conf, then a reload. First match wins, so the reject line goes after the allow line. On RDS, Aurora and Cloud SQL you cannot edit this file: use security groups or VPC firewall rules so that only the pooler's address reaches port 5432 for the agent.

# only the pooler host may connect as dba_agent
host  all  dba_agent  10.0.5.20/32  scram-sha-256
host  all  dba_agent  0.0.0.0/0     reject

Add the same pair for IPv6 if you use it. Docs: pg_hba.conf.

PgBouncer, a dedicated instance for the agent. state-changing config. Version labeled: the limits below were tested on PgBouncer 1.22.0 with PostgreSQL 16.

; pgbouncer.ini  (tested on PgBouncer 1.22.0)
[databases]
app      = host=db-primary port=5432 dbname=app
postgres = host=db-primary port=5432 dbname=postgres

[pgbouncer]
pool_mode            = transaction   ; a server connection is held only for one transaction
max_user_connections = 5             ; SERVER connections per user, all databases: the cap
default_pool_size    = 5             ; per user/database pair, so this alone is not the cap
max_client_conn      = 20            ; CLIENT connections this process accepts: the queue bound
query_wait_timeout   = 3             ; seconds a queued query waits before it is dropped
reserve_pool_size    = 0             ; the default: no extra connections
auth_type            = scram-sha-256 ; the sandbox used trust. Do not
auth_file            = /etc/pgbouncer/userlist.txt
admin_users          = pgb_admin     ; not the agent's role

Assumptions: the agent uses one role, so max_user_connections is the cap. Transaction pooling does not keep session state between transactions, so set the read-only and timeout settings on the role, as above, not per session. Client numbers (20 and 3 seconds) are what the test used. Choose yours from how many workers you run. On 1.24.0 or later you can instead set max_user_client_connections on a shared PgBouncer. A server connection that sits idle in the pooler still counts against the role's limit (see the measurement below), so lower server_idle_timeout if you need those slots back sooner. Its default is 600 seconds.

What happens under load

When five server connections are busy, new work waits in the queue, up to max_client_conn clients and up to query_wait_timeout seconds. When the queue is full, new clients are refused at connect. Nothing opens a sixth connection to PostgreSQL. The agent has to treat both outcomes as "busy", not as an error to push through.

Measured, in a test sandboxPostgreSQL 16 and PgBouncer 1.22.0, with the ini shown above except that the sandbox used auth_type = trust. Role dba_agent with CONNECTION LIMIT 5. 30 workers, each running SELECT pg_sleep(2), split across two databases, all at the same time.
What was measuredResult
Peak server connections for dba_agent in pg_stat_activity5
Workers that finished10
Workers that queued, then got query_wait_timeout10
Workers refused at connect with no more connections allowed (max_client_conn)10
Total timeabout 4 seconds
Then 7 direct connections to PostgreSQL as dba_agent, bypassing the poolerThe first was refused: FATAL: too many connections for role "dba_agent"
How to read itThe cap held at five even though 30 workers asked at once. Twenty clients were allowed in (max_client_conn = 20) and ten were turned away at the door. Of the twenty, ten ran in two waves of five, two seconds each. The other ten waited past the three-second limit and were dropped (derived from the settings, not separately measured). The direct connection was refused because PgBouncer's five idle server connections already used the role's limit. That is the backstop working, and it also shows that your own break-glass access must use a different role.

Retries: capped, backed off, with jitter

A refused or timed-out request is retried a few times, with a delay that grows and is randomized, so that many workers do not come back at the same moment. These numbers are an example, not a measurement.

attempt 1: now
on "no more connections allowed" or query_wait_timeout:
  wait a random time between 0 and min(8 s, 0.5 s x 2^attempt)     (full jitter)
  at most 3 retries
after the last retry: report "busy, try again in N seconds", mark the check "deferred"
after 3 busy answers in a row: stop sending for 60 s (circuit breaker)

Also keep a local limit of 4 in-flight checks inside the agent. That is a courtesy that keeps the queue short. It is not the cap. The cap is the four layers above.

Check it, and alert on it

read-only PgBouncer admin console, connect to the pgbouncer database as an admin or stats user. Any platform. The column names come from the current PgBouncer docs. Run the command on your version to see which it shows.

SHOW POOLS;    -- per database and user: cl_active, cl_waiting (the queue), sv_active, sv_idle, maxwait
SHOW USERS;    -- per user: max_user_connections, current_connections (server), current_client_connections

read-only PostgreSQL, any platform. Run as a role in pg_monitor, or you will not see other roles' sessions in full. Docs: pg_stat_activity.

SELECT usename, application_name, state, count(*)
FROM pg_stat_activity
WHERE usename = 'dba_agent'
GROUP BY 1, 2, 3;

SELECT rolname, rolconnlimit, rolsuper FROM pg_roles WHERE rolname = 'dba_agent';
SignalWhere to read itA starting alert (tune it)
Agent server connectionsSHOW USERS current_connections, or pg_stat_activityAt 5 for more than 5 minutes. Touching 5 in a burst is normal
Queue depthSHOW POOLS cl_waitingAbove 0 on consecutive scrapes
Queue waitSHOW POOLS maxwait (seconds the oldest client has waited)Over half of query_wait_timeout
Rejected or dropped workAgent tool errors, PgBouncer logAny rise. Show it to the operator as "checks deferred"
Bypass attemptsPostgreSQL log, too many connections for role, or a connect from an address that is not the poolerPage security. It means something is going around the pooler

When the cap is not a global cap

  • Only if every worker uses that role. A per-role limit counts a role. A second login, even a read-only one, has its own limit. Two roles at 5 each is a cap of 10.
  • The executor login is a second role. Split the budget: for example 4 for the reader and 1 for the executor, so the limits add up to 5. Set each role's CONNECTION LIMIT, give each user its share in PgBouncer (SHOW USERS reports a max_user_connections per user, and the configuration reference has the per-user form), and send both through the same pooler.
  • Two poolers are two caps. Independent PgBouncers each hold their own five. Give each a share that adds up to five, or run one pooler, with a standby that takes over, not two live ones.
  • It must not be bypassable. If the network lets an agent replica reach PostgreSQL directly, the role limit is the only thing left. Test it: from the agent's network, connect straight to 5432 and confirm it fails.
  • Superusers are exempt. That is why the agent's roles are never superusers.
  • The role must exist where you fail over to. Check the role and its limit after a restore or a logical migration. Do not assume they came along.
  • In an exhaustion incident the agent competes with the app. Ordinary roles cannot use the slots reserved for superusers (superuser_reserved_connections). If the app has taken every slot, a new agent connection fails too. A warm pooled connection (min_pool_size = 1) helps, and a human's break-glass role is the fallback. Connection settings
The trade-offThe cap protects the database and costs the agent speed. During a burst, checks queue or are refused, and an investigation takes longer. That is the right trade, because an agent that opened more connections to finish faster would be adding load to a database that is already in trouble. So the agent must degrade, not push: run the most useful check first, defer optional ones, show cached evidence marked stale, tell the operator "5 of 5 connections in use, 3 checks deferred", and never open a connection another way or ask for a higher cap.
6 · Operator experience

A calm incident workspace, and a simulation of one

The agent is useful in an incident when it connects evidence to a decision, not when it talks. This is the design. The DBA agent does not have this interface today. The demo below is a simulation with scripted data.

  • Timeline. Alerts, evidence collected, deploys and changes, hypotheses, decisions and outcomes, in time order.
  • Summary. User impact, affected database and environment, known facts, uncertainties, and the single safest next check.
  • Evidence cards. Each claim links to its source: a metric, a query result, a log line, a deploy or a runbook step, with the time collected and a flag when it may be stale.
  • Ranked hypotheses. A confidence, the evidence for and against, and a "Why?" that opens the supporting evidence.
  • Next-action preview. The exact target and command, the expected result, the downside, who must approve and how it will be verified.
  • Handoff summary. A short text for the incident channel or ticket, with sensitive values removed.
  • What changed? Symptoms lined up with deploys, config changes, traffic shifts, failovers and maintenance.
ModeWhat it doesNeeds a database?
LearnExplains a symptom or concept and links to the lessonsNo
InvestigateRuns approved read-only checks and builds an evidence-backed diagnosisRead-only access. The demo uses none
ActProposes, or runs only what the policy allows, after showing the preview and getting approvalYes, with a separate executor login

Try it: investigate an incident

Pick an incident. Start in Investigate, run a few checks, open "Why?" on a hypothesis, then go to Act. Try the "Symptoms get worse" outcome and the Stop button. Everything is scripted and nothing is connected.

Simulation: no database is connected. Every result here is scripted.

7 · End-to-end incident workflow

Alert to verified outcome

  1. AlertIt arrives as data. A duplicate of an open incident is attached to it, not started again.
  2. Gather read-only evidenceApproved checks only, inside the connection cap. Each result is stored with its source and time.
  3. Identify the target and the scopeWhich cluster, which environment, which services. If this is unclear, stop and ask.
  4. Rank hypothesesEach with the evidence for it, the evidence against it, and what is still unknown.
  5. Recommend a bounded actionOne action, the smallest that tests or fixes the leading cause.
  6. Preview the impactTarget, command, expected result, downside, undo, verification.
  7. Get approvalA named person, for tier 3 and above. Tier 4 goes to the human process.
  8. Execute through a constrained toolAfter a fresh precheck. A separate login, one action, the same connection cap.
  9. VerifyA read-only check that proves the effect, and watches the symptom for a few minutes.
  10. Update the record or escalateWrite the outcome, the audit line and the handoff, or page a person.
Branch: not enough evidenceThe agent says what it lacks and which check would add it. If the checks cannot run, because the cap is full or a tool is down, it says "deferred", hands the playbook to the on-call person and offers no action. Guessing a fix to fill the silence is the wrong move.
Branch: the action makes it worseThe verification fails or the symptom grows. The agent stops. It does not try a second action, does not ask for broader rights and does not retry. It writes the audit line, shows the undo step and pages the on-call person. Some changes have no undo, such as ending a session. The preview said so before the approval.
8 · Worked example

PostgreSQL connection exhaustion after a deploy

Checkout is failing with "sorry, too many clients already". This is the same incident the simulation runs, with the real commands. The numbers in the simulation are scripted, not measured. Commands are for PostgreSQL 16 and work on self-managed servers, RDS, Aurora and Cloud SQL unless a note says otherwise.

1. Read-only evidence

read-only Connections against the limit. Any platform. Prerequisite: pg_monitor. Impact: a read of the statistics view.

SELECT count(*) AS in_use,
       current_setting('max_connections')::int AS max_connections,
       current_setting('superuser_reserved_connections')::int AS reserved
FROM pg_stat_activity WHERE backend_type = 'client backend';

read-only By application and state. The oldest transaction start shows who is holding slots.

SELECT application_name, state, count(*), min(xact_start) AS oldest_xact
FROM pg_stat_activity WHERE backend_type = 'client backend'
GROUP BY 1, 2 ORDER BY 3 DESC;

read-only Who blocks whom. Query text can hold customer values: the agent keeps a fingerprint and drops the literals before it stores or posts anything.

SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, state,
       now() - xact_start AS xact_age
FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;

read-only Top statements. Needs the pg_stat_statements extension (available on RDS, Aurora and Cloud SQL, loaded through shared_preload_libraries on self-managed servers). PostgreSQL 13 and later use mean_exec_time. Older versions call it mean_time.

SELECT queryid, calls, round(mean_exec_time::numeric, 1) AS mean_ms
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;

Plus two reads outside the database: the request rate for the same hour last week, and the deploy and config change log. Docs: monitoring statistics.

2. Telling the five causes apart

CauseWhat you seeThe check that separates itWhat rules it out
Traffic increaseRequests and statement calls rise togetherRequest rate against the same hour last week, and statement callsRequest rate is flat
Retry stormStatement calls rise while requests stay flat. Many connection attempts a secondCalls against requests. Connection attempts, if log_connections is onCalls follow requests one to one
Bad query planOne statement's mean time jumps. CPU is high. Connections are normalpg_stat_statements by queryid, then EXPLAINStatement times are unchanged
Lock waitSessions wait on a lock, CPU is low, one blocker is idle in a transactionpg_blocking_pidsNothing is waiting on a lock
Pool problemConnections near the limit, mostly idle or idle in transaction. Pods times pool size passes the limitConnections by state and application, the deploy diff, whether a pooler existsConnections are low, slots are free

In this incident the evidence points at a pool problem made worse by retries, with a lock chain on top. Six pods of 40 connections is 240 possible connections against 197 usable (derived). The traffic and plan hypotheses are ruled out.

3. What the agent does at each level

  • Recommends: reduce the pool size or add a pooler for checkout-api, and look at the 14:02 deploy. It hands the rollback to the service owner, because the deploy tool is not one of its tools.
  • May do without asking: run the read-only checks, post the evidence summary, page the owner. It changes nothing in the database.
  • Needs approval (tier 3): ending the one session that blocks nine others. The preview names the session and says the transaction rolls back.
  • Never, in this guide's model: raising max_connections (a restart, more memory, hides the cause), raising its own cap, ending all 151 idle sessions at once (the blast radius is above the limit of 5 sessions per change).

state-changing The approved action. Self-managed: the role needs pg_signal_backend or must own the session. On RDS, Aurora and Cloud SQL, use the role your provider allows to signal other sessions, and check its docs. Neither can signal a superuser's session. Impact: the session ends, its open transaction rolls back, the app sees a connection error and may retry. It cannot be undone.

SELECT pg_terminate_backend(48213);

Precheck at apply: the same pid still has the same backend_start and xact_start, is still idle in a transaction and still blocks others. Process IDs are reused, so the pid alone is not enough. If any differs, the answer is "stale" and nothing runs. Prefer pg_cancel_backend for a running query. It cancels the query and leaves the session. It does nothing for a session idle in a transaction. Docs: server signaling functions.

4. The five-connection cap during the incident

The agent has six checks to run. It keeps at most 4 in flight, and PgBouncer allows 5 server connections. If another worker is also using the role, a check waits in the queue for up to 3 seconds. If the queue is full, it is refused, and the agent shows "checks deferred" instead of trying a side door. It does not need more connections to finish: each check is short.

5. What to verify afterwards

  • The lock query returns no waiters. Connections in use and the error rate are falling, not just the blocker count.
  • Idle-in-transaction sessions are not growing back. If they are, the cause is still open.
  • The agent's own connections never went above 5 (SHOW USERS), and no check was refused for longer than expected.
  • Follow-ups sit with people: the pool size, a pooler for the app, and idle_in_transaction_session_timeout on the application role.
9 · Guardrails and failure modes

What can go wrong, and what limits it

Each guardrail has a limit of its own, so none of them is enough alone. Approval can be rubber-stamped. A read-only session can still run a query that loads the server. Logging records a mistake after it happens. A tier label does not know what the workload is doing right now.

RiskGuardrailWhere it falls short
Wrong identitySeparate identities per environment and purpose. Least privilege. Short-lived credentialsA leaked credential works until it expires. The network and the role limit still apply
Arbitrary executionAn explicit tool allowlist. Parameterized commands. No shell and no free SQLOne "run this query" tool undoes the whole list
Disruptive changeApproval workflow with a preview, by a named personPeople approve what they do not read. Keep requests few and the evidence next to the command
Stale or wrong targetRe-validate the target and the evidence right before the action. Check backend_start, not just the pidCheck and action are not one atomic step. Keep each action small and idempotent
Duplicates and stormsDedupe alerts by fingerprint. One open change per target. Rate limits, timeouts, no automatic retry of a changeA bad fingerprint hides a second real incident
Prompt injectionTreat logs, SQL comments, ticket text, row values and runbooks as data. Text cannot add a tool or change a policy. The model never holds credentials, and the policy engine, not the model, decides what is allowedYou cannot prove a model will never follow hostile text. So no path to a change depends on the model alone
Data exposureTenant isolation. Fingerprints and counts, not row values. Redact before storing or postingQuery text and error messages can still carry values. Test the redaction
Model or tool outageThe agent is optional. Alerts still page people. The playbooks work without itPeople lose the speed-up. Practice without it
Wrong diagnosisShow the evidence for and against. Track the false diagnosis rateA confident wrong answer is still persuasive
Partial executionOne action at a time. Verify after each. Stop at the first failure. State the undo, or "none", in the previewSome changes cannot be undone
Runaway agentA kill switch that stops every tool, and a way to disable the logins (ALTER ROLE dba_agent NOLOGIN stops new logins, so end the open sessions too)It only helps if someone knows it exists. Practice it
No recordAn audit trail: who approved, the command, the target, the evidence, the result. Credentials and query literals redactedAn audit log the agent can edit proves little. Write it somewhere it cannot
Untested behaviorReplay past incidents, run simulations, and in production start in shadow mode where the agent proposes and people comparePast incidents are not tomorrow's. Keep adding cases
Operator is stuck with itThe operator can inspect, reject, edit or stop any proposalOnly works if the controls are one click away
Silent failureAn unavailable action says why: "needs this right", "not enough evidence", "cap is full"A silent skip looks like "nothing to do"
10 · Operational readiness

A checklist, with owners

DB ops database operations, Platform platform and security, Service the teams that own the applications.

Before the pilot

  • DB opsThe agent role exists with CONNECTION LIMIT 5, is not a superuser, and owns nothing
  • PlatformOnly the pooler can reach PostgreSQL as that role. A direct connection from the agent's network was tried and failed
  • PlatformSecrets sit in a manager, and are short-lived where the platform supports it
  • DB opsThe list of read-only checks is reviewed, and runs in staging first
  • ServiceEach service has an owner and a named approver
  • DB opsThe kill switch was tested
  • DB opsShadow mode: the agent proposes, people decide, nothing executes

Before production

  • DB opsEach action has a tier, a target limit and a written undo
  • PlatformThe audit log goes where the agent cannot edit it
  • DB opsAlerts exist for agent connections, queue depth and queue wait
  • ServiceApprovers are on call, and know what they are approving
  • DB opsPast incidents were replayed, and the misses reviewed
  • PlatformA prompt-injection test: hostile text in a SQL comment, a ticket and a log line
  • DB opsThe "action makes it worse" path was rehearsed

After rollout

  • DB opsReview proposals, rejections and overrides every week
  • PlatformReview roles, the allowlist and the network path every month
  • DB opsReplay the incidents again after any model or tool change
  • DB opsRemove any action with low acceptance, or one that was ever unsafe
  • ServiceFix the causes the agent keeps finding, not just the symptoms
  • DB opsCompare the cap with the peak you see. Change it only through review

Signals to track

These are suggested definitions. This site has not measured them for any real deployment.

SignalHow to count itWhat to look for
Unsafe-action rateActions a reviewer says should not have been proposed or run, divided by actions proposedZero for executed actions. Any miss triggers a review
Acceptance and override rateProposals approved as written, and proposals rejected or editedNear-100% acceptance with fast approvals may mean nobody is reading
False diagnosis rateIncidents where the leading hypothesis was wrong at closeBy incident type. A rising trend after a change
Time to mitigationAlert to verified mitigationAgainst the same incident type before the agent
Post-action regressionsActions followed by a failed verification or a related alert in a set windowAny, and what the precheck missed
Agent connections, queue depth, rejected workSHOW USERS, SHOW POOLS, agent tool errorsThe cap is hit often: the checks are too heavy, or too many run at once
11 · Review of the playbook suggestions

"An agent can" is not permission

The playbooks have an "Automate it" list on each page. I went through every line that says an agent could act and classified it. Four classes: Observe (reads), Recommend (writes a proposal for a person), Approval-gated (a change a person approves), Strict policy (potentially automatable only under a written policy). A line that says "an agent can" describes what is possible. It never grants autonomous production changes. Where the wording promised more than that, I changed it at the source: the playbooks and runbooks.json.

SuggestionClassPrerequisitesImpactApprovalVerification
Collect and post evidence: the one-minute snapshot (CPU), top reader (I/O), logs from before a restart (memory), Patroni and kernel logs after a failover, RDS events, pod describe and logs, cluster.status(), replica set voters and oplog window, etcd health, plan comparison, big-key sample, Cassandra repair history, nightly recall testObserveRead-only login, timeouts, approved checks. For Redis, sample on a replica with commands that do not blockA small read load. Text may carry sensitive values, so redactNone per run. People approve the check list onceThe post shows the command and the time
Find the head blocker and post who it isObserveAs aboveA readNoneThe blocker is named with its age and what it holds
Track wraparound age and open a ticket. Open Cassandra repair ticketsRecommendWrite access to the ticket system only, not the databaseA ticketNone. A person owns the ticketDedupe by fingerprint, so there is one open ticket
End sessions idle in a transaction past a thresholdApproval-gated. Strict policy only through idle_in_transaction_session_timeoutExecutor login with pg_signal_backend. A precheck on pid and backend_start. A limit on sessions per changeOpen transactions roll back. The app sees errors and may retryA named person. For no person at all, a DBA sets the timeout on the application role, and the database does itSessions gone, locks gone, error rate down
Grow a cloud volume by a fixed step when time to full is shortStrict policy, otherwise approval-gatedOne fixed step, a hard ceiling, a cooldown, an agreed cost owner, and a notice to a personCost goes up. Growing is usually one way, so check your providerPre-approved by policy, or a personFree space and time to full recomputed. The volume reports the change complete
Take a replica out of the read pool on lag, and put it backApproval-gated. Strict policy with limitsNever the last healthy replica. A delay before putting it back. A limit on runs per hourThe other replicas and the primary take more load. Routing changesA person, or a policy that has the limits aboveLag recovers, other nodes cope, errors do not rise
Pause a batch job when lag or disk latency risesStrict policyThe job owner builds the guard into the job. A rule for resumingThe job runs late. The database is not changedNone. It is the job owner's own codeLag falls and the job resumes
Cancel a DDL that waits on a lockApproval-gated. Better: lock_timeout in the migrationThe migration sets a few seconds of lock_timeout itselfThe DDL fails and must be retried at a quiet timeA person for a tool-side cancel. None for the timeout, set in code reviewThe queue behind the DDL clears
Run ANALYZE after a bulk jobStrict policyA step of the job, run by the job's own login, on named tablesA short read load. Plans may changeNone, owned by the jobThe table's statistics time is new
Prepare the async switch when a sync standby is deadRecommend. The switch is a person's decisionThe data-loss window stated in the proposalLower durability from then onA person, ideally twoWrites continue. Replication state is checked
Propose removing an InnoDB Cluster member with a growing applier queueRecommend. An HA change, so a person decidesClear evidence, and the plan that --dry-run showsCluster capacity and quorum changeTyped approval in the DBA agentThe cluster status is healthy afterwards
Pre-deploy check that blocks a deploy, and a CI plan checkStrict policy (a CI gate)The service team owns the check. It runs on a copy of statisticsA deploy is blocked or flaggedNone. It is the team's own pipelineThe check ran on every deploy
Patroni remove_data_directory_on_rewind_failureNot an agent. A configuration choiceDecided on purpose by the cluster ownerIt deletes the data directory on a failed rewindPart of the config reviewTest it in a rehearsal
12 · The assistant page

A documentation lookup is not an operations agent

The site's MCP server answers questions from this site's pages: which database, how big, a query review, which lesson. It never gets a connection string and cannot run anything on a database. review_query reads SQL you paste and applies the Query coach rules to the text. It is built and works on a local machine, but the download is not published, so there is nothing to install yet. For an assistant that reads the web, llms.txt is live today.

13 · Related pages

Read next

SourcesChecked against the primary documentation on Nov 30, 2026: PostgreSQL CREATE ROLE (CONNECTION LIMIT), predefined roles, server signaling functions, monitoring statistics, pg_hba.conf, connection settings; PgBouncer configuration, admin console commands and changelog. The connection test is the measurement above. The simulation and the retry numbers are illustrative.
Part 4 of 4 · Operate · 21 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.