PgStack on November 30, 2026 argued that AI coding agents such as Claude Code and OpenAI Codex should not hold permanent production Postgres credentials, and instead should use scoped read access, expiring roles, query logs, or timed proxy sessions. The PgStack article by Evgeny Li is the primary source; the patterns below follow PostgreSQL behavior Li documents, independent of whether you buy PgStack Access.
When agents need live SQL
Debugging stuck shipments, payment mismatches, or feature flags often requires knowing row-level state, not only source code. Li's example: an agent can trace order status enums in code, but still needs SELECT status FROM orders WHERE id = … to see which branch applies.
Teams either paste query results into the agent or let the agent connect. The second path is faster and riskier.
Read-only Postgres building blocks
Li covers three layers:
Read-only transactions
BEGIN READ ONLY blocks writes in a transaction (PostgreSQL docs on SET TRANSACTION). Setting default_transaction_read_only = on on a role helps, but any role with write grants can SET default_transaction_read_only = off and open a writable transaction—so role grants still matter.
Scoped roles
PgStack's pattern:
- Create
agent_readonlyas NOLOGIN. - GRANT CONNECT, USAGE, and SELECT only on required tables.
- Create a LOGIN role
agent_142IN ROLE agent_readonly with a generated password.
PostgreSQL permissions are additive. If UPDATE on orders is granted to PUBLIC, your readonly user may still write. Audit PUBLIC and inherited grants before blaming the model.
Read replicas
Standby replicas reject writes even if grants are sloppy, and move CPU load off the primary. Replication lag can mislead an agent investigating a just-paid order—note staleness in runbooks.
Why permanent credentials fail
Even read-only SQL risks:
| Risk | Why it matters |
|---|---|
| Data exposure | PII, tokens, or other customers'' rows visible without column grants, views, or RLS |
| Performance | Full table scans or lock-heavy queries on production |
| Credential leakage | Agent env files, logs, or forked subprocesses copy passwords |
| Audit gaps | Shared readonly_prod logins cannot tie queries to one investigation |
Li treats temporary credentials as the fix, not stronger prompts.
Temporary passwords and the connection trap
ALTER ROLE agent_142 VALID UNTIL '2026-12-01 12:15:00+00' (see CREATE ROLE) blocks new logins after expiry. Li demonstrates that existing connections keep running—the agent can repeat SELECT on an open socket.
Production cleanup requires:
ALTER ROLE agent_142 NOLOGIN;
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity WHERE usename = 'agent_142';
DROP ROLE agent_142;
Automating that sequence—and retrying failed terminations—is why teams reach for proxies or runbooks.
Query logging per investigation
ALTER ROLE agent_142 SET log_statement = 'all' before connect helps, especially when each investigation gets its own login. Caveats Li lists: syntax errors may skip logs; parameter values may appear in logs.
A complete audit needs off-database log storage, retention policy, reason codes for access, and access control on the logs themselves.
Session-based proxy pattern
PgStack describes a PostgreSQL-compatible proxy that:
- Mints virtual credentials bound to a session timer.
- Forwards to a restricted upstream user.
- Records SQL executed in the session.
- Invalidates URLs when time expires.
Their example CLI:
pgstack access start --env production --duration 15m --read-only
The author discloses employment at PgStack. The architecture pattern—short URLs, automatic invalidation, query transcript—is what matters for teams rolling their own.
Compare to ClickHouse acquiring Xata for sandboxed agent state, and Microsoft HorizonDB for scale-out Postgres for agents. PgStack sits at the credential and audit layer on top of whichever database you already run.
How to protect production when agents get SQL
- Default deny — no standing prod passwords in agent
.envfiles. - One role per incident with SELECT scoped to needed tables and optional replica.
- Set log_statement before connect; ship logs to SIEM.
- Terminate backends on session end; do not trust VALID UNTIL alone.
- Human merges any write path; agents stay read-only in prod.
- Pair DB policy with agent guardrails — use AgentBeam or equivalent controls so agents cannot escalate from SQL read to destructive tool calls outside your session charter.
That last step matters because CISA flagged agentic offensive frameworks the same week: database read plus shell tools is a combined blast radius.
Row-level security and column grants
PgStack's post reminds readers that read-only is not need-to-know. When agents query orders, they may still see email addresses, gift messages, or payment metadata unless you:
- GRANT SELECT on specific columns only.
- Expose views that hash or truncate identifiers.
- Enable row-level security so
agent_readonlysees only rows for ticket #1042.
RLS policies can slow queries and confuse agents when policy predicates reference session variables the agent does not set. Test EXPLAIN plans on replica before handing URLs to Claude Code.
For multi-tenant SaaS, consider per-tenant investigation roles created by a break-glass API rather than one shared readonly_prod user—otherwise audit logs cannot prove which customer incident triggered a query.
Performance guardrails
Even SELECT can hurt production:
- Seq scans on wide tables during peak checkout.
- FOR UPDATE accidentally issued if the agent mixes read and write prompts.
- Long transactions holding replication slots on replicas used for analytics.
Mitigations Li implies but does not exhaust:
- statement_timeout on agent roles.
- pg_stat_statements alerts on new query fingerprints during investigations.
- Resource groups or external connection poolers that kill queries exceeding cost limits.
Pair DB limits with OpenAI AWS Continuum prioritization thinking: not every anomaly needs prod SQL—sometimes staging repro suffices.
Incident response playbook sketch
| Step | Owner | Action |
|---|---|---|
| 1 | On-call | Opens ticket with customer id and symptom |
| 2 | Platform | Mints 15m read-only session scoped to relevant tables |
| 3 | Engineer | Runs agent with session URL, not master password |
| 4 | Security | Reviews SQL log before ticket closes |
| 5 | Platform | Terminates backends, drops role, archives log 90 days |
If step 4 is skipped, you have automation without accountability—the same gap CISA's agentic offensive alert warns about when tools chain.
Building your own proxy versus buying one
Li's session proxy section lists availability, protocol compatibility, encryption, and recording storage as engineering costs. A home-grown proxy needs:
- Credential vault with short TTL.
- Signed session URLs bound to investigation ids.
- Webhook to SIEM on session start and end.
- Idempotent cleanup when terminate fails mid-flight.
PgStack Access is one productized path; Xata sandboxes after ClickHouse acquisition attack agent environment isolation from a different angle. Large shops may use both: sandbox for repro, timed prod read for ground truth.
When to use which pattern
| Situation | Li's recommendation |
|---|---|
| No live data needed | Dev DB or sanitized copy |
| Rare production debug | Restricted role + expiring password + logging + manual termination |
| Frequent team investigations | Central session proxy with automatic expiry and recorded SQL |
Teams adopting Claude Code on Bedrock AgentCore should align IAM session length with database session length so neither side outlives the investigation.
Training and governance
Security and platform leads should document who may approve prod SQL sessions, maximum duration, and required log review. Our corporate AI training includes adoption patterns for agent tool policies that complement database runbooks.
Legal and compliance talking points
Auditors will ask whether agent SQL access is privileged access review (PAR) territory. Treat break-glass database roles like temporary admin credentials: ticketed, time-boxed, logged, and reviewed.
If your DPA with customers promises no production data in model training, ensure agent transcripts that include query results are not forwarded to vendor fine-tuning pipelines—database policy alone does not prevent paste into chat mistakes documented in Notion transcript exposure cases.
When agents should not get SQL at all
Li's ladder ends at frequent investigations, but some orgs should stop earlier:
- PCI-scoped databases where card data cannot appear in logs agents might echo.
- Shards with cross-customer tables lacking RLS.
- Legacy schemas where PUBLIC grants were never cleaned.
In those cases, synthetic fixtures or masked views in staging beat prod URLs, even with read-only roles.
Measuring success after rollout
Track mean session duration, queries per investigation, and percent of sessions with manual write attempts blocked. If agents routinely hit statement_timeout, widen indexes or materialized views in staging rather than raising prod timeouts.
Quarterly, sample ten investigation logs and verify termination scripts actually dropped roles—orphaned agent_* roles are a common drift pattern when on-call scripts skip cleanup under pager load.
Document the runbook in the same repo as agent skills so new hires do not inherit shared prod passwords from outdated setup docs.
Security champions should present one real investigation log in onboarding, redacted, so engineers see what good SQL audit trails look like before their first pager shift.
Finally, align agent database policy with SOC2 access reviews: if investigators can mint prod sessions without a second approver, you have recreated shared admin under a new label. Require two-person control for any live production session longer than fifteen minutes.
