explainx.ai350K+ learn from us
TrendingAI News TodayExplainx for Business
Pricing
explainx.ai

Upskill in AI — 16 free pathways, live workshops & bootcamps, and 50+ courses from practitioners. Plus the skills, tools, and MCP servers to practice on.

follow us

follow on google

Add explainx.ai as a preferred source

corporate training

support@explainx.ai

get started

Find your pathTake Free Evaluation

community

Join the community

learn

mind: share how you thinkpathways — start freeworkshopsbootcampscoursescompare Explainxcertificationsmock testsexplainx universitycorporate traininglearn skills & mcp

discover

skillsmcp serversexplainx mcpestacktoolsmdx readeragentsllmsdesignsdictionarypeopleagi trackerfelony benchranks

company

aboutvisionmissionteaminstructorsteach on explainxpartnershipscommunityhackathonscareers

content

daily AI newsstate of AI — live resultsblogreleasespromptsgeneratorsresource libraryfor LLMsexplainx.ai kids

solutions

all solutionsdeveloper upskillingmarketing upskillingproduct manager upskillingleadership upskilling

newsletter · weekly

Get AI news, tools, and insights in your inbox.

supportcontactprivacytermsdata rightshow we create contentsubmission guidelines

© 2026 AISOLO Technologies Pvt Ltd

explainx.ai

On this page

  • When agents need live SQL
  • Read-only Postgres building blocks
  • Why permanent credentials fail
  • Temporary passwords and the connection trap
  • Query logging per investigation
  • Session-based proxy pattern
  • How to protect production when agents get SQL
  • Row-level security and column grants
  • Performance guardrails
  • Incident response playbook sketch
  • Building your own proxy versus buying one
  • When to use which pattern
  • Training and governance
  • Legal and compliance talking points
  • When agents should not get SQL at all
  • Measuring success after rollout
  • Related reading
← Back to blog

explainx / blog

AI Agents and Postgres: Why Permanent DB Credentials Fail

PostgreSQL, AI Agents, Security, Claude Code, DevOps

Part of AI Agents

PgStack's Nov 30, 2026 guide explains read-only roles, expiring passwords, query logs, and session proxies so Codex and Claude Code agents never keep permanent production credentials.

Dec 1, 2026·8 min read·Yash Thakker
add explainx.ai
go deep
AI Agents and Postgres: Why Permanent DB Credentials Fail

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.

Daily briefFrom Yash · 350K+ students taught

Catch up on AI

One AI story explained in plain English, plus one thing to try. Every day, free. Unsubscribe anytime.

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_readonly as NOLOGIN.
  • GRANT CONNECT, USAGE, and SELECT only on required tables.
  • Create a LOGIN role agent_142 IN 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:

table · 2 cols
RiskWhy it matters
Data exposurePII, tokens, or other customers'' rows visible without column grants, views, or RLS
PerformanceFull table scans or lock-heavy queries on production
Credential leakageAgent env files, logs, or forked subprocesses copy passwords
Audit gapsShared 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:

sql
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:

bash
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

  1. Default deny — no standing prod passwords in agent .env files.
  2. One role per incident with SELECT scoped to needed tables and optional replica.
  3. Set log_statement before connect; ship logs to SIEM.
  4. Terminate backends on session end; do not trust VALID UNTIL alone.
  5. Human merges any write path; agents stay read-only in prod.
  6. 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_readonly sees 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

table · 3 cols
StepOwnerAction
1On-callOpens ticket with customer id and symptom
2PlatformMints 15m read-only session scoped to relevant tables
3EngineerRuns agent with session URL, not master password
4SecurityReviews SQL log before ticket closes
5PlatformTerminates 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

table · 2 cols
SituationLi's recommendation
No live data neededDev DB or sanitized copy
Rare production debugRestricted role + expiring password + logging + manual termination
Frequent team investigationsCentral 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.

Related reading

  • ClickHouse acquires Xata managed Postgres agent sandboxes
  • Microsoft HorizonDB GA for agents at Ignite
  • Claude Code remote Bedrock AgentCore security controls
  • CISA alert on agentic offensive frameworks
  • Anthropic zero-trust AI agents framework
  • OpenAI Codex cloud browser computer use
Spotted something out of date? Let us know.
Daily briefFrom Yash · 350K+ students taught

Catch up on AI

One AI story explained in plain English, plus one thing to try. Every day, free. Unsubscribe anytime.

  • ✓ Free
  • ✓ One email a day, no spam
  • ✓ Unsubscribe anytime
Yash Thakker

Written by

Yash Thakker

Yash is an AI expert with over 300K learners. Join his workshops →

View Yash Thakker in People in AI →

Related posts

Oct 16, 2026

OpenRouter Armor: A Tool-Call Safety Classifier for Any Model, Claimed vs Verified

OpenRouter launched Armor in beta on October 15, 2026: a classifier between the model and your app that checks every tool call against plain-English rules. The company says it beats Claude Code's auto classifier at a fraction of the cost. We read the docs and separate what is documented from what is claimed.

Oct 9, 2026

REA MCP Server: What Agent Reverse Engineering Changes in Your Setup

REA is an MCP server and CLI that lets Claude Code, Codex, Cursor and other agents inspect binaries, Electron apps, APKs and websites. This post covers what its setup edits, what runtime capture runs, and how to review it before you approve.

Aug 5, 2026

Fable 5 Found a RAT on a Windows PC — What the Viral Reddit Story Actually Shows

A 1.2K-upvote r/Anthropic post claims Fable 5 caught a remote-access trojan that Windows Defender and an earlier Opus check both missed. explainx.ai breaks down what's independently verifiable in the story, what "bypass permissions" mode actually trades away, and why this is not a malware-scanner endorsement.