<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Anurag Jain]]></title><description><![CDATA[Anurag Jain]]></description><link>https://anuragjain-data.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 18 Nov 2026 13:18:07 GMT</lastBuildDate><atom:link href="https://anuragjain-data.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[3 guardrails that stop an AI agent from deleting your BigQuery data (or running up your bill)]]></title><description><![CDATA[Giving an AI agent access to your database feels a bit like handing your car keys to a very confident teenager. It will probably be fine. But "probably" is…]]></description><link>https://anuragjain-data.hashnode.dev/3-guardrails-that-stop-an-ai-agent-from-deleting-your-bigquery-data-or-running-up-your-bill</link><guid isPermaLink="true">https://anuragjain-data.hashnode.dev/3-guardrails-that-stop-an-ai-agent-from-deleting-your-bigquery-data-or-running-up-your-bill</guid><category><![CDATA[bigquery]]></category><category><![CDATA[google cloud]]></category><category><![CDATA[AI]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Anurag Jain]]></dc:creator><pubDate>Tue, 10 Nov 2026 12:52:11 GMT</pubDate><content:encoded><![CDATA[<p>Giving an AI agent access to your database feels a bit like handing your car keys to a very confident teenager. It will <em>probably</em> be fine. But "probably" is not a plan.</p>
<p>I'm a data architect and I work on Google Cloud every day. Lately a lot of people have been building "ask your data" agents: you type a question in plain English, a model like Gemini writes the SQL, runs it on BigQuery, and tells you the answer. It's a genuinely useful thing to build.</p>
<p>But the demo version usually has three holes in it:</p>
<ol>
<li>Nothing stops the agent from running a query that <strong>changes or deletes data</strong>.</li>
<li>Nothing stops one query from <strong>scanning a huge table and costing real money</strong>.</li>
<li>Nothing stops the agent from <strong>looping</strong>, calling the model and the database again and again.</li>
</ol>
<p>Here's how to close all three. None of it is hard, and the whole thing takes about 20 minutes.</p>
<p>The rule of thumb behind all of it:</p>
<blockquote>
<p><strong>Ask "what's the worst thing this agent could do?" Then make that thing <em>impossible</em>, not just discouraged.</strong></p>
</blockquote>
<hr />
<h2>Guardrail 1: Make deleting data impossible, not just "against the rules"</h2>
<p>The first thing most people do is add a check in their tool code like this:</p>
<pre><code class="language-python">def run_query(sql: str) -&gt; str:
    if not sql.strip().lower().startswith("select"):
        return "Error: only SELECT queries are allowed."
    ...
</code></pre>
<p>That's a good start. But be honest about what it is: <strong>a speed bump, not a wall.</strong> Look at this:</p>
<pre><code class="language-sql">SELECT 1; DROP TABLE shop.orders
</code></pre>
<p>It starts with <code>SELECT</code>, so it passes the check. And BigQuery can run multi-statement scripts. A model that has been confused (or tricked by text hidden in your own data) could send exactly that.</p>
<p>You could keep adding rules to the string check, but you'd be playing whack-a-mole. The real fix is to take the permission away entirely.</p>
<p><strong>Run the agent as a service account that is only allowed to read.</strong></p>
<pre><code class="language-bash"># 1. Create an identity just for the agent
gcloud iam service-accounts create ask-your-data-sa \
  --display-name="Ask Your Data agent"

# 2. Let it run query jobs (it needs this to run any query at all)
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
  --member="serviceAccount:ask-your-data-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/bigquery.jobUser"
</code></pre>
<p>Then, in BigQuery, give it read access to <strong>only the one dataset it needs</strong>, not your whole project:</p>
<pre><code class="language-sql">GRANT `roles/bigquery.dataViewer`
ON SCHEMA `YOUR_PROJECT_ID.shop`
TO "serviceAccount:ask-your-data-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com";
</code></pre>
<p>That's it. Two roles, nothing more:</p>
<ul>
<li><strong>BigQuery Job User</strong> lets it <em>run</em> queries.</li>
<li><strong>BigQuery Data Viewer</strong> on one dataset lets it <em>read</em> those tables.</li>
</ul>
<p>Now if the agent ever sends a <code>DROP</code>, <code>DELETE</code> or <code>UPDATE</code>, BigQuery itself refuses with an access-denied error. The permission simply doesn't exist. Your string check is still there to give the model a friendly error message, but it's no longer the thing keeping your data safe.</p>
<p>When you deploy to Cloud Run, attach this service account to the service (<code>--service-account</code> flag), so the agent never runs with your own, much more powerful, account.</p>
<hr />
<h2>Guardrail 2: Cap what a single query can cost</h2>
<p>BigQuery's on-demand pricing charges by <strong>how much data a query scans</strong>, not by how many rows it returns. This trips up a lot of people.</p>
<p><code>SELECT * FROM events</code> on a large table can scan many gigabytes even if you only look at the first ten rows. An agent doesn't know your table sizes, and it will happily write that query.</p>
<p>The fix is one setting: <code>maximum_bytes_billed</code>.</p>
<pre><code class="language-python">from google.cloud import bigquery

