How to safely let Claude (or any AI) query your production Postgres

When setting up AI agents for analytical tasks, it might be very tempting to ask yourself: “Why not just have Claude connect to my production database and let it do its thing?”. After all, AI is supposed to be smart, efficient, and great at writing SQL, right?

If you’ve considered this, you’re not alone. People are asking this across Postgres and other database user communities, and the looseness with which AI is treated is a new phenomenon. For some reason, we often tend to give AI access more casually than to fellow humans.

Don’t take this lightly. Be as protective of your production database when working with AI as you’d be in any other situation. Your database doesn’t really care who’s at the keyboard.

Here are just two of the biggest risks you should consider when giving AI access to your data:

Destructive writes. If AI can write, it can corrupt your data. If it can drop tables your whole database can go “Kaboom”! Performance and availability. A poorly structured query can lock tables or eat up compute and memory. Your users are not going to like that. All this doesn’t mean don’t use AI on your data. But it does mean that how you wire it up matters a lot.

The safest setup for this use case is a physical replica with a read-only role, statement timeout, and idle-transaction timeout.

A physical replica is your first and primary line of defense. When configured, Postgres will automatically and continuously ship the data from the production primary instance to the replica making it near-up-to-date at all times. AI agents can then connect to the replica and never even touch the primary.

Even better: a dedicated replica specifically for AI agents. This way if AI screws up, only AI is affected; application users, human data analysts or any other users don’t experience any unavailability or performance issues.

The second line of defense is the read-only role and a set of timeouts to prevent write attempts and long-running queries from overwhelming the replica. Simply run these four lines of SQL:

CREATE ROLE ai_readonly LOGIN PASSWORD '...' NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT; -- minimum privileges
GRANT pg_read_all_data TO ai_readonly; -- read anything, no writes
ALTER ROLE ai_readonly SET statement_timeout = '30s'; -- kill long queries
ALTER ROLE ai_readonly SET idle_in_transaction_session_timeout = '60s'; -- release locks fast

And then make sure all AI agents connect exclusively using ai_readonly credentials. That’s it! Your AI tooling can now query real data without putting your database at risk.