All articles
    AI Agents

    How to Deploy AI Agents in Production Safely

    To deploy AI agents in production safely, put every tool behind an allowlist and a sandbox, make write actions idempotent, cap spend per run and per tenant, log every tool call with redacted inputs, and release behind a kill switch to a small traffic slice before going wide.

    Syed Husnain Haider Bukhari
    9 min read

    A prototype agent that works in a notebook and a production agent are different systems. The model is the same. Everything around it changes.

    When teams ask me how to deploy AI agents in production, they usually expect an answer about models. The answer is almost entirely about the code around the model.

    What does it take to deploy AI agents in production safely?

    Safe means four things: the agent cannot take an action you have not explicitly allowed, cannot take it twice by accident, cannot spend past a budget you set, and can be stopped in under a minute. Everything else is implementation detail.

    Almost every agent incident I have debugged was not a model failure. The model picked a plausible tool with plausible arguments and the surrounding system had no opinion about what happened next. A retry loop that fired the same webhook dozens of times. A support agent that messaged the same customer on two channels. A scraper agent that walked past its rate limit and got the account blocked.

    So the work is mostly unglamorous infrastructure. If you are still deciding how much independence to grant, read how much autonomy is actually safe first. This post assumes you have something that works and now needs to survive real users.

    Design for blast radius before you design for capability

    Rank every tool the agent can call by what happens if it fires at the wrong moment, then set controls to match. Blast radius decides how much scaffolding you need, not benchmark scores.

    The tiering I use when scoping an agent build. Controls are cumulative down the table.

    Blast radiusExample toolMinimum controls
    Read-onlySearch a knowledge base, fetch a CRM recordAllowlist, schema validation, rate limit, audit log
    Reversible writeDraft an email, add a CRM note, tag a leadPlus idempotency key and per-run action cap
    Externally visibleSend a WhatsApp message, place an outbound callPlus per-tenant spend cap, content filter, quiet hours
    Irreversible or financialIssue a refund, delete records, move moneyPlus human approval step and a documented rollback

    Most teams start at the bottom row because it demos well. Start at the top row instead and earn your way down. Building AgentFlow, a visual builder where non-engineers chain input sources, AI processors and output actions on a canvas, is what convinced me this tiering belongs in the tool rather than in a document. When the person assembling the flow is not an engineer, the interface has to make blast radius visible at the point the node is dropped, not in a review later.

    How do you sandbox agent tools?

    You never expose a raw capability to the model. You expose a narrow typed function, validate its arguments against a schema before execution, run it under a service account with least privilege, and execute anything code-shaped inside a disposable container with network egress denied by default.

    The dispatcher pattern

    Anthropic's tool use documentation describes client tools as functions the model requests and your own application executes: the response carries a tool_use block, and your code decides whether to honour it. That gap between deciding and executing is where every safety control lives. Do not close it by auto-dispatching whatever comes back.

    The sandbox rules that have held up across builds:

    • One tool per intent. A single generic run_query tool is an incident waiting to happen; ten specific tools are auditable.
    • Validate arguments with Pydantic or the equivalent before dispatch, and reject rather than coerce.
    • Give each agent, and each tenant, its own service account and its own scoped credentials.
    • Deny outbound network access by default and allowlist specific hosts per tool.
    • Set a hard timeout on every tool call, plus a maximum step count on the loop itself.
    • Treat tool output as untrusted input. OWASP's Top 10 for LLM Applications lists insecure output handling and excessive agency as distinct risks for exactly this reason.
    ALLOWED_TOOLS = {"search_kb", "create_note", "send_whatsapp"}
    
    def dispatch(tool_name, raw_args, ctx):
        if tool_name not in ALLOWED_TOOLS:
            return deny("tool not in allowlist")
    
        args = TOOL_SCHEMAS[tool_name].model_validate(raw_args)  # reject, never coerce
    
        if ctx.spend_usd >= ctx.tenant_cap_usd:
            return deny("tenant spend cap reached")
        if ctx.step >= ctx.max_steps:
            return deny("step budget exhausted")
    
        key = idempotency_key(ctx.run_id, tool_name, args)
        prior = results.get(key)
        if prior:
            return prior  # replay the stored result, do not re-execute
    
        result = TOOLS[tool_name](args, timeout=20, actor=ctx.service_account)
        results.put(key, result, ttl=86400)
        audit.emit(ctx.run_id, ctx.tenant_id, tool_name, redact(args), result.status)
        return result

    "The model is not your security boundary. Your dispatcher is."

    Why every write action needs an idempotency key

    Agents retry, networks drop, and planners re-plan. Without idempotency you will eventually send the same message, create the same record or charge the same card twice. This is the single highest-value control per hour of engineering effort.

    Derive the key deterministically from the run id, the tool name and a canonical hash of the validated arguments. Store it with a unique constraint in Postgres or Supabase and replay the stored response on collision. Stripe's API documentation describes the same pattern: the first response for a given Idempotency-Key is saved and returned for later requests with that key, and keys are retained for at least 24 hours.

    One caveat from a multi-tenant WhatsApp build: idempotency at your layer does not protect you from duplicates created upstream. If a webhook can be delivered more than once, deduplicate on the provider's message id as well as your own key.

    Pair idempotency with disciplined error handling. When a tool call fails, return a structured error to the model rather than an exception trace, and decide per tool whether a retry is safe. A timeout on a read is safe to retry immediately. A timeout on a send is not, because you do not know whether the send happened. For that case, resolve the ambiguity by reading state back before retrying, and let the idempotency store break the tie if you cannot.

    How do you stop an AI agent from burning your budget?

    Meter tokens and tool calls per run, per tenant and per day, then hard-fail the run when it crosses a limit. Cost scales as tokens per call multiplied by calls per run multiplied by runs per day, and agents quietly inflate the middle term when a task goes sideways.

    The five limits worth wiring in on day one:

    • Max steps per run, so a confused planner cannot loop indefinitely.
    • Max calls per individual tool per run, which catches the specific loop shapes that step limits miss.
    • Token budget per run, measured on both input and output.
    • Per-tenant daily spend cap, enforced before dispatch rather than reconciled at invoice time.
    • A global circuit breaker that pauses new runs when the error rate or cost per run crosses a threshold.

    Model pricing is structured per million input and output tokens, with cached input priced lower and server-side tools such as web search often billed per use on top. Those numbers move, so read the current OpenAI and Anthropic Claude pricing pages rather than trusting a figure in a blog post, including this one. What does not move is the shape of the cost curve.

    Kill switches and staged rollout

    A kill switch is a flag your dispatcher checks before every tool call, readable from a store that does not require a deploy to change. If turning your agent off needs a pull request, you do not have a kill switch.

    The rollout sequence I use for a new agent:

    1. 1Shadow mode. The agent runs on real traffic, proposes actions, executes nothing. Compare its proposals against what humans actually did.
    2. 2Internal cohort. Enable write actions for your own team's accounts only, with every action reviewed for a week.
    3. 3Approval mode. Enable for a small slice of real users, but every tier-three or tier-four action queues for a human click.
    4. 4Auto-execute the safe tiers. Release read-only and reversible writes to that slice without approval, keeping the risky tiers gated.
    5. 5Widen the slice. Move from a small cohort to broad traffic only after you have a week of clean audit logs at the previous step.
    6. 6Keep the gate. Leave irreversible actions behind approval permanently unless you have a tested, automated rollback.

    Shadow mode is the step teams skip and the one that pays for itself. It gives you a labelled dataset of agreement and disagreement against human behaviour, which is the only honest accuracy measure you will get before launch. I go deeper on that in nine lessons from shipping agents in production.

    The teams that deploy AI agents in production without a bad week are the ones who treat rollout as a sequence rather than a launch date. Nothing in that list is clever. It is just refusing to skip steps when the demo went well.

    What should you log, and how do you handle PII?

    Log every tool call as a structured event: run id, tenant id, tool name, redacted arguments, result status, latency, token cost, and which policy authorised it. Redact personal data at the boundary before it reaches your log store, not in a cleanup job afterwards.

    You need this for three separate reasons: debugging a bad run, proving to a customer what the agent did on their account, and answering a security review. The third one is what closes enterprise deals. When I built Synthicare, an NHS-compliant clinical decision support platform, the role-based access control and the data isolation design took more review cycles than the model work did.

    Practical PII handling for agent systems:

    • Redact or tokenise identifiers before they enter prompts where the task does not genuinely need them.
    • Pin storage and inference to the region your contract requires, and confirm the provider offers it.
    • Set explicit retention windows on transcripts and traces, and enforce them with a scheduled job.
    • Check each provider's data usage policy for whether API inputs are retained, for how long, and whether zero-retention terms are available on your plan.
    • Keep raw and redacted logs in separate stores with separate access controls.

    The pre-launch checklist

    Before you deploy AI agents in production to real users, every line below should be true. If one is not, you are not launching a feature, you are running an experiment on your customers.

    Ten checks I run before any agent takes live write actions:

    • Every tool is tiered by blast radius and the tiering is written down.
    • No tool executes without passing an allowlist check and schema validation.
    • Every write action carries a deterministic idempotency key with a unique constraint behind it.
    • Step, tool-call and token budgets are enforced before dispatch, not after.
    • A per-tenant daily spend cap exists and has been tested by deliberately breaching it.
    • A kill switch can be flipped by an on-call engineer without a deploy, and someone has flipped it in a drill.
    • Every tool call emits a structured audit event with redacted arguments.
    • Personal data is redacted at the prompt boundary and retention windows are enforced by a scheduled job.
    • An evaluation set of real historical tasks runs on every prompt or model change.
    • Shadow mode has run against live traffic for long enough to produce disagreement examples you have reviewed.

    Is a custom agent worth it versus an off-the-shelf tool?

    If your workflow is generic and your data is not sensitive, buy the tool. Build when the workflow is specific to your business, the actions touch systems of record, or your compliance posture requires controls the vendor will not give you. I break the trade-off down in more detail on custom AI builds versus SaaS agent tools.

    The honest cost comparison is not licence fee versus build cost. It is licence fee versus build cost plus the safety harness described above, because the harness is what makes the agent deployable at all. That harness is roughly the same size whether the agent does one job or ten, which is why per-agent economics improve fast once the first one ships. This is most of what my AI engineering work actually consists of, particularly for SaaS teams putting agents in front of their own customers.

    Key takeaways

    • Controls should be sized by blast radius, not by how impressive the model is.
    • The dispatcher between the model's tool call and your execution layer is the security boundary.
    • Deterministic idempotency keys on every write action prevent the most common class of agent incident.
    • Spend caps must be enforced before dispatch, per run and per tenant, not reconciled after the fact.
    • Shadow mode gives you a real accuracy measure before any user is exposed to the agent.
    • A kill switch that requires a deploy is not a kill switch.

    Frequently asked questions

    What is the safest way to deploy AI agents in production?
    Run the agent in shadow mode on real traffic first, then enable write actions for a small internal cohort behind a kill switch. Gate every irreversible action behind human approval, enforce spend caps before dispatch, and only widen traffic after a clean week of audit logs at the previous stage.
    How much does it cost to run an AI agent in production?
    Cost is tokens per call multiplied by calls per run multiplied by runs per day, plus per-use charges for server-side tools and any voice or messaging provider. Agents inflate calls per run when tasks go wrong, so cap steps and tokens per run. Check current provider pricing pages for rates.
    Can an AI agent take an action I did not authorise?
    Only if your dispatcher lets it. The model returns a request to call a tool; your code executes it. If you validate against an allowlist and a schema, and enforce budget and approval checks before execution, an unauthorised action is a bug in your dispatcher rather than a model failure.
    What is the difference between a guardrail and a kill switch?
    A guardrail constrains what the agent may do on a given call, such as an allowlist, schema validation or a spend cap. A kill switch stops all agent activity immediately, regardless of what any individual call requested. You need both, and the kill switch must be changeable without a deploy.
    Do I need human approval for every agent action?
    No, and requiring it defeats the purpose. Gate by tier: let read-only and reversible actions run automatically, queue externally visible actions during early rollout, and keep irreversible or financial actions behind approval permanently unless you have an automated, tested rollback path.
    How do I test an AI agent before launch?
    Build a fixed evaluation set of real historical tasks with known correct outcomes, run it on every prompt or model change, and run the agent in shadow mode against live traffic. Agreement with human decisions in shadow mode is the most honest pre-launch accuracy signal available.
    Is it safe to give an AI agent access to customer data?
    It can be, with redaction at the prompt boundary, region-pinned storage and inference, explicit retention windows, and separate access controls for raw versus redacted logs. Confirm the provider's data usage policy on API input retention, and whether zero-retention terms are available on your plan.
    How long does it take to make a prototype agent production ready?
    For a single workflow with three to six tools, I typically budget somewhere between two and four weeks for the safety harness: dispatcher, allowlists, idempotency, spend caps, audit logging, kill switch and staged rollout. Subsequent agents reuse most of that harness and ship considerably faster.

    Sources

    Tags:
    AI AgentsLLMOpsAnthropic ClaudeOpenAIProduction Engineering
    HB

    Written by Syed Husnain Haider Bukhari

    AI engineer, data scientist, and founder of Revolutionary Technologies LLC. Ships production AI agents, automations, and data platforms for teams in the US, UK, and UAE — including AgentFlow, AI Walay, and ProLeads.

    Get in touch →

    Related pages

    Want this built instead of researched?

    Book a 30-minute scoping call. You get a one-page plan and a fixed-scope quote within 48 hours.

    Start a conversation

    Let's Create a Revolution