Rana Maninder Singh
Lesson 11 of 12AI Agents & Automation

Deployment, Monitoring & Operations

Lesson opener

In one line: Deploying an agent is not "copying code to prod" — it's a controlled rollout with monitoring, cost controls, and a kill switch that can stop the agent in seconds.

Why it matters: Agents in production face real traffic, real data, and real consequences. A runaway agent can cost thousands in API calls, corrupt data, or make wrong decisions at scale. This lesson teaches you the deployment patterns, monitoring dashboards, cost management, and operational procedures that keep agents safe and reliable in production.

Before this lesson: Evaluation & Testing

Prerequisites

PrerequisiteWhy it matters
Evaluation & TestingUnderstands evaluation metrics and regression testing

Lesson roadmap

By the end of this lesson you will be able to:

  1. Design a safe deployment pipeline for agents (canary, feature flags, rollback).
  2. Build monitoring dashboards covering health, quality, cost, and safety.
  3. Implement cost management: budgets, alerts, automatic throttling.
  4. Design logging, tracing, and debugging for multi-step agent runs.
  5. Create a kill switch and incident response procedures.
  6. Produce a production-readiness and monitoring plan with budgets, circuit breakers, rollback, and incident ownership.

Deployment pipeline for agents

Why agent deployment is different

Traditional appAgent
Deterministic behaviorNon-deterministic (temperature, sampling)
Single version in prodMultiple versions may run simultaneously (A/B, shadow)
Rollback = redeploy previous versionRollback = disable agent + drain in-flight cases
Health = HTTP 200Health = task success rate, safety, cost, latency

Deployment stages

┌─────────────┐    ┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│  Dev /      │    │  Staging    │    │  Canary     │    │  Production │
│  Local      │───▶│  (Full test │───▶│  (5% traffic)│───▶│  (100%)     │
│  Testing    │    │   suite)    │    │              │    │             │
└─────────────┘    └─────────────┘    └─────────────┘    └─────────────┘

Stage gates

StageEntry criteriaExit criteria
DevCode compiles, unit tests passDeveloper validates locally
StagingDev complete, unit tests passFull regression suite passes (all metrics green)
CanaryStaging green, feature flag ready48 hours with: no safety violations, task success ≥ target, cost ≤ budget, latency ≤ SLA
ProductionCanary green, stakeholder sign-offOngoing monitoring within thresholds

Feature flags (essential for agents)

# Feature flag configuration
FEATURE_FLAGS = {
    "refund_agent": {
        "enabled": True,
        "rollout_percentage": 100,
        "version": "v2.3.1",
        "config": {
            "max_refund_auto_approve": 500,
            "max_iterations": 3,
            "model": "gpt-4.1",
            "temperature": 0.1
        },
        "kill_switch": False  # If True, agent refuses all requests
    }
}

# Runtime check
def handle_request(request):
    flag = FEATURE_FLAGS["refund_agent"]
    if not flag["enabled"] or flag["kill_switch"]:
        return {"status": "agent_disabled", "message": "Agent temporarily unavailable"}
    if random.random() > flag["rollout_percentage"] / 100:
        return {"status": "fallback", "message": "Routing to human queue"}
    # ... run agent

Rollback procedure

ScenarioRollback actionTime to execute
Canary failsSet enabled: false, rollout_percentage: 0< 30 seconds
Production safety violationSet kill_switch: true, drain in-flight cases< 60 seconds
Model regressionRevert model to previous version< 2 minutes
Cost spikeSet max_iterations: 1, reduce rollout_percentage< 30 seconds

Drain in-flight cases: Don't kill running cases. Let them complete (with timeout). New requests get routed to human fallback.


Monitoring dashboards

Dashboard 1: Health & Availability

MetricTargetAlert threshold
Request success rate≥ 99.5%< 99% for 5 min
Agent availability100% (no downtime)Any downtime
Error rate (5xx)< 0.1%> 1% for 5 min
Timeout rate< 1%> 5% for 5 min
In-flight casesStableGrowing > 10% / hour (stuck cases)

