The demo took an afternoon. You gave a model three tools ("find invoices", "send a reminder", "issue a refund"), typed "chase everyone who's overdue", and watched it work. Then you put it behind an API route. The first slow response timed out the request, the client retried, and two customers got the same reminder twice. A week later, someone asks why the agent refunded an invoice nobody approved.
None of that is the model's fault. It's the backend around it. This post is about AI agent backend architecture for a SaaS that already has customers: the queue, the worker, the tool schemas, retries and idempotency, human approval, per-tenant limits, cost tracking and evaluation. These are the boring production parts most tutorials skip, with TypeScript code type-checked against the current Anthropic SDK and BullMQ.
TL;DR#
- Never run an agent inside an HTTP request. The API saves a run and enqueues it; a worker runs the loop; the client watches progress.
- Tools get strict schemas, and you validate again on your side. The model proposes; your code decides.
- Idempotency keys come from the business action, not from the attempt, so a retry can't send the same email or refund twice.
- Risky tools park the run for a person to approve. The worker exits and resumes later from a saved checkpoint.
- Cap everything per tenant: steps per run, runs per minute, and money per month. Log tokens for every model call and price them by the model that actually answered.
- Keep a small evaluation set of real tasks and run it before every prompt, tool or model change.
What this means for your product#
An agent is a feature that takes actions on your customers' behalf, at machine speed, with judgement that's usually right. That's valuable. "Chase overdue invoices", "triage support tickets" and "prepare the weekly report" are hours your customers get back.
The risk is in the word actions. A chatbot that answers wrongly is embarrassing. An agent that refunds wrongly costs money, and one that emails customers twice costs trust. So the design question isn't "which model?" but "what may it do without asking, how many times, for whom, at what cost, and how will we know what it did?" Everything below is an answer to one part of that question.
The architecture#
The flow is API → queue → agent worker → tools → database, with two side channels: approvals that pause a run, and a usage log that pays for it.
1. Never run the agent in the request#
An agent run takes anywhere from seconds to minutes: several model calls, each waiting on tools. HTTP requests time out, load balancers cut idle connections, and clients retry. Each retry starts another agent.
So the API does three cheap things: check the user may start this run, save a row in an agent_runs table, and enqueue a job. It returns a run ID immediately. The client then polls GET /runs/:id or listens for progress over Server-Sent Events, which suit this one-way stream of status updates.
// API side: enqueue with the run ID as the job ID, so a double click enqueues once.
const jobOptions = { attempts: 3, backoff: { type: 'exponential', delay: 5_000 } };
export async function startRun(run: Run) {
await agentRuns.add('step', { runId: run.id }, { ...jobOptions, jobId: run.id });
}
BullMQ ignores a job whose jobId already exists, so the run ID doubles as a de-duplication key. One gotcha: custom job IDs can't be plain integers or contain a colon. BullMQ throws Custom Id cannot contain :, so use UUIDs and join parts with a dash.
2. Tools with strict schemas#
Each tool has four parts: the schema the model sees, a parser that re-checks the input on your side, a flag for whether a person must approve it, and the code that runs it.
// src/agent/tools.ts
import type Anthropic from '@anthropic-ai/sdk';
import { z } from 'zod';
import { crm } from './deps.js'; // your existing services
type Ctx = { tenantId: string; runId: string };
export const TOOLS = {
find_invoices: {
risky: false,
definition: {
name: 'find_invoices',
description: "Find this workspace's invoices for one customer email. Read-only.",
strict: true,
input_schema: {
type: 'object',
properties: {
customerEmail: { type: 'string', description: 'The customer email address' },
status: { type: 'string', enum: ['open', 'paid', 'overdue'] },
},
required: ['customerEmail', 'status'],
additionalProperties: false,
},
},
parse: z.object({ customerEmail: z.string().email(), status: z.enum(['open', 'paid', 'overdue']) }),
run: (ctx: Ctx, input: { customerEmail: string; status: string }) => crm.findInvoices(ctx.tenantId, input),
},
send_reminder: {
risky: false,
definition: {
name: 'send_reminder',
description: 'Email the customer a payment reminder for one overdue invoice.',
strict: true,
input_schema: {
type: 'object',
properties: { invoiceId: { type: 'string' } },
required: ['invoiceId'],
additionalProperties: false,
},
},
parse: z.object({ invoiceId: z.string().min(1) }),
run: (ctx: Ctx, input: { invoiceId: string }) =>
// One reminder per invoice per day, however many times the agent or the queue retries.
crm.sendReminder(ctx.tenantId, input.invoiceId, { idempotencyKey: `reminder:${input.invoiceId}:${new Date().toISOString().slice(0, 10)}` }),
},
refund_invoice: {
risky: true, // moves money: a person approves it first
definition: {
name: 'refund_invoice',
description: 'Refund part or all of one paid invoice. Requires approval by a person.',
strict: true,
input_schema: {
type: 'object',
properties: { invoiceId: { type: 'string' }, amountCents: { type: 'integer' } },
required: ['invoiceId', 'amountCents'],
additionalProperties: false,
},
},
parse: z.object({ invoiceId: z.string().min(1), amountCents: z.number().int().positive().max(500_00) }),
run: (ctx: Ctx, input: { invoiceId: string; amountCents: number }) =>
crm.refund(ctx.tenantId, input.invoiceId, input.amountCents, { idempotencyKey: `refund:${ctx.runId}:${input.invoiceId}` }),
},
} as const;
export type ToolName = keyof typeof TOOLS;
export const toolDefinitions: Anthropic.Beta.BetaTool[] = Object.values(TOOLS).map((t) => t.definition as Anthropic.Beta.BetaTool);
export async function execute(name: string, rawInput: unknown, ctx: Ctx): Promise<{ content: string; isError: boolean }> {
const tool = TOOLS[name as ToolName];
if (!tool) return { content: `Unknown tool ${name}`, isError: true };
const parsed = tool.parse.safeParse(rawInput);
if (!parsed.success) return { content: `Invalid input: ${parsed.error.issues[0]?.message}`, isError: true };
try {
const result = await (tool.run as (c: Ctx, i: unknown) => Promise<unknown>)(ctx, parsed.data);
return { content: JSON.stringify(result), isError: false };
} catch (err) {
return { content: `Tool failed: ${(err as Error).message}`, isError: true };
}
}
strict: true makes the API guarantee the tool input matches the schema (strict tool use), but the schema can only say so much. The Zod parser enforces the rules a JSON schema can't express cleanly, like a valid email or a maximum refund of $500. The tenant never comes from the model: it's in ctx, set from the run's owner.
Errors go back to the model as is_error results with a short message, so it can correct itself ("Invalid input: Invalid email") instead of crashing the run.
3. The worker loop#
This is the whole worker. It's a manual loop rather than an SDK helper for one reason: a run must be able to stop for hours while a person decides, then continue in a different job, maybe on a different machine. So every step is checkpointed to the database.
// src/agent/worker.ts
import Anthropic from '@anthropic-ai/sdk';
import { Queue, Worker, UnrecoverableError } from 'bullmq';
import { budgets, runs, usageLog, type Run } from './deps.js';
import { TOOLS, execute, toolDefinitions, type ToolName } from './tools.js';
const connection = { host: process.env.REDIS_HOST ?? 'localhost', port: 6379 };
export const agentRuns = new Queue('agent-runs', { connection });
const client = new Anthropic({ timeout: 120_000, maxRetries: 2 });
const MODEL = 'claude-opus-5-5';
const MAX_STEPS = 12;
const SYSTEM = 'You help a small business follow up on invoices. Use the tools. Never guess invoice IDs; look them up first.';
new Worker(
'agent-runs',
async (job) => {
const run = await runs.get(job.data.runId);
if (run.status === 'done' || run.status === 'failed') return; // a retry of finished work does nothing
if (run.pendingToolUse && run.approved === null) return; // still waiting for a person
// Resuming after a person approved or declined the risky call.
if (run.pendingToolUse) {
const { id, name, input } = run.pendingToolUse;
const result = run.approved
? await execute(name, input, { tenantId: run.tenantId, runId: run.id })
: { content: 'A person declined this action. Do not retry it; tell the user it was declined.', isError: true };
run.messages.push({ role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: result.content, is_error: result.isError }] });
run.pendingToolUse = null;
run.approved = null;
}
run.status = 'running';
for (let step = 0; step < MAX_STEPS; step++) {
if ((await budgets.remainingCents(run.tenantId)) <= 0) {
run.status = 'failed';
await runs.save(run);
throw new UnrecoverableError('Tenant AI budget exhausted');
}
const response = await client.beta.messages.create({
model: MODEL,
max_tokens: 4096,
system: SYSTEM,
tools: toolDefinitions,
messages: run.messages,
output_config: { effort: 'medium' },
betas: ['server-side-fallback-2026-07-01'],
fallbacks: 'default',
});
await usageLog.record({
runId: run.id,
tenantId: run.tenantId,
model: response.model,
inputTokens: response.usage.input_tokens,
outputTokens: response.usage.output_tokens,
cacheReadTokens: response.usage.cache_read_input_tokens ?? 0,
});
run.messages.push({ role: 'assistant', content: response.content });
if (response.stop_reason === 'end_turn') {
run.status = 'done';
break;
}
if (response.stop_reason !== 'tool_use') {
run.status = 'failed'; // refusal, max_tokens or anything unexpected: stop, don't loop
break;
}
const results: Anthropic.Beta.BetaToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type !== 'tool_use') continue;
if (run.pendingToolUse) {
// Every tool_use needs a result. Calls after the parked one wait for the next turn.
results.push({ type: 'tool_result', tool_use_id: block.id, content: 'Skipped: an earlier action is waiting for approval. Call it again afterwards if still needed.', is_error: true });
} else if (TOOLS[block.name as ToolName]?.risky) {
run.pendingToolUse = { id: block.id, name: block.name, input: block.input };
} else {
const result = await execute(block.name, block.input, { tenantId: run.tenantId, runId: run.id });
results.push({ type: 'tool_result', tool_use_id: block.id, content: result.content, is_error: result.isError });
}
}
if (results.length) run.messages.push({ role: 'user', content: results });
if (run.pendingToolUse) {
// Park the run. A person approves or declines in the app, which re-enqueues it;
// the approved call's result then joins this same user turn.
run.status = 'awaiting_approval';
await runs.save(run);
return;
}
await runs.save(run); // checkpoint every step, so a crash resumes here
}
if (run.status === 'running') run.status = 'failed'; // hit MAX_STEPS
await runs.save(run);
},
{ connection, concurrency: 5, limiter: { max: 20, duration: 60_000 } },
);
The details that matter:
- Every exit is explicit. The loop ends on
end_turn, on anything unexpected (including a refusal or hittingmax_tokens), afterMAX_STEPS, or when the budget runs out. An agent that can loop forever eventually will. - Timeouts at two levels. The SDK client times out a single model call after 120 seconds and retries it twice; BullMQ retries the whole job three times with backoff.
UnrecoverableErrortells BullMQ not to retry a run that failed for a reason retrying won't fix. - The full assistant content is stored and sent back unchanged, including any thinking blocks. Rewriting history between steps breaks things on current models; only ever append.
- Fallbacks are on.
fallbacks: 'default'lets the API retry a request on another model if the first one declines it for safety reasons, inside the same call.response.modelrecords which model actually answered, which matters for pricing. - Effort is set explicitly. Claude Opus 5.5 defaults to
mediumeffort; routine tool-calling work rarely needs more, and higher effort costs more tokens per step.
4. Retries and idempotency#
Retries happen at every layer: the SDK retries a failed model call, BullMQ retries a failed job, and the model itself may call a tool again. You can't stop retries, so you make them harmless.
The key insight is the same one I use for Stripe webhooks that never double-charge: build idempotency keys from the business action, not from the attempt. If the worker crashes after sending a reminder but before saving the checkpoint, the retried step calls the model again, and the model issues a brand-new tool call with a new ID. A key built from that ID would let the second email through. A key built from the business action, reminder:{invoice}:{day}, stops it, because your email service (or a unique index in your own database) refuses a key it has already seen.
| Layer | What retries | What makes it safe |
|---|---|---|
| HTTP API | The client, after a timeout | Return a run ID fast; jobId = run ID de-duplicates the enqueue |
| Model call | The SDK, on 429, 5xx and network errors | Nothing to undo: a model call has no side effects |
| Job | BullMQ, after a crash or error | Checkpoint after each step; finished runs exit at the top |
| Tool | The model, or a retried step | Idempotency keys from the business action |
5. Human approval for risky actions#
Decide up front which tools a person must approve. My rule is simple: anything that moves money, deletes data, or contacts many people at once.
When the model asks for a risky tool, the worker doesn't wait. It saves the pending call, marks the run awaiting_approval, and exits. The app shows the proposed action ("Refund $40.00 on invoice INV-1042?") to someone with permission, and their answer re-enqueues the run:
// Called by the approve/decline endpoint after it saves run.approved.
export async function resumeRun(run: Run) {
await agentRuns.add('step', { runId: run.id }, { ...jobOptions, jobId: `${run.id}-${run.pendingToolUse!.id}` });
}
The approval endpoint must check the approver's own permissions and tenant, not just that the run exists. And a declined action goes back to the model as an error result that says so, so it tells the user instead of trying a workaround.
6. Per-tenant limits and budgets#
One customer's runaway agent shouldn't slow down, or pay for, anyone else's. Three limits cover most cases:
- Steps per run (
MAX_STEPS): stops loops. - Runs per tenant per minute: check before enqueueing. BullMQ's
limiterabove caps the worker's total throughput across all tenants; the per-tenant part is a Redis counter in the API. - Money per tenant per month: sum the usage log, price it, and refuse new steps when the budget is spent.
Pricing a step is arithmetic on the usage the API returns. At the list price for Claude Opus 5.5 as of October 2026 ($4 per million input tokens, $20 per million output tokens), a run of 10 steps averaging 6,000 input and 500 output tokens costs about 60,000 × $4/M + 5,000 × $20/M = $0.34. Notice that input dominates: every step resends the whole conversation. Prompt caching and shorter tool outputs cut it the most, and I go through those levers in how to keep your AI feature's API bill under control.
Price each row by response.model, not the model you asked for, because a fallback may have answered.
7. Observability#
When a customer asks "why did the agent do that?", you need the answer in a minute, not a day. Log one structured line per step with the run ID, tenant, step number, model, tokens, latency, stop reason and the names of the tools called. Keep the full message history on the run row, so you can replay exactly what the model saw.
Then put a few numbers on a dashboard: runs started, finished and failed per hour; median and worst-case steps per run; cost per tenant per day; approvals pending; and the share of tool calls that returned an error. A jump in tool errors is usually the first sign that a prompt or schema change went wrong. If you're on AWS, CloudWatch logs, metrics and alarms cover this without another vendor.
8. Evaluation basics#
Agents change behaviour when you change the prompt, a tool description or the model. Without a test set, you find out from customers.
Start small: 20 to 50 real tasks taken from production runs (anonymised), each with what a good outcome looks like. "Chase overdue invoices for Acme" should call find_invoices before send_reminder, never call refund_invoice, and finish in under six steps. Run the set against a staging copy with fake services before every change, and compare pass rate, steps and cost with the last run. Grade tool calls and outcomes with code where you can; use a model as the grader only for judgement calls like tone.
Failure modes I design for#
| Failure | What it looks like | The guard |
|---|---|---|
| Timeout retries | Two runs for one click | Enqueue with jobId = run ID |
| Crash mid-step | Duplicate email or refund | Business-level idempotency keys |
| Infinite loop | A run that never ends, a large bill | MAX_STEPS, budget check every step |
| Unapproved risky action | A refund nobody asked for | Risky tools park the run for approval |
| Wrong tenant | One customer's data in another's run | Tenant from the run owner, never from model input |
| Silent regressions | "It used to work" | An evaluation set run before every change |
Planning an AI feature?#
I'll help you design it so it's safe and affordable: which actions an agent may take on its own, where people approve, how it retries, and what it costs per customer, built on the backend you already run. If you want AI tools to call your product from the outside too, that's an MCP server. Email mhuzaifaa.dev@gmail.com or see the projects I've shipped.
FAQ#
How do you add an AI agent to an existing SaaS?#
Add it as a background job, not an API endpoint. The API saves a run and enqueues it; a worker calls the model, validates and executes tool calls against your existing services, checkpoints each step, and reports progress. Give it narrow tools with strict schemas, per-tenant limits, and human approval for risky actions.
Should AI agents run in a queue or in the API request?#
In a queue. An agent run can take minutes and makes several model calls, which outlasts HTTP timeouts and invites duplicate runs when clients retry. A queue such as BullMQ gives you retries with backoff, concurrency limits, and a place to pause runs that wait for human approval.
How do you stop an AI agent from taking a wrong action?#
Limit what it can do: narrow tools, strict input schemas, and your own validation on every call. Take the tenant from the run, not from the model. Require human approval for anything that moves money, deletes data or contacts many people, and cap steps per run so mistakes can't repeat endlessly.
How do you make AI agent tool calls idempotent?#
Give each side-effecting tool an idempotency key built from the business action, such as one reminder per invoice per day, and have the service or a unique database index reject repeats. Keys built from the attempt or the tool-call ID don't help, because a retried step produces a new call with a new ID.
How much does it cost to run an AI agent in production?#
It's the tokens per step times the steps per run times the model's price. Input usually dominates, because each step resends the conversation. Log usage from every API response, price it by the model that actually answered, and enforce a monthly budget per customer so costs can't run away.
How do you test an AI agent before deploying changes?#
Keep an evaluation set of 20–50 real tasks with expected outcomes, such as which tools should and shouldn't be called and the maximum steps. Run it against a staging environment with fake services before every prompt, tool or model change, and compare pass rate, steps and cost with the previous version.