client = bigquery.Client()

job_config = bigquery.QueryJobConfig(
    maximum_bytes_billed=1_000_000_000,  # 1 GB hard cap per query
)

rows = client.query(sql, job_config=job_config).result()
</code></pre>
<p>If a query would scan more than 1 GB, BigQuery <strong>refuses to run it</strong> and you aren't charged. The agent gets an error back, and you can tell it (in its instruction) to rewrite the query with a filter or a <code>LIMIT</code>.</p>
<p>Two more things worth doing:</p>
<p><strong>Estimate before you run.</strong> A dry run tells you how much a query <em>would</em> scan, for free:</p>
<pre><code class="language-python">dry = client.query(
    sql,
    job_config=bigquery.QueryJobConfig(dry_run=True, use_query_cache=False),
)
gb = dry.total_bytes_processed / 1e9
print(f"This query would scan {gb:.2f} GB")
</code></pre>
<p>You can log this for every question. It's a great way to spot which questions are expensive.</p>
<p><strong>Set a budget alert on day one.</strong> In the Google Cloud console go to <strong>Billing → Budgets &amp; alerts</strong>, set a small monthly budget and turn on email alerts at 50% and 90%. It takes five minutes. Note that it <em>warns</em> you, it doesn't stop spending. The byte cap is what actually stops a bad query.</p>
<p>And if your real tables are big, <strong>partition them by date</strong>. Then a "last month" question only scans last month's slice instead of the whole table. It's the single biggest cost saver in real projects.</p>
<hr />
<h2>Guardrail 3: Cap how many times the agent can try</h2>
<p>An agent works in a loop. It reads your question, calls a tool, looks at the result, and decides whether to call the tool again. Usually that's two or three steps.</p>
<p>But a confused agent can get stuck: the query fails, it tweaks it, it fails again, it tries again… Every loop costs model tokens and maybe a BigQuery query.</p>
<p>So put a ceiling on it. If you're using Google's Agent Development Kit (ADK), there's a run setting for the maximum number of model calls in one turn. At the time of writing it looks like this (check the ADK docs, because these libraries move fast):</p>
<pre><code class="language-python">from google.adk.agents.run_config import RunConfig

run_config = RunConfig(max_llm_calls=10)
# pass run_config=run_config when you call the runner
</code></pre>
<p>Ten is plenty for a question-answering agent. If it can't answer in ten steps, it should give up and say so, not keep spending.</p>
<p>While you're at it, add two lines to the agent's instruction:</p>
<pre><code>Add LIMIT 1000 to any query that could return many rows.
If a query fails twice, stop and tell the user what went wrong.
</code></pre>
<p><strong>Then log every turn.</strong> For each question, write down three things: the question, the SQL the agent wrote, and the answer. When someone says "it gave me a weird answer", you look at the SQL and see the problem immediately. Without that log you're guessing. On Cloud Run, anything you print shows up in Cloud Logging automatically.</p>
<hr />
<h2>Quick checklist</h2>
<p>Before you let anyone else use your data agent:</p>
<ul>
<li><input disabled type="checkbox" /> It runs as a service account with <strong>only</strong> BigQuery Job User + Data Viewer on <strong>one</strong> dataset</li>
<li><input disabled type="checkbox" /> Every query has <code>maximum_bytes_billed</code> set</li>
<li><input disabled type="checkbox" /> A billing budget alert is switched on</li>
<li><input disabled type="checkbox" /> The agent has a maximum number of steps</li>
<li><input disabled type="checkbox" /> Every question, SQL query and answer is logged</li>
</ul>
<p>None of these make the agent smarter. They make it <strong>safe to be wrong</strong>, which matters more. Your agent <em>will</em> write a bad query one day. With these guardrails, a bad query is just an error message, not a deleted table or a scary bill.</p>
<hr />
<h2>Want to build the whole agent?</h2>
<p>This article is one section of a longer guide I wrote, <strong>Ask Your Data</strong>. It takes you from an empty folder to a live agent on Cloud Run that answers plain-English questions about your BigQuery data. It uses Gemini, ADK, FastMCP and BigQuery, and it's written in plain language, with all the code, evals, troubleshooting and deployment included.</p>
<p>👉 <a href="https://anuragjain0.gumroad.com/l/brviaf">Get <em>Ask Your Data</em> on Gumroad</a></p>
<p>If you just wanted the guardrails, I hope this saved you a bad day.</p>
]]></content:encoded></item></channel></rss>