Dashboard 2: Quality & Safety

MetricTargetAlert threshold
Task success rate≥ 95% (happy path)< 90% for 1 hour
Safety violations0Any violation = immediate alert
Groundedness≥ 90%< 85% for 1 hour
Escalation rate< 5%> 10% for 1 hour
User override rate< 10%> 20% for 1 hour
Injection attempts blockedTrackedSpike > 10x baseline

Dashboard 3: Performance & Cost

MetricTargetAlert threshold
Latency p50< 10s> 20s
Latency p95< 30s> 60s
Latency p99< 60s> 120s
Cost per case< budget> 1.5x budget
Daily cost< daily budget> 1.2x daily budget
Tokens per caseStable> 2x baseline (prompt stuffing?)

Dashboard 4: Business Impact

MetricTargetAlert threshold
Cases auto-resolved> 80%< 60%
Avg handling time< human baseline> human baseline
Customer satisfaction≥ human baseline< human baseline - 5 pts
Straight-through processing> 70%< 50%

Logging and tracing

Structured logging (every agent action)

{
  "timestamp": "2024-10-15T10:30:45.123Z",
  "level": "INFO",
  "agent_id": "refund_agent",
  "version": "v2.3.1",
  "case_id": "REF-2024-045123",
  "session_id": "sess_abc123",
  "loop_iteration": 2,
  "event_type": "tool_call",
  "tool_name": "verify_invoice",
  "inputs": {"invoice_id": "INV-447833", "customer_id": "C00123"},
  "outputs": {"status": "delivered", "amount": 350, "eligible": true},
  "duration_ms": 245,
  "success": true,
  "trace_id": "trace_xyz789",
  "span_id": "span_002"
}

Distributed tracing (OpenTelemetry)

Every agent run gets a trace_id. Each loop iteration is a span. Tool calls are child spans.

Trace: trace_xyz789 (refund_agent, case REF-2024-045123)
├── Span 1: Loop iteration 1 (perceive)
│   └── Child: get_customer_summary (tool)
├── Span 2: Loop iteration 2 (reason + act)
│   ├── Child: check_eligibility (tool)
│   └── Child: verify_invoice (tool)
├── Span 3: Loop iteration 3 (act + observe)
│   ├── Child: issue_refund (tool)
│   └── Child: notify_customer (tool)
└── Span 4: Case complete

Why it matters: When an agent fails or behaves strangely, traces show exactly which loop iteration, which tool, and what the inputs/outputs were. Essential for debugging non-deterministic failures.


Cost management

Cost drivers

DriverControl mechanism
Model choiceUse cheaper model for simple tasks (e.g., gpt-4o-mini for classification, gpt-4.1 for reasoning)
Token usageLimit context: summarize history, truncate RAG, cap max iterations
Tool callsCache tool results within a case. Batch similar calls.
Retry loopsExponential backoff. Max retries. Circuit breaker.
VolumeRate limiting. Queue with priority.

Budget enforcement

# Per-agent budget configuration
AGENT_BUDGETS = {
    "refund_agent": {
        "daily_token_budget": 500000,      # ~$1.50/day at gpt-4.1 pricing
        "daily_cost_budget_usd": 2.00,
        "per_case_token_limit": 8000,      # Hard limit per case
        "per_case_cost_limit_usd": 0.05,
        "alert_threshold_pct": 80,         # Alert at 80% of budget
        "throttle_threshold_pct": 95,      # Throttle at 95%
        "hard_stop_threshold_pct": 100     # Kill switch at 100%
    }
}

