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
| Prerequisite | Why it matters |
|---|---|
| Evaluation & Testing | Understands evaluation metrics and regression testing |
Lesson roadmap
By the end of this lesson you will be able to:
- Design a safe deployment pipeline for agents (canary, feature flags, rollback).
- Build monitoring dashboards covering health, quality, cost, and safety.
- Implement cost management: budgets, alerts, automatic throttling.
- Design logging, tracing, and debugging for multi-step agent runs.
- Create a kill switch and incident response procedures.
- 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 app | Agent |
|---|---|
| Deterministic behavior | Non-deterministic (temperature, sampling) |
| Single version in prod | Multiple versions may run simultaneously (A/B, shadow) |
| Rollback = redeploy previous version | Rollback = disable agent + drain in-flight cases |
| Health = HTTP 200 | Health = task success rate, safety, cost, latency |
Deployment stages
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Dev / │ │ Staging │ │ Canary │ │ Production │
│ Local │───▶│ (Full test │───▶│ (5% traffic)│───▶│ (100%) │
│ Testing │ │ suite) │ │ │ │ │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘Stage gates
| Stage | Entry criteria | Exit criteria |
|---|---|---|
| Dev | Code compiles, unit tests pass | Developer validates locally |
| Staging | Dev complete, unit tests pass | Full regression suite passes (all metrics green) |
| Canary | Staging green, feature flag ready | 48 hours with: no safety violations, task success ≥ target, cost ≤ budget, latency ≤ SLA |
| Production | Canary green, stakeholder sign-off | Ongoing 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 agentRollback procedure
| Scenario | Rollback action | Time to execute |
|---|---|---|
| Canary fails | Set enabled: false, rollout_percentage: 0 | < 30 seconds |
| Production safety violation | Set kill_switch: true, drain in-flight cases | < 60 seconds |
| Model regression | Revert model to previous version | < 2 minutes |
| Cost spike | Set 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
| Metric | Target | Alert threshold |
|---|---|---|
| Request success rate | ≥ 99.5% | < 99% for 5 min |
| Agent availability | 100% (no downtime) | Any downtime |
| Error rate (5xx) | < 0.1% | > 1% for 5 min |
| Timeout rate | < 1% | > 5% for 5 min |
| In-flight cases | Stable | Growing > 10% / hour (stuck cases) |
Dashboard 2: Quality & Safety
| Metric | Target | Alert threshold |
|---|---|---|
| Task success rate | ≥ 95% (happy path) | < 90% for 1 hour |
| Safety violations | 0 | Any 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 blocked | Tracked | Spike > 10x baseline |
Dashboard 3: Performance & Cost
| Metric | Target | Alert 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 case | Stable | > 2x baseline (prompt stuffing?) |
Dashboard 4: Business Impact
| Metric | Target | Alert 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 completeWhy 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
| Driver | Control mechanism |
|---|---|
| Model choice | Use cheaper model for simple tasks (e.g., gpt-4o-mini for classification, gpt-4.1 for reasoning) |
| Token usage | Limit context: summarize history, truncate RAG, cap max iterations |
| Tool calls | Cache tool results within a case. Batch similar calls. |
| Retry loops | Exponential backoff. Max retries. Circuit breaker. |
| Volume | Rate 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 resultCost optimization patterns
| Pattern | Savings | Trade-off |
|---|---|---|
| Model routing | 60–80% | Simple tasks → small model; complex → large model |
| Prompt caching | 30–50% | Cache system prompt + static context |
| RAG chunk limiting | 20–40% | Top-3 chunks instead of top-10 |
| History summarization | 40–60% | Summarize after 5 iterations instead of full history |
| Tool result caching | 10–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
| Trigger | Activation | Who can activate |
|---|---|---|
| Safety violation | Automatic (monitoring detects PII leak, unauthorized action) | System (auto) |
| Cost spike | Automatic (daily budget 100% reached) | System (auto) |
| Model misbehavior | Manual (operator sees anomaly) | Agent Operator, Platform Team |
| Security incident | Manual (security team detects compromise) | Security Team, Platform Team |
| Regulatory order | Manual (compliance/legal) | Compliance Officer, Legal |
Incident response playbook
| Phase | Actions | Owner | SLA |
|---|---|---|---|
| Detect | Alert fires (safety, cost, quality, availability) | Monitoring | Immediate |
| Triage | Check dashboards. Confirm real vs. false positive. Assess blast radius. | Agent Operator | < 5 min |
| Contain | Activate kill switch / drain mode / throttle. Route traffic to human fallback. | Agent Operator | < 2 min |
| Investigate | Pull traces. Check logs. Identify root cause. | Agent Operator + Platform | < 30 min |
| Resolve | Fix code / config / data. Test in staging. Deploy fix. | Platform Team | Varies |
| Recover | Disable kill switch. Ramp up rollout. Monitor closely. | Agent Operator | < 1 hour after fix |
| Postmortem | Write 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: 2via 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.
- First 5 min: Confirm which agent and the $200 vs $5 budget on the cost dashboard. Set
rollout_percentage: 10, tighten throttle (for examplethrottle_threshold_pct: 50), and route the rest to the human queue. - First 30 min: Read traces for token drivers — new prompt, loop iterations, tool retries, or prompt stuffing. Check whether history summarization or a per-case cap was removed.
- First 2 hours: Restore summarization and per-case token caps; regression in staging; canary the fix at 5% and watch cost; ramp only if cost returns to baseline; add "tokens per iteration" to the dashboard; write the postmortem.
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.
- Likely cause: Observe is not detecting completion, or
max_iterationsis not enforced in code. - Check: At iteration 3, what did Observe say? Common causes: tool success not parsed, vague termination text, state not serialized so the agent "forgets" it finished.
- Fix without killing the process: Complete that case through the admin path (mark complete, attach the expected output) or hot-patch Observe via a feature flag. Do not kill the process mid-case — that corrupts state and the audit trail.
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.
- Traffic split: Day 1: 5% new / 95% current; Day 2: 20%; Day 3: 50%; Day 4: 100% — each stage only if the previous is green.
- Duration: At least 24 hours per stage (daily cycle); 48 hours for the first stage.
- Success criteria: Task success ≥ baseline − 1%; safety = 0; p95 latency ≤ baseline + 10%; cost per case ≤ baseline + 15%; groundedness ≥ baseline − 2%; escalation ≤ baseline + 2%.
- Rollback triggers (any one): Any safety violation; success < baseline − 3%; p95 > baseline + 25%; cost > baseline + 30%; new error pattern in traces.
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
- Cost dashboard: daily cost > 1.2× budget; tokens per case > 2× baseline
- Health dashboard: in-flight cases climbing; timeout rate up
- ERP: multiple PO numbers sharing the same request id
- Traces: the same
trace_idshows many child spans namedcreate_purchase_orderafter 5xx/timeout - Kill switch and
hard_stop_threshold_pctwere still false / unused
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
- Duplicate commitments to vendors; buyers spent the afternoon cancelling POs
- Model spend blew the weekly budget by day two
- Finance froze further agent writes until a rollback drill completed
- Operators lost trust in "the dashboard is green" because cost and write-error views were not on the same page
Diagnostic steps
- Confirm blast radius: count POs per request id; sum committed amount.
- Open traces: iteration count, retry count, token growth per iteration.
- Check feature flags:
kill_switch,rollout_percentage,max_iterations, budget thresholds. - Verify whether
create_purchase_orderrequired an idempotency key and whether the circuit breaker opened.
Correction
- Contain:
rollout_percentage: 0orkill_switch: true; drain in-flight cases; route new requests to humans (first five minutes of Q1). - Cancel or reverse duplicate POs with a documented compensating action; leave the audit trail intact.
- Enforce idempotency on create; cap retries with exponential backoff; open a circuit breaker after repeated ERP failures.
- Enforce daily and per-case token/cost limits in the runtime path; throttle at 95%; hard-stop at 100%.
- Restore history summarization so retries cannot grow context without bound.
Validation after correction
- Staging: force an ERP timeout after a successful create — only one PO exists; retries return the same PO number.
- Load a stuck-loop fixture:
max_iterationsstops the case; tokens stay under the per-case cap. - Canary 5% for 48 hours: cost ≤ budget, zero duplicate POs, safety alerts quiet.
- Tabletop: operator hits kill switch in < 60 seconds and drain completes without new writes.
Preventive control
- Production-readiness checklist: budgets, circuit breaker, idempotency, rollback, kill switch, named incident owner.
- Alerts on cost, timeout rate, and "duplicate write" (same idempotency key reused) page the Operator.
- No 100% rollout until the canary exit criteria in this lesson are green.
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
| Item | Value |
|---|---|
| Writes | issue_refund (money out) |
| Budget (from this lesson) | $2.00/day, $0.05/case, 8,000 tokens/case; alert 80%, throttle 95%, hard stop 100% |
| SLA | p95 < 30s; task success ≥ 95% happy path; safety = 0 |
| Known risk | ERP/payment tool timeouts; retry storms; loop past max_iterations |
Constraints
- Use dashboards, flags, budgets, kill switch, and the incident playbook already in this lesson.
- Do not invent a new APM vendor API. Refer to metrics, flags, and traces by the names already used.
- Rollback must drain in-flight cases; do not "kill the process."
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
- [ ] Entry/exit criteria for canary and production
- [ ] Four dashboard areas with at least one alert each
- [ ] Budget, throttle, hard stop, circuit breaker, rollback, kill switch all named
- [ ] Incident roles and SLAs from the playbook
- [ ] Validation that a timeout cannot create two refunds
Complete model solution
Readiness (stage gates):
| Stage | Exit criteria before the next stage |
|---|---|
| Staging | Full regression green (success, safety, groundedness, cost fixtures) |
| Canary | 5% traffic, 48 hours: no safety violations, success ≥ target, cost ≤ budget, latency ≤ SLA, zero duplicate issue_refund for the same case id |
| Production | Canary 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:
| Dashboard | Metric | Alert |
|---|---|---|
| Health | Timeout rate, in-flight growth | Timeout > 5% for 5 min; in-flight +10%/hour |
| Quality / Safety | Task success, safety violations, injection blocks | Any safety = page; success < 90% for 1 hour |
| Performance / Cost | p95, cost/case, daily cost, tokens/case | Cost > 1.2× daily; tokens > 2× baseline |
| Business | Auto-resolve %, override rate | Overrides > 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
- Tabletop the $5 → $200 spike using Q1 timings; record the actual flag changes.
- Staging: timeout-after-success test; assert one refund.
- 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
- Use this lesson only: pipeline, dashboards, logging/tracing, cost controls, kill switch, playbook.
- No new ERP product API. You may keep
post_match_resultas the write name.
Constraints
- Incorrect action to prevent: posting a match that releases payment on the wrong invoice, or posting twice after a timeout.
- Cost to prevent: retry loops and unbounded tokens.
- Rollback must preserve audit for every match attempt.
Required controls
Monitoring, budgets, circuit breakers, rollback, kill switch, and incident ownership must all appear with owners and numeric thresholds.
Measurable acceptance criteria
- [ ] Canary % and minimum hours stated; 50% Monday is either rejected or gated
- [ ] Daily and per-case cost/token limits with 80/95/100 behavior
- [ ] Circuit breaker condition on the match/write tool
- [ ] Rollback + drain steps with target times from this lesson
- [ ] Kill switch: automatic triggers and manual roles
- [ ] At least four alerts with thresholds (health, safety, cost, business or quality)
- [ ] Incident phases Detect → Postmortem with owners and SLAs
- [ ] Test named: timeout after a successful post does not post a second time
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
- [ ] Plan would stop Brightline-style duplicates, not only "watch the cost chart"
- [ ] In-flight drain is specified; process kill is forbidden
- [ ] Feature-flag field names are taken from this lesson's style (
enabled,rollout_percentage,kill_switch,drain_mode) - [ ] You can explain the first five minutes without opening a new vendor runbook
- [ ] Residual risk (what can still go wrong at 5% canary) is written down
Common mistakes
| Mistake | Symptom | Cause | Consequence | Correction | Preventive control |
|---|---|---|---|---|---|
| 100% on a green staging suite | Cost or safety breaks on day one | Staging volume ≠ production | Runaway spend or bad writes at full traffic | Canary 5% / 48h with exit criteria | Stage-gate table signed before prod |
| Unlimited tool retries | Duplicate POs or refunds | Timeout treated as "try again" | Incorrect commitments; token spike | Idempotency + capped backoff + circuit breaker | Write-tool contract test in staging |
| Budget only on a slide | Daily cost 40× plan | Runtime never reads AGENT_BUDGETS | Hard-stop never fires | Enforce alert/throttle/stop in code | Budget check in the request path |
| Kill switch untested | Debate while the agent keeps writing | Flag exists but never drilled | Slow containment | Monthly kill + drain drill | IR playbook SLA: contain < 2 min |
| Kill the process | Missing spans, half-written ERP state | "Just stop the pods" | Corrupt cases, weak audit | Drain mode; complete or hand off | Runbook: never kill mid-case |
| Cost dashboard only | Duplicates found by Finance next week | Ops watched $ not write errors | Incorrect actions missed | Alert on duplicate idempotency keys | Quality + cost on the same incident view |
Quick checks
- 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.
- Predict the result: Daily tokens hit 100% of budget but
hard_stop_threshold_pctis 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.
- Diagnose the failure: p99 latency is 120s, in-flight cases grow, average loop iteration is 5,
max_iterationsis 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.
- 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.
- 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
| Control | This lesson |
|---|---|
| Accountable owner | Agent Owner for business risk; Operator for flags and first response |
| Approved users | Roles allowed to invoke the agent in each rollout percentage |
| Data sources | Production logs and traces with sanitized payloads; no secret material in log fields |
| Least privilege | Production write tools only when the flag allows; canary before 100% |
| Prohibited | Unlimited retries, process-kill mid-case, 100% rollout without canary exit criteria |
| Validation | Staging regression + timeout-after-success test + kill-switch drill |
| Approval gate | Canary and prod require Operator + Finance (budget) + quality gates from Evaluation & Testing |
| Escalation | Playbook: Detect → Triage → Contain → Investigate → Resolve → Recover → Postmortem |
| Audit | Structured logs with case_id, trace_id, version, tool name; retain enough to reconstruct writes |
| Fallback | Human queue when killed, throttled, or circuit-open |
| Stop | Automatic 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.