# Runtime enforcement
async def run_agent_with_budget(agent_id, case_input):
    budget = AGENT_BUDGETS[agent_id]
    usage = await get_daily_usage(agent_id)
    
    if usage.tokens >= budget["daily_token_budget"] * budget["hard_stop_threshold_pct"] / 100:
        raise BudgetExceededError("Daily token budget exhausted")
    
    if usage.tokens >= budget["daily_token_budget"] * budget["throttle_threshold_pct"] / 100:
        # Throttle: reduce rollout, increase queue delay
        await throttle_agent(agent_id)
    
    # Track per-case usage
    case_usage = CaseUsageTracker(budget["per_case_token_limit"])
    result = await run_agent(agent_id, case_input, usage_tracker=case_usage)
    
    await record_usage(agent_id, case_usage.total_tokens, case_usage.estimated_cost)
    return result

Cost optimization patterns

PatternSavingsTrade-off
Model routing60–80%Simple tasks → small model; complex → large model
Prompt caching30–50%Cache system prompt + static context
RAG chunk limiting20–40%Top-3 chunks instead of top-10
History summarization40–60%Summarize after 5 iterations instead of full history
Tool result caching10–30%Cache get_customer results for 5 min within case

Kill switch and incident response

Kill switch design

# Global kill switch (Redis)
KILL_SWITCH_KEY = "agent:kill_switch:refund_agent"

async def check_kill_switch(agent_id):
    if await redis.get(f"agent:kill_switch:{agent_id}"):
        raise AgentDisabledError("Kill switch activated")

# Per-agent kill switch (feature flag)
FEATURE_FLAGS = {
    "refund_agent": {
        "kill_switch": False,  # Set to True to stop immediately
        "drain_mode": False    # Set to True to stop new requests, finish in-flight
    }
}

Activation triggers

TriggerActivationWho can activate
Safety violationAutomatic (monitoring detects PII leak, unauthorized action)System (auto)
Cost spikeAutomatic (daily budget 100% reached)System (auto)
Model misbehaviorManual (operator sees anomaly)Agent Operator, Platform Team
Security incidentManual (security team detects compromise)Security Team, Platform Team
Regulatory orderManual (compliance/legal)Compliance Officer, Legal

Incident response playbook

PhaseActionsOwnerSLA
DetectAlert fires (safety, cost, quality, availability)MonitoringImmediate
TriageCheck dashboards. Confirm real vs. false positive. Assess blast radius.Agent Operator< 5 min
ContainActivate kill switch / drain mode / throttle. Route traffic to human fallback.Agent Operator< 2 min
InvestigatePull traces. Check logs. Identify root cause.Agent Operator + Platform< 30 min
ResolveFix code / config / data. Test in staging. Deploy fix.Platform TeamVaries
RecoverDisable kill switch. Ramp up rollout. Monitor closely.Agent Operator< 1 hour after fix
PostmortemWrite incident report. Update runbooks. Add regression tests.Agent Owner< 48 hours

Runbook example: "Agent stuck in loop"

Symptom: In-flight cases growing. Latency p99 > 120s. Loop iteration avg > 5.

Immediate:

1. Set max_iterations: 2 via feature flag (limits damage).

2. Check traces for stuck cases. Are they all on same tool? Same input?

Investigate:

3. Pull traces for 5 stuck cases. Look at loop iteration 3+.

4. Check tool success rates. Is a tool failing silently?

5. Check prompt: did a recent change remove termination condition?

Fix:

6. If tool issue: deploy tool fix, restart affected cases.

7. If prompt issue: revert prompt, add explicit termination guard.

Recover:

8. Reset max_iterations: 3. Monitor for 30 min.

9. If stable, ramp rollout to 100%.


Pause-and-think questions

Q1. Your "procurement agent" is deployed at 100% rollout. Suddenly, daily cost jumps from $5 to $200. The alert fires at 95% budget. What do you do in the first 5 minutes? First 30 minutes? First 2 hours?

Answer.

Q2. An agent case has been running for 10 minutes (normal is 30 seconds). The trace shows it's on loop iteration 12 (max is 3). What's the likely cause? How do you fix it without killing the case?

Answer.

Q3. You're rolling out a new model version for the "customer service agent." Design the canary deployment plan: traffic split, duration, success criteria, rollback triggers.

Answer.


Failure example: Production usage creates uncontrolled cost, retries, and incorrect actions

Business context

Brightline Foods put a procurement agent at 100% rollout. Feature flags included create_purchase_order against the ERP. Daily budget was $5. Retry policy on ERP timeouts was "immediate, unlimited" because "we do not want lost POs."

Intended outcome

Canary then full rollout with daily and per-case budgets, throttle at 95%, kill switch at 100%, a circuit breaker on the ERP tool, idempotent writes, and a rollback path that drains in-flight cases instead of double-posting.

Actual failure

An ERP timeout after a PO was already created triggered retries. Each retry spent more tokens (full history, no summarization) and called create_purchase_order again. By mid-morning the agent had opened 11 duplicate POs for the same request (about $48,000 committed) and daily model cost had moved from $5 toward $200. Incorrect actions and cost were the same incident: retries without idempotency plus no hard stop.

Observable symptoms

Root cause

Unbounded retries + non-idempotent writes + missing budget enforcement. The observe/retry loop treated timeout as "try again" without an idempotency key. Per-case token limits and the daily hard stop were configured in a document, not checked at runtime. Circuit breaker on the ERP tool was never armed.

Business impact

Diagnostic steps

  1. Confirm blast radius: count POs per request id; sum committed amount.
  2. Open traces: iteration count, retry count, token growth per iteration.
  3. Check feature flags: kill_switch, rollout_percentage, max_iterations, budget thresholds.
  4. Verify whether create_purchase_order required an idempotency key and whether the circuit breaker opened.

Correction

  1. Contain: rollout_percentage: 0 or kill_switch: true; drain in-flight cases; route new requests to humans (first five minutes of Q1).
  2. Cancel or reverse duplicate POs with a documented compensating action; leave the audit trail intact.
  3. Enforce idempotency on create; cap retries with exponential backoff; open a circuit breaker after repeated ERP failures.
  4. Enforce daily and per-case token/cost limits in the runtime path; throttle at 95%; hard-stop at 100%.
  5. Restore history summarization so retries cannot grow context without bound.

Validation after correction

Preventive control


Guided practice: Production-readiness and monitoring plan

Scenario

You are the Agent Operator for the refund agent (refund_agent v2.3.1) described in this lesson's feature-flag and budget examples. Staging regression is green. You must write the production-readiness and monitoring plan that Security and Finance will sign before canary.

Input information

ItemValue
Writesissue_refund (money out)
Budget (from this lesson)$2.00/day, $0.05/case, 8,000 tokens/case; alert 80%, throttle 95%, hard stop 100%
SLAp95 < 30s; task success ≥ 95% happy path; safety = 0
Known riskERP/payment tool timeouts; retry storms; loop past max_iterations

Constraints

Staged hints

Hint 1 — Readiness: Stage gates (dev → staging → canary → prod) and feature-flag fields you will actually change.

Hint 2 — Monitor: Pick metrics from Health, Quality/Safety, Performance/Cost, and Business Impact. Each needs a target and an alert.

Hint 3 — Break glass: Who can set kill_switch or drain_mode, and what the first five minutes look like on a cost or retry spike.

Hint 4 — Incorrect actions: How you detect a duplicate or over-limit refund in the same plan as cost (they share retries).

Learner checkpoints

Complete model solution

Readiness (stage gates):

StageExit criteria before the next stage
StagingFull regression green (success, safety, groundedness, cost fixtures)
Canary5% traffic, 48 hours: no safety violations, success ≥ target, cost ≤ budget, latency ≤ SLA, zero duplicate issue_refund for the same case id
ProductionCanary green + Finance and Operator sign-off on flags

Feature flags to set: enabled, rollout_percentage, max_refund_auto_approve, max_iterations, kill_switch, drain_mode. Rollback: enabled: false or kill_switch: true in < 60 seconds; drain in-flight.

Monitoring plan:

DashboardMetricAlert
HealthTimeout rate, in-flight growthTimeout > 5% for 5 min; in-flight +10%/hour
Quality / SafetyTask success, safety violations, injection blocksAny safety = page; success < 90% for 1 hour
Performance / Costp95, cost/case, daily cost, tokens/caseCost > 1.2× daily; tokens > 2× baseline
BusinessAuto-resolve %, override rateOverrides > 20% for 1 hour

Budgets and breakers: Runtime checks from AGENT_BUDGETS in this lesson. Circuit breaker: open issue_refund after N consecutive timeouts; fallback to human queue. Idempotency key: case_id + invoice + amount.

Incident (first hour): Detect (alert) → triage (< 5 min) → contain (kill/drain/throttle, < 2 min) → investigate traces (< 30 min) → fix in staging → recover (ramp) → postmortem < 48 hours. Owners: Operator, Platform, Agent Owner.

Why this solution works

Cost, retries, and incorrect refunds are one control plane: the same timeout that burns tokens can also double-pay. The plan ties flags, budgets, circuit breakers, and dashboards so the Brightline failure cannot pass "ready for 100%."

Validation procedure

  1. Tabletop the $5 → $200 spike using Q1 timings; record the actual flag changes.
  2. Staging: timeout-after-success test; assert one refund.
  3. Confirm pages fire on daily cost and on any safety violation.

Governance check

Agent Operator owns the kill switch drill (monthly). Finance owns the dollar budget. Platform owns circuit breaker and trace retention. No canary without those three names.


Independent practice: Readiness plan for an invoice-matching agent

Workplace scenario

Cedar Mills wants to canary an invoice-matching agent that compares PO, goods receipt, and invoice, then calls post_match_result (write). Staging looks fine. There is no written budget, no circuit breaker on the ERP match tool, and retries are still "until it works." Leadership wants 50% traffic next Monday.

Deliverable

A production-readiness and monitoring plan (two pages): stage gates, flags, four dashboard areas, budgets, circuit breakers, rollback, kill switch, and an incident table. This is not the refund-agent plan with the title changed — matching has a three-way document set and a different write tool.

Scope

Constraints

Required controls

Monitoring, budgets, circuit breakers, rollback, kill switch, and incident ownership must all appear with owners and numeric thresholds.

Measurable acceptance criteria

Model approach / example answer

Reject 50% next Monday. Staging-green is not a canary. First production step: enabled: true, rollout_percentage: 5, 48 hours, exit criteria from this lesson (no new safety violation; no duplicate post_match_result; latency and cost inside budget).

Flags: enabled, rollout_percentage, kill_switch, drain_mode. Write tool off unless the flag allows it.

Budgets (example numbers a reviewer can score): daily tokens alert 80%, throttle 95%, hard stop 100%; per-case token cap. Runtime must read AGENT_BUDGETS, not a slide.

Circuit breaker: open post_match_result after N consecutive timeouts or error-rate threshold; fallback human match queue. Idempotency key: case_id + invoice_id + match_hash. Timeout after success → lookup by key, do not create a second post.

Four dashboard areas: health/availability of the match worker; quality/safety (wrong-invoice match, duplicate key); performance/cost; business (matches posted, payment-release lag).

Kill vs drain: automatic kill on safety or 100% budget; Security/Platform may kill on compromise. Drain in-flight matches; never kill the process mid-write. Rollback target: contain < 2 min as in this lesson's playbook.

Score: 1 point per acceptance-criteria checkbox (8). Zero if Monday 50% is accepted with no hours gate.

Self-review checklist


Common mistakes

MistakeSymptomCauseConsequenceCorrectionPreventive control
100% on a green staging suiteCost or safety breaks on day oneStaging volume ≠ productionRunaway spend or bad writes at full trafficCanary 5% / 48h with exit criteriaStage-gate table signed before prod
Unlimited tool retriesDuplicate POs or refundsTimeout treated as "try again"Incorrect commitments; token spikeIdempotency + capped backoff + circuit breakerWrite-tool contract test in staging
Budget only on a slideDaily cost 40× planRuntime never reads AGENT_BUDGETSHard-stop never firesEnforce alert/throttle/stop in codeBudget check in the request path
Kill switch untestedDebate while the agent keeps writingFlag exists but never drilledSlow containmentMonthly kill + drain drillIR playbook SLA: contain < 2 min
Kill the processMissing spans, half-written ERP state"Just stop the pods"Corrupt cases, weak auditDrain mode; complete or hand offRunbook: never kill mid-case
Cost dashboard onlyDuplicates found by Finance next weekOps watched $ not write errorsIncorrect actions missedAlert on duplicate idempotency keysQuality + cost on the same incident view

Quick checks

  1. Explain in your own words: Why does a cost spike and a duplicate ERP write often share one root cause?

Answer: Timeouts and loops retry the same tool. Each retry spends tokens and, without an idempotency key, may create another PO or refund. Uncontrolled cost and incorrect actions are the same retry storm.

  1. Predict the result: Daily tokens hit 100% of budget but hard_stop_threshold_pct is not implemented. What happens this afternoon?

Answer: The agent keeps accepting work. Cost continues to climb until someone sets the kill switch or rollout to zero by hand.

  1. Diagnose the failure: p99 latency is 120s, in-flight cases grow, average loop iteration is 5, max_iterations is 3. What is broken?

Answer: The max-iteration guard is not enforced (or Observe never terminates). Treat it as the stuck-loop runbook: cap iterations via flag, inspect traces, do not kill the process.

  1. Select the safer design: ERP create timed out after success. Choose (a) immediate unlimited retry of create, or (b) lookup by idempotency key, circuit-break after repeated failures, drain new writes.

Answer: (b). (a) is the Brightline failure mode.

  1. Identify the required control: Security reports a suspected compromise of the agent runtime. Who may activate the kill switch, and what happens to in-flight cases?

Answer: Security Team or Platform (manual security trigger in this lesson). Activate kill or drain; finish or hand off in-flight work; do not drop the audit trail; page via the incident playbook.


Responsible AI

ControlThis lesson
Accountable ownerAgent Owner for business risk; Operator for flags and first response
Approved usersRoles allowed to invoke the agent in each rollout percentage
Data sourcesProduction logs and traces with sanitized payloads; no secret material in log fields
Least privilegeProduction write tools only when the flag allows; canary before 100%
ProhibitedUnlimited retries, process-kill mid-case, 100% rollout without canary exit criteria
ValidationStaging regression + timeout-after-success test + kill-switch drill
Approval gateCanary and prod require Operator + Finance (budget) + quality gates from Evaluation & Testing
EscalationPlaybook: Detect → Triage → Contain → Investigate → Resolve → Recover → Postmortem
AuditStructured logs with case_id, trace_id, version, tool name; retain enough to reconstruct writes
FallbackHuman queue when killed, throttled, or circuit-open
StopAutomatic kill on safety or 100% budget; manual kill on security or regulatory order; drain then ramp

Complete the lesson quiz to test whether you can apply these decisions to a new scenario.


Key takeaways

  • Deployment pipeline: Dev → Staging (full regression) → Canary (5%, 48h) → Production. Feature flags control everything.
  • Monitoring: Four dashboards — Health, Quality/Safety, Performance/Cost, Business Impact. Alert on thresholds, not just outages.
  • Logging & tracing: Structured JSON logs with case_id, trace_id, span_id. Distributed tracing for debugging non-deterministic runs.
  • Cost management: Per-agent daily budgets, per-case limits, throttle at 95%, kill switch at 100%. Optimization: model routing, caching, summarization.
  • Kill switch: Automatic (safety, cost) and manual (security, regulatory). Drain in-flight cases. Incident response playbook with SLAs.

Bridge to next lesson

What's next: Capstone: ERP + Copilot + AI Agent Automation — apply everything you've learned to design a governed AI agent ecosystem for a real business scenario.