<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Eldar Muratov</title>
    <description>The latest articles on DEV Community by Eldar Muratov (@muratover).</description>
    <link>https://dev.to/muratover</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4205052%2Fced29790-2223-46eb-a595-8cb53b2d3695.png</url>
      <title>DEV Community: Eldar Muratov</title>
      <link>https://dev.to/muratover</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muratover"/>
    <language>en</language>
    <item>
      <title>Agent Systems for Newbies: Building a Support Agent From One File to Temporal, Sagas and a Circuit Breaker</title>
      <dc:creator>Eldar Muratov</dc:creator>
      <pubDate>Wed, 11 Nov 2026 18:39:21 +0000</pubDate>
      <link>https://dev.to/muratover/agent-systems-for-newbies-building-a-support-agent-from-one-file-to-temporal-sagas-and-a-circuit-2fhf</link>
      <guid>https://dev.to/muratover/agent-systems-for-newbies-building-a-support-agent-from-one-file-to-temporal-sagas-and-a-circuit-2fhf</guid>
      <description>&lt;p&gt;A customer writes to support: "My parcel never arrived, give me my money back." You can write an agent that answers this in one evening. The loop from part 1, three tools, and in the demo it answers correctly. Then the process restarts in the middle of a refund, the model provider goes down for half an hour, the customer hits "send" twice. And it turns out the agent is a small part of the system.&lt;/p&gt;

&lt;p&gt;This is the third and last part of a series. In &lt;a href="https://dev.to/muratover/ai-engineering-for-newbies-agents-mcp-tokens-and-caching-with-numbers-1gh1"&gt;the first&lt;/a&gt; we looked at the agent loop, tokens and caching. In &lt;a href="https://dev.to/muratover/ai-agents-in-production-for-newbies-tools-rag-reliability-and-evals-4boa"&gt;the second&lt;/a&gt; we collected the practices: retries, idempotency, sagas, Temporal, human approval, evals. Here we put them together into one system. We start with an agent in one file, and at every step we run into a problem. Each problem adds a component, and the system diagram grows along with the text. The code, as before, is pseudocode: English names, as in real Python.&lt;/p&gt;

&lt;p&gt;I draw the diagrams with &lt;a href="https://c4model.com" rel="noopener noreferrer"&gt;C4&lt;/a&gt;. It's a way to draw architecture at different zoom levels, like a map. Context shows the system as one box among people and external systems. Container breaks it into applications and data stores. Component breaks one application into parts. The C4 authors recommend the first two levels to every team and the third only when it adds something. A container in C4 isn't Docker: it's anything that has to be running for the system to work, such as a service, a database or a queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An agent in a single process loses everything on restart. Keep the case and the dialog history in a database, and run the processing itself in Temporal: one workflow per case, Workflow ID equal to the dialog id.&lt;/li&gt;
&lt;li&gt;Temporal has its own database, and business data doesn't go there. You run the workers with your code; the Temporal Service doesn't execute it.&lt;/li&gt;
&lt;li&gt;A retry and a circuit breaker are different things. A retry repeats a transient failure; a circuit breaker stops calling a service that is down. Its place is in front of the model provider, in an LLM gateway.&lt;/li&gt;
&lt;li&gt;The model decides, code moves the money: the refund runs as a saga where paying the money back is the pivot step, the point of no return. An operator approves large amounts.&lt;/li&gt;
&lt;li&gt;The agent doesn't have to do everything. A router on a small model sends FAQ questions to a single call, "where is my order" to a chain, and only a disputed refund to the agent.&lt;/li&gt;
&lt;li&gt;Add a component when the pain it treats shows up. Checklist at the end.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Step 0. An agent in one file
&lt;/h2&gt;

&lt;p&gt;Let's start with what we can do after part 1. The script keeps the dialog history in memory, calls the model and runs the tools the model asked for. There are three tools: &lt;code&gt;track_order_status&lt;/code&gt; checks the order status with the delivery service, &lt;code&gt;get_refund_policy&lt;/code&gt; fetches the refund rules, &lt;code&gt;refund_payment&lt;/code&gt; returns the money. A similar &lt;code&gt;track_order_status&lt;/code&gt; appears in OpenAI's guide to agents, where the example is also about support.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: a support agent in one file&lt;/span&gt;
&lt;span class="n"&gt;history&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;llm&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;track_order_status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                                       &lt;span class="n"&gt;get_refund_policy&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;refund_payment&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stop_reason&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"tool_use"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;call&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;tool_calls&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;run_tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At the Context level the system looks like this. A customer writes; an operator joins now and then. Outside are the model provider, the shop with its orders, the delivery service, the payment system and a knowledge base with articles.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fohc7h9xr1neylthzf686.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fohc7h9xr1neylthzf686.png" alt=" " width="800" height="675"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;C4, level 1. External systems aren't ours; we only call them.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the demo this works. The problems start when there is more than one customer. The history lives in the process memory, so any restart wipes every dialog. The script serves one customer at a time. And if the process crashed between &lt;code&gt;refund_payment&lt;/code&gt; and the reply to the customer, nobody knows whether the money went back or not.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 1. An API and a database
&lt;/h2&gt;

&lt;p&gt;The first thing we add is an entry point and memory. The script from step 0 did everything at once: it took the message, called the model and waited for its answer. We split it into two programs.&lt;/p&gt;

&lt;p&gt;The API is a web service the chat sends the customer's message to. It validates the request, saves the message to the database, queues a "process the dialog" task there and immediately tells the chat the message was accepted. The API doesn't call the model, so it answers in milliseconds.&lt;/p&gt;

&lt;p&gt;A worker is a separate background process where the agent itself lives, that is, the loop from step 0. The worker takes a task from the database, reads the dialog history, calls the model and the tools and writes the reply to the database, where the chat picks it up. You run several workers, and each takes its own task. The worker never talks to the customer directly.&lt;/p&gt;

&lt;p&gt;The dialog history now lives in the database and survives any restart. SDKs have ready-made history stores. In the OpenAI Agents SDK these are sessions: SQLite, Redis, SQLAlchemy, MongoDB and your own implementations.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsjsi8q1f44iyndsmtcnm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fsjsi8q1f44iyndsmtcnm.png" alt=" " width="800" height="1119"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;C4, level 2. The orange frame marks what was added in this step.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Why split them? The agent spends anywhere from seconds to a minute on one case. If the API did that work, every case would hold a connection open the whole time. So the slow work goes to workers: the API stays fast, and you add workers as load grows.&lt;/p&gt;

&lt;p&gt;But the main problem is still there. Say a worker crashes in the middle of a case. It has checked the order status and called &lt;code&gt;refund_payment&lt;/code&gt;, but the response never came back. A new worker picks the case up from the start. Call the refund again? If the first one went through, the customer gets paid twice. Don't call it? If it didn't go through, the customer gets nothing. The database knows what the customer said, but not at which step processing stopped.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2. Temporal: every case is a workflow
&lt;/h2&gt;

&lt;p&gt;This is where we need durable execution, which we covered in part 2. Temporal records every step in a history. After a crash another worker replays the history and continues from the same place. Finished steps don't run a second time: their results come from the history.&lt;/p&gt;

&lt;p&gt;It's important to understand what Temporal is physically made of, because this is where people get confused most often. The Temporal Service is a server plus its own database. Inside, the server is split into four services. Frontend accepts calls, rate-limits them and checks permissions. History holds workflow state, Matching keeps the task queues, and Worker runs internal background jobs. Temporal has its own database: PostgreSQL, MySQL or Cassandra. That database is the only thing it needs to run.&lt;/p&gt;

&lt;p&gt;And Temporal doesn't run your code. The documentation says it plainly: workers live outside the Temporal Service, and the application team writes and runs them. A worker polls the task queue itself and takes a new task only when it's free. That spreads the load across workers without a load balancer. If a worker crashes, the task stays in the queue and waits for the next one.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F35l10tljugfcn7rx3zt1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F35l10tljugfcn7rx3zt1.png" alt=" " width="800" height="1119"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Temporal keeps the processing progress; the app database keeps the data.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here's how the agent loop fits in. The loop lives in the workflow, and each model call and each tool call become activities. That's how Temporal's official integration with the OpenAI Agents SDK works: the loop, tool selection and handoffs between agents run in the workflow, model calls run as activities and aren't repeated on recovery. According to Temporal itself, OpenAI's Codex web agent runs on it. That's the vendor's claim; I couldn't find a write-up from OpenAI.&lt;/p&gt;

&lt;p&gt;How does a case get into a workflow? You choose the workflow ID, and it should carry business meaning, such as an order number. We'll use the dialog id. Temporal guarantees that only one open execution can exist with a given ID. If the customer hits "send" twice, the second start won't create a duplicate. Update-with-Start is even more convenient. It's one call from the API: if a workflow for this dialog is already running, the new message goes into it; if not, the workflow starts. The call must specify a workflow ID conflict policy, here Use Existing. The API can also wait for the reply. The API no longer queues a task in the database: Temporal now holds the task queue, and the app database stores only the messages themselves.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: the API accepts a customer message&lt;/span&gt;
&lt;span class="nd"&gt;@post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/chat/{dialog_id}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;new_message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dialog_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;db&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;save_message&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dialog_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;temporal&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;update_with_start&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;workflow&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;support_case&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;workflow_id&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"dialog-{dialog_id}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;id_conflict_policy&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;USE_EXISTING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;   &lt;span class="c1"&gt;# workflow already running: the message goes into it&lt;/span&gt;
        &lt;span class="n"&gt;update&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"new_message"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;arg&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are three ways to write into a workflow. A Signal is an asynchronous message with no reply. An Update is a synchronous write: the sender waits for a result or an error, and the workflow can validate the request before accepting it. A Query reads the current state and writes nothing to the history. A new customer message fits an Update, an operator's decision fits a Signal, and the UI reads the status with a Query.&lt;/p&gt;

&lt;p&gt;So why not keep everything in Temporal, since it stores the history anyway? The history of one execution is limited: 51,200 events or 50 MB. After that the execution is terminated. For a long dialog there's Continue-As-New: the workflow hands its state to a new execution with the same ID and a clean history. But keep customer data, orders and the conversation history the operator reads in the app database. One more reason: the Workflow ID is stored in plain text and visible in the UI and logs, so it must not contain personal data.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 3. An LLM gateway and a circuit breaker
&lt;/h2&gt;

&lt;p&gt;Say the model provider goes down for half an hour. Temporal does what it should: it retries the activity with growing backoff, by default with no limit on attempts. A hundred workers with a thousand open cases all hammer the dead API. Every attempt waits for a timeout and holds a connection. When the provider comes back, the whole queue hits it at once.&lt;/p&gt;

&lt;p&gt;A retry is built for a failure that clears in seconds. For a long outage there's a different pattern, the circuit breaker. Martin Fowler describes it like this. A wrapper around the call counts failures. After a threshold it trips, and further calls get an error right away, without going to the service. After a while the breaker lets a trial call through. If it succeeds, the breaker closes again.&lt;/p&gt;

&lt;p&gt;Microsoft's description of the pattern stresses the difference. A retry repeats an operation expecting it to succeed. A circuit breaker prevents an operation that is likely to fail. You can combine them: the retry goes through the breaker. But the retry must understand the breaker's error and stop trying if the failure isn't transient.&lt;/p&gt;

&lt;p&gt;Where do you put the breaker? There are many workers, and each has its own memory. If the breaker lives in worker memory, each worker learns separately that the provider is down. So the breaker state has to be shared. A convenient place is an LLM gateway, a separate service between the workers and the providers. LiteLLM, for example, does what we need. It takes a model out of rotation if it failed more than a set number of times in a short window (in the docs example, more than three failures, and the model "cools down" for 30 seconds), switches to a fallback model and keeps this state in Redis, shared by all instances.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F804a6lqxo1laj1le8nqw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F804a6lqxo1laj1le8nqw.png" alt=" " width="800" height="1119"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The breaker in the gateway is shared by all workers. Its state is in Redis.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;What follows is my advice, not a rule from the docs. Let the model-call activity tell two kinds of errors apart. A transient error from the provider is retried by the Temporal policy. A "breaker open" error means the provider is down, and the workflow decides for itself: switch to a fallback model, wait longer or hand the case to an operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: calling the model through the gateway&lt;/span&gt;
&lt;span class="nd"&gt;@activity&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;call_llm&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;gateway&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;chat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"main"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fallback&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"backup"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"all_models_cooling_down"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;NonRetryableError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"providers unavailable"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# don't burn Temporal retries&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;

&lt;span class="nd"&gt;@workflow&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;support_case&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call_llm&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;retry_policy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;NonRetryableError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;hand_off_to_operator&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"model unavailable"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same breakers go in front of any external API that can be down for a long time: the delivery service, the payment system. The rule is the same: the breaker state is shared by all workers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 4. A saga and operator approval
&lt;/h2&gt;

&lt;p&gt;Now the refund itself. It touches three systems. First, create a return label with the delivery service. Then pay the money back through the payment system. Then notify the customer and update the order in the shop. There's no shared transaction across these systems. How a saga solves this was covered in detail in part 2: every step has a compensation prepared in advance, and on failure the completed steps are undone in reverse order.&lt;/p&gt;

&lt;p&gt;Here I'll add a concept that Microsoft's description of the pattern calls a pivot transaction, the point of no return. Steps before it can be undone. After it there's nothing to undo, and the remaining steps have to be driven to completion, retried as many times as it takes. In our case the pivot is paying the money back. The label can be cancelled. Once the money is gone, the email to the customer and the order update must happen, even if that takes a day of retries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: the refund as a saga inside the workflow&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;refund&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;label&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;create_return_label&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;refund_payment&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;# point of no return&lt;/span&gt;
    &lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;PermanentError&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cancel_return_label&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;label&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                        &lt;span class="c1"&gt;# compensation&lt;/span&gt;
        &lt;span class="k"&gt;raise&lt;/span&gt;
    &lt;span class="c1"&gt;# forward only from here: retry until it succeeds&lt;/span&gt;
    &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;notify_customer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;FOREVER&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;update_order&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;retry&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;FOREVER&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every action gets an idempotency key: the decision id. If Temporal repeats a step after a failure, the payment system returns the old response for the same key instead of charging again. A saga in Temporal is written as ordinary code in the workflow. Microsoft calls this variant orchestration: one coordinator knows all the steps and runs the compensations itself.&lt;/p&gt;

&lt;p&gt;The model shouldn't carry out a large refund on its own. OpenAI's guide explicitly lists cancelling an order, a large refund and a payment among the reasons to bring in a human. An operator console appears in the system. The workflow shows it the decision and waits for a signal. The wait is recorded in the history, so the operator can answer an hour later, and the workers can restart in the meantime. How this works and what rules apply to approval is in part 2.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjut1uxpgtst681k50dxp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fjut1uxpgtst681k50dxp.png" alt=" " width="800" height="1119"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;A waiting workflow doesn't occupy a worker: its state lives in the history.&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 5. Chain or agent
&lt;/h2&gt;

&lt;p&gt;The system is now reliable, but expensive and slow. Every case goes through the full agent loop, even the question "how do I return an item?", which has an article in the knowledge base. Yet cases come in three kinds. A question from the knowledge base needs one model call with search. "Where is my order" is solved by a chain: extract the number, call &lt;code&gt;track_order_status&lt;/code&gt;, write a reply. Only a disputed refund needs judgment: the order may have reached the pickup point, the customer may not have collected it in time, the rules differ between products.&lt;/p&gt;

&lt;p&gt;A chain (workflow, agents chain) is a system where the steps are written in code in advance. An agent is a system where the model itself decides which step to take next. That's how Anthropic, OpenAI and LangGraph separate them. Microsoft adds a ladder of complexity: a direct model call, a single agent with tools, multiple agents. Their advice is simple: take the lowest level that reliably solves the task. If a good prompt is enough, you don't need an agent.&lt;/p&gt;

&lt;p&gt;Anthropic describes splitting by case type as the "routing" pattern, and its example is exactly support: general questions, refunds and technical support go to different processes with their own prompts and tools. A router on its own isn't an agent yet. The model makes one decision there and doesn't spin in any loop.&lt;/p&gt;

&lt;p&gt;Inside the worker we can now see several components. This is the Component level in C4.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F130sj5gjykaj7exgqn8j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F130sj5gjykaj7exgqn8j.png" alt=" " width="800" height="976"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;C4, level 3. A dashed orange frame marks where the model decides; plain code and the saga move the money.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: one customer message inside the workflow&lt;/span&gt;
&lt;span class="n"&gt;kind&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;classify&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"small"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                  &lt;span class="c1"&gt;# router: one call&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;kind&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"faq"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;answer_from_kb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                       &lt;span class="c1"&gt;# single call&lt;/span&gt;
&lt;span class="k"&gt;elif&lt;/span&gt; &lt;span class="n"&gt;kind&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s2"&gt;"where_is_order"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;track_order_status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;order&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;write_reply&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                           &lt;span class="c1"&gt;# chain&lt;/span&gt;
&lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;decision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;agent_loop&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;READ_ONLY_TOOLS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;            &lt;span class="c1"&gt;# agent&lt;/span&gt;
    &lt;span class="nf"&gt;check_rules&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                                            &lt;span class="c1"&gt;# code: limits, threshold&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="no"&gt;THRESHOLD&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;approved&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;wait_for_signal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"operator_decision"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;              &lt;span class="c1"&gt;# Signal from the console&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;approved&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;hand_off_to_operator&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;refund&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                                                 &lt;span class="c1"&gt;# saga&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two details are worth noting. The agent gets only read tools: order status, rules, customer history. It proposes a decision but doesn't move money. The money is moved by the saga, plain code, after the rule check and, for a large amount, operator approval.&lt;/p&gt;

&lt;p&gt;The second detail is the right model for the job. OpenAI advises putting a small model on classification and trusting the refund decision to a strong one. The difference is noticeable: a thousand classifications at 2,000 input tokens each cost $0.23 on Claude Haiku 5.5 and $4.50 on Sonnet 5.5, at list prices as of the end of October 2026.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 6. Traces and an outbox
&lt;/h2&gt;

&lt;p&gt;An operator opens a complaint: "The agent refused a refund even though the parcel never arrived." Why did it decide that? Which tools did it call, what did they return, how much did the case cost? Without a trace there are no answers.&lt;/p&gt;

&lt;p&gt;We add trace collection. Every case gets a trace that shows each model and tool call, tokens, time and cost. The format is standard, OpenTelemetry with the GenAI conventions, which we covered in part 2. I would link the trace to the Workflow ID: then from a complaint the operator can get to both the Temporal history and the call trace.&lt;/p&gt;

&lt;p&gt;One last small thing: events. After a refund the CRM has to learn that the order is closed, and analytics that a refund happened. If the worker updates the database first and then crashes before sending the event to the broker, the CRM never learns about the refund. That's what the transactional outbox pattern is for. The event is written to an outbox table in the same transaction as the order change. A separate process reads the table and sends the events to the broker. The record and the event either both appear or neither does.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc0muwskicwj99aumyog2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc0muwskicwj99aumyog2.png" alt=" " width="800" height="1197"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;C4, level 2, final version. The numbers on the containers show where each pattern lives.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  What we ended up with
&lt;/h2&gt;

&lt;p&gt;The one-file agent turned into a system of about ten components. The easiest way to sum it up is which pattern sits where and what it protects against:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Workflow per case&lt;/strong&gt; (Temporal): a worker crash doesn't lose the processing progress.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Workflow ID = dialog id&lt;/strong&gt;: a double send doesn't create a second handler.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retries&lt;/strong&gt; (Temporal activity policy): short failures of the model and APIs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Circuit breaker&lt;/strong&gt; (LLM gateway, shared state in Redis): a long provider outage doesn't clog the workers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Idempotency key&lt;/strong&gt; (every action toward an external system): a repeated step doesn't pay the money back twice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Saga with a point of no return&lt;/strong&gt; (code in the workflow): a failure in the middle of a refund doesn't leave the system half done.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Operator approval&lt;/strong&gt; (Signal from the console): a large refund doesn't go through without a human.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Router&lt;/strong&gt; (a chain on a small model): the agent works only where judgment can't be avoided.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Outbox&lt;/strong&gt; (app database): an event isn't lost between the write and the send.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Traces&lt;/strong&gt; (OpenTelemetry): you can see why the agent decided what it did and what it cost.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What matters in this diagram is less the list of components than the order in which they appeared. Each one appeared when something broke without it. In a small project half of them may not be needed for a long time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Checklist: which component to add for which pain
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Dialogs are lost on restart: history in a database, entry through an API.&lt;/li&gt;
&lt;li&gt;You can't tell at which step processing failed: durable execution, a workflow per case.&lt;/li&gt;
&lt;li&gt;Duplicates from a double send: a Workflow ID from a business identifier, Update-with-Start.&lt;/li&gt;
&lt;li&gt;Business data wants to go into Temporal: no, it belongs in the app database; Continue-As-New for long workflows.&lt;/li&gt;
&lt;li&gt;The provider is down and the workers hang: an LLM gateway with a circuit breaker and a fallback model; the breaker's error isn't retried.&lt;/li&gt;
&lt;li&gt;An action across several systems: a saga; find the point of no return, and after it go forward only.&lt;/li&gt;
&lt;li&gt;Repeating a step is dangerous: an idempotency key toward the external system.&lt;/li&gt;
&lt;li&gt;An action with money: the agent only proposes, code checks, an operator approves the large ones.&lt;/li&gt;
&lt;li&gt;The agent is expensive and slow: a router, chains for typical cases, a small model for classification.&lt;/li&gt;
&lt;li&gt;You can't tell why the agent decided what it did: traces linked to the Workflow ID.&lt;/li&gt;
&lt;li&gt;Events get lost between the database and the broker: an outbox.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The agent that answers "my parcel never arrived, give me my money back" takes up one box out of ten in this system. The other nine are there for the customer's money and the operator's peace of mind, not for the model. Almost all of them are familiar from ordinary backend work. Only one thing is new: inside there's now a component that decides differently every time. All the architecture around it is there so that this doesn't become a problem.&lt;/p&gt;

&lt;p&gt;Which box in this diagram would you start with in your own system, and which would you throw out?&lt;/p&gt;

&lt;h2&gt;
  
  
  Series "AI Engineering for Newbies"
&lt;/h2&gt;

&lt;p&gt;This is a series of three articles.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://dev.to/muratover/ai-engineering-for-newbies-agents-mcp-tokens-and-caching-with-numbers-1gh1"&gt;"AI Engineering for Newbies: Agents, MCP, Tokens and Caching, With Numbers"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/muratover/ai-agents-in-production-for-newbies-tools-rag-reliability-and-evals-4boa"&gt;"AI Agents in Production for Newbies: Tools, RAG, Reliability and Evals"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;"Agent Systems for Newbies: Building a Support Agent From One File to Temporal, Sagas and a Circuit Breaker" (you are reading it now)&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>ai</category>
      <category>agents</category>
      <category>llm</category>
      <category>architecture</category>
    </item>
    <item>
      <title>AI Agents in Production for Newbies: Tools, RAG, Reliability and Evals</title>
      <dc:creator>Eldar Muratov</dc:creator>
      <pubDate>Wed, 11 Nov 2026 18:33:29 +0000</pubDate>
      <link>https://dev.to/muratover/ai-agents-in-production-for-newbies-tools-rag-reliability-and-evals-4boa</link>
      <guid>https://dev.to/muratover/ai-agents-in-production-for-newbies-tools-rag-reliability-and-evals-4boa</guid>
      <description>&lt;p&gt;An agent solves a task in 30 steps: it calls the model, searches, writes to the database, calls the model again. Say each step fails once in a hundred times: the network blinked, the API answered "overloaded". Then the whole task gets to the end 74% of the time. One task in four fails. At 3% failures per step, only 40% get to the end.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frpunwrldzw9jkqrfozxr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Frpunwrldzw9jkqrfozxr.png" alt=" " width="800" height="493"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;A back-of-the-envelope calculation: step failures are independent and transient.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In a demo the agent gets through 10 steps out of 10. In production it runs thousands of tasks, and everything surfaces at once. The model mixes up tools, the context is full of junk, search doesn't find what's needed. The process crashes halfway, and a prompt tweak breaks something that used to work.&lt;/p&gt;

&lt;p&gt;This is the second part of a series. In &lt;a href="https://dev.toPART1_DEVTO_URL"&gt;the first&lt;/a&gt; we looked at how the agent loop works and what it costs. This one collects the practices that separate a demo from production: tools, context, RAG, loop control, reliability, observability, evals and security. Reliability takes up the most space. Almost all of it is familiar from backend work, but an agent has a sharper trap than usual. What hurts is not the crash but the repeat.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fewer tools, but bigger ones. Short responses, and errors written so the model can fix them.&lt;/li&gt;
&lt;li&gt;Keep only what's needed in the context: load things as you go, compress the history, hand big chunks to subagents.&lt;/li&gt;
&lt;li&gt;A knowledge base under 200,000 tokens fits into the prompt whole. If it's bigger, search by meaning and by keywords and rerank: at Anthropic this cut retrieval failures from 5.7% to 1.9%.&lt;/li&gt;
&lt;li&gt;Start with a chain, not an agent. Give an agent a turn limit, a dollar budget and a plan B: a stuck agent at 100 turns costs 5.3 times as much as a normal task.&lt;/li&gt;
&lt;li&gt;Retry transient errors and only idempotent actions. Keep progress outside the process (Temporal and similar), and write sagas for rollback.&lt;/li&gt;
&lt;li&gt;Put sending, payments and deletion behind a human approval. Keep the wait for the answer in Temporal, not in process memory.&lt;/li&gt;
&lt;li&gt;Write a trace of every step and count the cost of a successful task, not of one call. Run evals on every prompt change.&lt;/li&gt;
&lt;li&gt;Don't give an agent private data, untrusted content and a way out all at once.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Tools: fewer, but bigger
&lt;/h2&gt;

&lt;p&gt;All the model knows about a tool is its name, description, parameter schema and what it returned. From these it decides what to call and with which parameters. That's why a tool for an agent is written differently from an API for a programmer. Anthropic collected the rules in &lt;a href="https://www.anthropic.com/engineering/writing-tools-for-agents" rel="noopener noreferrer"&gt;Writing effective tools for agents&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Don't make one tool per endpoint. Instead of &lt;code&gt;list_users&lt;/code&gt;, &lt;code&gt;list_events&lt;/code&gt; and &lt;code&gt;create_event&lt;/code&gt;, one &lt;code&gt;schedule_event&lt;/code&gt; that finds a free slot and creates the meeting by itself is better. The model makes one call instead of three, and no extra lists end up in the context. The more similar tools there are, the easier it is for the model to mix them up.&lt;/p&gt;

&lt;p&gt;Keep tool responses short. Return names, not internal &lt;code&gt;uuid&lt;/code&gt;s. Cut long lists with pagination and filters. A response format parameter helps. In Anthropic's example, a Slack tool in concise mode returned 72 tokens instead of 206. Claude Code truncates any tool's response to 25,000 tokens by default. And every token of a response goes into the history and, as we calculated in part 1, gets paid for again on every following turn.&lt;/p&gt;

&lt;p&gt;A tool writes its errors for the model too. A traceback or a bare 400 code tells it nothing. A message like "the date must be in 2026-11-09 format, got 09.11" is something the model will fix on its own on the next turn. And name parameters unambiguously: &lt;code&gt;user_id&lt;/code&gt; is clearer than &lt;code&gt;user&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A tool call is structured model output: JSON that follows a schema. Validate it against the schema before running it, like any user input.&lt;/p&gt;
&lt;h2&gt;
  
  
  Context: fewer tokens, more signal
&lt;/h2&gt;

&lt;p&gt;The context window is finite, and the fuller it gets, the worse the model works with each token. Anthropic's article on &lt;a href="https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents" rel="noopener noreferrer"&gt;context engineering&lt;/a&gt; puts the goal like this: find the smallest set of tokens that helps the most with the task. In part 1 we calculated what an extra token costs. But extra tokens also get in the way of the model's thinking.&lt;/p&gt;

&lt;p&gt;Three techniques help. The first is loading as you go. Don't put everything into the prompt up front. Keep references in it (file paths, document ids) and give the agent a tool that loads what's needed. That's how Claude Code works: CLAUDE.md is in the context from the start, and the agent finds the rest through glob and grep.&lt;/p&gt;

&lt;p&gt;The second is compaction. When the history has grown, it gets summarized. In Claude Code, compaction keeps decisions, open bugs and implementation details, and throws out old tool responses. The third is notes. The agent keeps a file like NOTES.md outside the context and rereads it when needed.&lt;/p&gt;

&lt;p&gt;For big tasks there are subagents. Each one works through its part in its own context and returns a summary of 1–2 thousand tokens. The main agent sees conclusions, not hundreds of pages of search results.&lt;/p&gt;
&lt;h2&gt;
  
  
  RAG and search
&lt;/h2&gt;

&lt;p&gt;RAG (retrieval-augmented generation) means finding the right pieces of knowledge before answering and putting them into the context. First decide whether you need it at all. Anthropic gives a threshold. If the knowledge base is under 200,000 tokens (about 500 pages), you can put the whole thing into the prompt and cache it. No search needed.&lt;/p&gt;

&lt;p&gt;If the base is bigger, the classic setup goes like this. Documents are cut into chunks of a few hundred tokens. Each chunk is turned into an embedding, a vector of meaning, and stored in a vector database. For a question, the nearest chunks are found and handed to the model. But a cut-out chunk loses its context. The sentence "revenue grew 3% over the previous quarter" is useless without the company name and the quarter.&lt;/p&gt;

&lt;p&gt;What helps, per Anthropic's measurements in &lt;a href="https://www.anthropic.com/news/contextual-retrieval" rel="noopener noreferrer"&gt;Contextual Retrieval&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Search by meaning is combined with keyword search (BM25). Embeddings catch meaning well but can miss an exact string like the error code &lt;code&gt;TS-999&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Before indexing, the model adds 50–100 tokens of context to each chunk: which document it's from and what it's about. With prompt caching, this costs about a dollar per million document tokens.&lt;/li&gt;
&lt;li&gt;The results are reranked by a separate model, and the model gets the top 20 chunks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkcl7plhqx5umyk61c96s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fkcl7plhqx5umyk61c96s.png" alt=" " width="800" height="373"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Anthropic's measurement on their datasets. A failure means the right chunk didn't make the top 20.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Test retrieval separately from the answer. If the answer is bad, you need to know who's at fault: search didn't find the right chunk, or the model used it badly. Build a set of questions where you know where the answer lives, and count how often the right chunk lands in the results. That's the metric Anthropic used to measure its 5.7% and 1.9%.&lt;/p&gt;

&lt;p&gt;You don't always need an index. Early versions of Claude Code ran on RAG with a local vector database. The team &lt;a href="https://x.com/bcherny/status/2017824286489383315" rel="noopener noreferrer"&gt;switched&lt;/a&gt; to agentic search: the model finds files by itself through glob and grep. According to Boris Cherny, this works better and gets rid of the problems with a stale index, privacy and security. But that's experience with code, where text has names and structure. For a base of documents in plain language, classic RAG still makes sense, and opinions differ here.&lt;/p&gt;
&lt;h2&gt;
  
  
  Keeping the loop and the money under control
&lt;/h2&gt;

&lt;p&gt;Agents often get built where a chain would have been enough. In &lt;a href="https://www.anthropic.com/engineering/building-effective-agents" rel="noopener noreferrer"&gt;Building effective agents&lt;/a&gt;, Anthropic advises starting with the simplest solution. Often one model call with retrieval and examples is enough. An agent picks its own steps and pays for that in latency and money. &lt;a href="https://github.com/humanlayer/12-factor-agents" rel="noopener noreferrer"&gt;12-Factor Agents&lt;/a&gt; puts it more bluntly: most agents in production are mostly ordinary code, with the model called at a few points. It also advises building small agents of 3–10 steps.&lt;/p&gt;

&lt;p&gt;If you do need an agent, put limits on it. The main reason is money. Every turn rereads the whole history, so the cost grows faster than the number of turns. The task from part 1 costs $0.51 for 30 turns. An agent that got stuck and made 100 turns costs $2.68. That's 3.3 times the turns and 5.3 times the money. On the last turn it reads almost 300,000 tokens.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr64dfx3opvbmjgplva4j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr64dfx3opvbmjgplva4j.png" alt=" " width="800" height="394"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;A back-of-the-envelope calculation for the part 1 scenario: Sonnet 5.5, caching, +2,900 tokens per turn.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;There are three limiters:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;A turn limit.&lt;/strong&gt; In the OpenAI Agents SDK the default is 10 turns, after which it raises &lt;code&gt;MaxTurnsExceeded&lt;/code&gt;. The Claude Agent SDK has no default limit; you set one with the &lt;code&gt;max_turns&lt;/code&gt; parameter.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A dollar budget.&lt;/strong&gt; In the Claude Agent SDK it's &lt;code&gt;max_budget_usd&lt;/code&gt;: when the spend estimate reaches the threshold, the task stops with &lt;code&gt;error_max_budget_usd&lt;/code&gt;. The estimate is computed on the client and can overshoot the threshold a little, so the docs advise leaving some margin.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A timeout on the whole task&lt;/strong&gt;, not just on a single call.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Take the values from real tasks: look at how many turns and how much money a normal one uses, and add a margin. OWASP's risk list has unbounded resource consumption as a separate item.&lt;/p&gt;

&lt;p&gt;Return a tool error to the model as a result instead of crashing the loop. The model will often fix the parameters itself or take another route. In Anthropic's experience this works surprisingly well. But count consecutive errors: if the model keeps repeating the same failed call over and over, stop.&lt;/p&gt;

&lt;p&gt;And decide up front where a task goes when it runs out of attempts, turns or budget. The options: a fallback model or provider, a simple chain without an agent, a human.&lt;/p&gt;
&lt;h2&gt;
  
  
  Reliability: why an agent breaks more often than a regular service
&lt;/h2&gt;

&lt;p&gt;A regular backend request makes one or two external calls. An agent lives longer and calls more. The loop in part 1 had 30 turns, and almost every one had two calls: the model and a tool. Anthropic writes about this in its article on its research system: agents run for a long time and keep state across many calls. A minor failure that a service would just return to the user can derail an agent's whole task.&lt;/p&gt;

&lt;p&gt;The model call itself is unreliable too. The Claude API answers with errors like any external service:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;429: you hit a limit;&lt;/li&gt;
&lt;li&gt;529: the API is overloaded by overall traffic;&lt;/li&gt;
&lt;li&gt;500: an internal error;&lt;/li&gt;
&lt;li&gt;504: the request timed out.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It gets trickier. With streaming, an error can arrive in the middle of the response, after the server has already returned 200.&lt;/p&gt;

&lt;p&gt;The third reason is that an agent has state. Surviving an error isn't enough; you have to not lose what's been done. Anthropic rejected restarting from scratch because it's expensive and frustrates users. Their agents resume from where the error happened.&lt;/p&gt;
&lt;h2&gt;
  
  
  Retries: what to repeat and what not to
&lt;/h2&gt;

&lt;p&gt;Only transient failures are worth retrying. A permanent error comes back the same on a retry.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4mpu2ofiocgnkjs116d7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4mpu2ofiocgnkjs116d7.png" alt=" " width="799" height="502"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Per Anthropic's docs as of 2026-11-02.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;There's a subtlety with 429. Usually it's a per-minute limit, and the response has a &lt;code&gt;retry-after&lt;/code&gt; header: how many seconds to wait. But 429 also comes when the monthly spend cap is exhausted. That response has no &lt;code&gt;retry-after&lt;/code&gt;, and the error body has the code &lt;code&gt;enforced_spend_limit_reached&lt;/code&gt;. Retrying is pointless until next month. A retry that can't tell the difference will hammer the API for hours.&lt;/p&gt;

&lt;p&gt;The pause between attempts should grow. Otherwise retries just add load to an API that's already overloaded. Usually the pause doubles: 1, 2, 4, 8 seconds and on up to a ceiling. That's how Temporal works by default (more on it below): it starts at one second, with a multiplier of 2 and a ceiling of 100 seconds. Ten retries take about seven minutes.&lt;/p&gt;

&lt;p&gt;The official Anthropic SDK already retries transient failures by itself: twice by default, with a growing pause and respecting &lt;code&gt;retry-after&lt;/code&gt;. For a single call that's enough. For a 30-step agent, you decide: how many attempts per step, and what to do when they run out.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: retrying a model call&lt;/span&gt;
&lt;span class="no"&gt;TRANSIENT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="mi"&gt;429&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;504&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;529&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;call_model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;attempts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;pause&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;attempt&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;attempts&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;messages&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ok&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;code&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="no"&gt;TRANSIENT&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="nf"&gt;is_429_without_retry_after&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;PermanentError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;       &lt;span class="c1"&gt;# fix it, don't retry it&lt;/span&gt;
        &lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;retry_after&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="n"&gt;pause&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;pause&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;min&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pause&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;raise&lt;/span&gt; &lt;span class="nc"&gt;OutOfAttempts&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The calculation at the start of the article has a weak spot: failures aren't always independent. If the provider is down entirely, three quick retries won't help. You need a longer pause or a fallback provider.&lt;/p&gt;

&lt;p&gt;One more link to part 1. Claude API limits are counted in tokens per minute. For most models, cached tokens don't count toward the input limit. The docs give an example. With a limit of 2 million tokens per minute and an 80% cache hit rate, you can process 10 million. Caching cuts both the bill and the number of 429 errors.&lt;/p&gt;

&lt;h2&gt;
  
  
  The main danger: repeating an action
&lt;/h2&gt;

&lt;p&gt;Take a &lt;code&gt;send_email&lt;/code&gt; tool. The email went out, but the response got lost on the way. The harness retries the call, and the customer gets a second email. With &lt;code&gt;charge_card&lt;/code&gt;, the money gets charged twice. Retries save you from failures, but they cause errors of their own when an action can't be safely repeated.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fg94y0m5cf0lk10m9h12j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fg94y0m5cf0lk10m9h12j.png" alt=" " width="800" height="461"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The same failure without an idempotency key and with one.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The property "a repeat doesn't change the result" is called idempotency. A read is idempotent by itself. An action with consequences is made idempotent with a key. That's how the Stripe API works. The client creates a unique key and sends it with the request. The server remembers the response to the first request with that key. On a repeat, it returns the saved response and doesn't run the operation a second time. If the key is the same but the parameters differ, Stripe returns an error.&lt;/p&gt;

&lt;p&gt;For an agent, the key already exists. Every tool call comes from the model with its own &lt;code&gt;id&lt;/code&gt;, and it doesn't change on a retry. My advice, not a rule from the docs: pass this &lt;code&gt;id&lt;/code&gt; as the idempotency key into the tool and on into the external system.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: an idempotent tool&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;send_email&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="nf"&gt;already_done&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;                 &lt;span class="c1"&gt;# this call has already run&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;saved_result&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mail&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotency_key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt;

&lt;span class="nf"&gt;send_email&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;to&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This check has a hole. If the process crashes between sending the email and the &lt;code&gt;save&lt;/code&gt; line, it won't catch the duplicate. It's most reliable when the external system itself understands the key, like Stripe. If it doesn't, it's better to hand that action to a human for approval.&lt;/p&gt;

&lt;h2&gt;
  
  
  Durable execution and Temporal: not losing what's done
&lt;/h2&gt;

&lt;p&gt;A retry saves one step. But if the agent's process itself crashes, there's nothing to retry. The history, the step number and the tool results were in memory and they're gone. Progress has to be kept outside the process. This approach is called durable execution. I'll walk through it with Temporal.&lt;/p&gt;

&lt;p&gt;In Temporal, code is split into two parts. A workflow is the logic: the agent loop, branches, waits. Activities are everything that touches the outside world: an API call, a database write, an email, a charge. Every event is written to a history. If a worker crashes, another one takes the history, replays the workflow code and continues from where it crashed. Finished steps don't run a second time: their results come from the history.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fts6mmd87k7obaky5vc14.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fts6mmd87k7obaky5vc14.png" alt=" " width="800" height="421"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;On recovery, steps 1–3 don't run again: their results come from the history.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This leads to two requirements. Workflow code must be deterministic, since Temporal replays it. Random numbers, the current time and network requests live only in activities. And activities must be idempotent: the step where everything crashed will be run again. By default, Temporal retries activities with no limit on the number of attempts.&lt;/p&gt;

&lt;p&gt;An agent fits this scheme naturally. The loop lives in the workflow. The model call and every tool call become activities with their own retry policy.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: the agent loop as a workflow&lt;/span&gt;
&lt;span class="nd"&gt;@workflow&lt;/span&gt;
&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;agent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;history&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;task&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call_model&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;retries&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;model_policy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stop_reason&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"tool_use"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;call&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;run_tool&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the cost. The loop from part 1 with caching costs $0.51. If the process crashed on turn 25 and the task was started from scratch, it comes to $0.93, 81% more.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F08jxznu0qe0hleyeyap3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F08jxznu0qe0hleyeyap3.png" alt=" " width="800" height="402"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;A back-of-the-envelope calculation for the part 1 scenario: 30 turns, Sonnet 5.5, caching.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The money is the lesser problem. On a restart, the 25 actions already done run again, and each non-idempotent one produces a duplicate.&lt;/p&gt;

&lt;p&gt;A large tech company went through this in production. Its research agent, built into its AI assistant, works for up to 20 minutes and goes through dozens of websites. In the first version, state was kept locally: the process crashed, and everything started over, along with the tokens already burned. The team moved to Temporal to recover from the history. And it immediately ran into what the previous section is about: Temporal can run an activity again, so side effects have to be idempotent.&lt;/p&gt;

&lt;p&gt;Temporal isn't the only option. LangGraph has its own mechanism: it saves state at every step and, after a crash, continues from the last checkpoint. There are other engines too: Restate, DBOS, Inngest. I haven't compared them. And keep in mind that most of the writing about durable execution for agents comes from the engine authors themselves, Temporal included.&lt;/p&gt;
&lt;h2&gt;
  
  
  Sagas: rolling back what's already done
&lt;/h2&gt;

&lt;p&gt;Durable execution gets a process to the end, even if it crashed along the way. But the end can be a failure. The agent booked a hotel, bought a ticket, and then the card was declined at payment. There's no shared transaction across the hotel, the airline and the bank. You can't undo it all with one &lt;code&gt;ROLLBACK&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;That's what a saga is for. Garcia-Molina and Salem described the pattern back in 1987. A long process is split into steps, and each one gets a compensation written in advance. If something breaks, the system undoes what's been done in reverse order. A compensation doesn't erase history. It undoes the operation in business terms: return the ticket, cancel the booking, refund the money.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fahxseb8injrdbh4dbaxl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fahxseb8injrdbh4dbaxl.png" alt=" " width="800" height="429"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Compensations run in reverse order.&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: a saga&lt;/span&gt;
&lt;span class="n"&gt;compensations&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;try&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;booking&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;book_hotel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;compensations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;cancel_booking&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;booking&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;ticket&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;buy_ticket&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;compensations&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nf"&gt;return_ticket&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;ticket&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nf"&gt;charge_payment&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;except&lt;/span&gt; &lt;span class="nc"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;undo&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;reversed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;compensations&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="nf"&gt;undo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# compensations must be idempotent too&lt;/span&gt;
    &lt;span class="k"&gt;raise&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can't take back a sent email. Put actions like that last, when everything else has already worked, or hand them to a human for approval. That's the next section.&lt;/p&gt;

&lt;h2&gt;
  
  
  Human approval of an action
&lt;/h2&gt;

&lt;p&gt;Some actions an agent shouldn't take silently: sending an email to a customer, charging money, deleting data, deploying code. OWASP lists the opposite situation as a separate risk, Excessive Agency: the agent has more permissions and autonomy than the task needs.&lt;/p&gt;

&lt;p&gt;Two questions decide what to approve: can the action be undone, and what does a mistake cost. Reads and drafts don't need approval. Sending, payments and deletion do.&lt;/p&gt;

&lt;p&gt;12-Factor Agents advises asking a human through the same mechanism as tools. The model calls a tool like &lt;code&gt;request_approval&lt;/code&gt; with a description of the action, and the code pauses the task and waits for an answer. In the Claude Agent SDK there's the &lt;code&gt;can_use_tool&lt;/code&gt; callback for this (&lt;code&gt;canUseTool&lt;/code&gt; in TypeScript). The SDK calls it for every tool call that the rules haven't allowed or denied in advance. The callback shows the action to a human and returns "allow" or "deny". On a denial, the model sees the reason and can take another route. The rules are set as lists: &lt;code&gt;allowed_tools&lt;/code&gt; lets calls through without asking, &lt;code&gt;disallowed_tools&lt;/code&gt; always denies. For an agent with no human nearby, there's the &lt;code&gt;dontAsk&lt;/code&gt; mode: anything that would require asking is denied right away.&lt;/p&gt;

&lt;p&gt;A human answers slowly: minutes, hours, sometimes a whole night. The SDK callback can wait as long as it takes, but the process has to stay alive the whole time. The docs say outright that for a long wait you should defer the call through a hook, let the process exit, and resume the saved session later. Keeping a process in memory for hours is risky: a deploy will restart it or a failure will kill it. Temporal helps here again. The workflow waits for a signal, an asynchronous message to a workflow that's already running. The wait is recorded in the history and survives crashes and deploys. The wait has a timeout. Temporal Agent Harness works the same way: the agent pauses until the human decides and continues even if the answer came hours later.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Pseudocode: human approval in Temporal&lt;/span&gt;
&lt;span class="nd"&gt;@workflow&lt;/span&gt;
&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SendInvoice&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;decision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;

    &lt;span class="nd"&gt;@signal&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;human_decision&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;   &lt;span class="c1"&gt;# comes from the UI when the human clicks a button&lt;/span&gt;
        &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt;

    &lt;span class="nd"&gt;@run&lt;/span&gt;
    &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;email&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;prepare_email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;show_to_human&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# recipient, amount and the full text&lt;/span&gt;
        &lt;span class="n"&gt;got_answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;wait_condition&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;lambda&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;one_day&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;got_answer&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;decision&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"approve"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s2"&gt;"not sent"&lt;/span&gt;                   &lt;span class="c1"&gt;# no answer, no action&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;activity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;send_email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nb"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three rules. Show the human what will actually run: the recipient, the amount and the text, not the model's paraphrase. If there's no answer before the timeout, the action doesn't run. And make the execution after "yes" idempotent too, since someone can click the button twice.&lt;/p&gt;

&lt;h2&gt;
  
  
  A deploy in the middle of a task
&lt;/h2&gt;

&lt;p&gt;The last source of failures is one you create yourself: you roll out a new version while agents are working. Anthropic rolls out its system gradually, which is called rainbow deployments. The new version runs next to the old one, and agents that are already running finish on the old one. Temporal has its own constraint. New workflow code must replay old steps the same way the old code did, or recovery will break. So workflow logic with unfinished tasks gets changed carefully.&lt;/p&gt;

&lt;h2&gt;
  
  
  Observability: seeing every step
&lt;/h2&gt;

&lt;p&gt;The agent crashed on turn 17. Without a trace, all you'll know is that the task didn't get done. A trace shows every step: what went into the model, what it answered, which tool was called, how long it took and what it cost.&lt;/p&gt;

&lt;p&gt;You don't need to invent a format. OpenTelemetry has &lt;a href="https://github.com/open-telemetry/semantic-conventions-genai" rel="noopener noreferrer"&gt;GenAI conventions&lt;/a&gt;: separate spans for a model call, an agent (&lt;code&gt;invoke_agent&lt;/code&gt;) and a tool (&lt;code&gt;execute_tool&lt;/code&gt;), plus attributes for the model and tokens. Their status is still Development, so they may change. Under the standard, prompt and response texts are recorded only when explicitly turned on, since they can contain personal data.&lt;/p&gt;

&lt;p&gt;What to measure on the money side:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The cost of the whole task&lt;/strong&gt;, not of one call. The Claude Agent SDK returns it in the final message: &lt;code&gt;total_cost_usd&lt;/code&gt; and &lt;code&gt;num_turns&lt;/code&gt;. It's an estimate on the client side, not a bill.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The cost of a successful task.&lt;/strong&gt; Failed tasks cost money too: the steps before the failure are already paid for. At 1% failures per step without retries, a successful task costs $0.60 instead of $0.51. At 3%, it's $0.84, 63% more. That's the number to compare with the cost of manual work.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache share.&lt;/strong&gt; Look at &lt;code&gt;cache_read_input_tokens&lt;/code&gt; in &lt;code&gt;usage&lt;/code&gt;. If it's almost always zero, caching isn't working, and in the part 1 example it made the task 6.6 times cheaper.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Turns and retries per task.&lt;/strong&gt; Tasks with far more turns than usual are the first candidates for a loop.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The share of tasks that went to plan B.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Keep prompts in git and write their version into the trace. Otherwise you won't be able to tell which change made quality drop.&lt;/p&gt;

&lt;h2&gt;
  
  
  Evals: tests for nondeterministic code
&lt;/h2&gt;

&lt;p&gt;You changed one word in a prompt or a tool description, and the agent started making more mistakes somewhere else. Evals catch this. &lt;a href="https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents" rel="noopener noreferrer"&gt;Anthropic's guide to agent evals&lt;/a&gt; advises not waiting for a perfect set: 20–50 simple tasks from real failures are already a good start. Take them from the bug tracker and support tickets.&lt;/p&gt;

&lt;p&gt;You can grade with code (the answer matched, the test passed), with a model (an LLM judges against criteria) or with a human. Code is fast and unambiguous, a model is more flexible, a human is more accurate but more expensive. The model is nondeterministic, so one attempt proves nothing. You need two metrics. pass@k: at least one of k attempts succeeds. pass^k: all k succeed. For an agent that acts on its own, the second one matters.&lt;/p&gt;

&lt;p&gt;Run evals in CI on every change to a prompt, a tool or the model, like unit tests. Add every production failure to the set. And read transcripts regularly: it's the only way to see that an eval measures what it should.&lt;/p&gt;

&lt;h2&gt;
  
  
  Security: the agent will follow someone else's instructions
&lt;/h2&gt;

&lt;p&gt;The model can't reliably tell your instructions apart from text it came across along the way. Prompt injection is first in the 2025 &lt;a href="https://genai.owasp.org/llm-top-10/" rel="noopener noreferrer"&gt;OWASP Top 10 for LLM Applications&lt;/a&gt;. Indirect injection is the most dangerous: the instruction comes not from the user but in a tool response. It can be a web page, an email or a document from RAG.&lt;/p&gt;

&lt;p&gt;MCP has its own version of the attack. Invariant Labs &lt;a href="https://invariantlabs.ai/blog/mcp-security-notification-tool-poisoning-attacks" rel="noopener noreferrer"&gt;demonstrated&lt;/a&gt; tool poisoning: an instruction is hidden in an MCP tool's description, visible to the model but not to the user. In their demo, a harmless addition tool asked the model to read &lt;code&gt;~/.ssh/id_rsa&lt;/code&gt; and pass the contents in a parameter. On top of that, the description can change after you've approved the server.&lt;/p&gt;

&lt;p&gt;Injection filters give no guarantee. Simon Willison &lt;a href="https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/" rel="noopener noreferrer"&gt;writes&lt;/a&gt; that in security, catching 95% of attacks is a failing grade. He proposes the "lethal trifecta" rule. An agent is dangerous when it has three things at once: access to private data, untrusted content and a way to send data out.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgygczk27vcczwcjgg0yj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgygczk27vcczwcjgg0yj.png" alt=" " width="800" height="336"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Based on Simon Willison's article, June 2025.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The rest is familiar from backend work. Give tools minimal permissions: if read access is enough, don't give write access. Run code the agent writes in a sandbox. Validate model output before passing it to SQL, a shell or a browser. Don't write secrets and personal data to logs and traces. Hand irreversible actions to a human, as in the section on approval.&lt;/p&gt;

&lt;h2&gt;
  
  
  Checklist: an agent from demo to production
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Design
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;First try a chain or a single call with retrieval. Use an agent only where you can't do without one.&lt;/li&gt;
&lt;li&gt;Big tools with no overlap. Short responses, and errors that hint how to fix the call.&lt;/li&gt;
&lt;li&gt;If the knowledge base is under 200,000 tokens, put it into the prompt with caching. If it's bigger, search by meaning and by keywords, rerank, and test retrieval separately.&lt;/li&gt;
&lt;li&gt;A turn limit, a dollar budget and a task timeout, with a margin over a normal task. Decide where a task goes when they run out.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Reliability
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Retry only transient errors: 429 with &lt;code&gt;retry-after&lt;/code&gt;, 529, 500, 504, network. Increase the pause.&lt;/li&gt;
&lt;li&gt;For each tool, decide whether it can be repeated. Pass the idempotency key (the call &lt;code&gt;id&lt;/code&gt;) all the way to the external system.&lt;/li&gt;
&lt;li&gt;Keep progress outside the process: durable execution, checkpoints, or at least a step log. Only deterministic logic in the workflow.&lt;/li&gt;
&lt;li&gt;For actions across several systems, write compensations in advance. Put the irreversible last.&lt;/li&gt;
&lt;li&gt;Put sending, payments and deletion behind a human approval: show the exact action, and do nothing without an answer before the timeout.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Operations
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;A trace of every step, with the prompt version in it. Cost per task, cost per successful task, cache share, turns per task.&lt;/li&gt;
&lt;li&gt;20–50 tasks from real failures in CI on every change to a prompt, a tool or the model.&lt;/li&gt;
&lt;li&gt;Don't give an agent private data, untrusted content and external communication all at once. Minimal permissions, a sandbox, no secrets in logs.&lt;/li&gt;
&lt;li&gt;Turn on prompt caching: it cuts both the bill and the number of 429 errors.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;An agent that gets through 10 steps out of 10 in a demo runs thousands of 30-step tasks in production. That's where the arithmetic from the start of the article kicks in: 1% failures per step, and without retries one task in four doesn't get to the end. Retries fix exactly that. The other practices decide how much a task costs and how much damage the agent can do along the way.&lt;/p&gt;

&lt;p&gt;Which of these practices did you only adopt after getting burned?&lt;/p&gt;

&lt;h2&gt;
  
  
  Series "AI Engineering for Newbies"
&lt;/h2&gt;

&lt;p&gt;This is a series of three articles.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://dev.to/muratover/ai-engineering-for-newbies-agents-mcp-tokens-and-caching-with-numbers-1gh1"&gt;"AI Engineering for Newbies: Agents, MCP, Tokens and Caching, With Numbers"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;"AI Agents in Production for Newbies: Tools, RAG, Reliability and Evals" (you are reading it now)&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/muratover/agent-systems-for-newbies-building-a-support-agent-from-one-file-to-temporal-sagas-and-a-circuit-2fhf"&gt;"Agent Systems for Newbies: Building a Support Agent From One File to Temporal, Sagas and a Circuit Breaker"&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>ai</category>
      <category>llm</category>
      <category>agents</category>
      <category>beginners</category>
    </item>
    <item>
      <title>"AI Engineering for Newbies: Agents, MCP, Tokens and Caching, With Numbers"</title>
      <dc:creator>Eldar Muratov</dc:creator>
      <pubDate>Sun, 08 Nov 2026 19:06:04 +0000</pubDate>
      <link>https://dev.to/muratover/ai-engineering-for-newbies-agents-mcp-tokens-and-caching-with-numbers-1gh1</link>
      <guid>https://dev.to/muratover/ai-engineering-for-newbies-agents-mcp-tokens-and-caching-with-numbers-1gh1</guid>
      <description>&lt;p&gt;Open a large job board and search for job ads that mention "AI agent". As of October 28, 2026, there are 1,458 of them. LLM comes up in 1,261 ads, RAG in 520, MCP in 245. Now search for "prompt caching": 13 ads. Tokens are mentioned in 19.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnuk73tpadwymngx2xdvx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnuk73tpadwymngx2xdvx.png" alt=" " width="800" height="528"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Job board search, 2026-10-28.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;That's an odd picture. The market wants agents built at scale. Yet almost nobody asks what an agent costs or why it works. Let's go through these terms one by one: what each one is, why it exists and what it looks like inside. Then we'll count the tokens and the money on a single agent task. With caching, the same task costs 6.6 times less, and you'll see why. There's a checklist at the end.&lt;/p&gt;

&lt;p&gt;This is the first part of a series. In the second I'll cover reliability: durable execution, transactions and idempotency. In the third I'll show how a chain differs from an agent and put everything together in one application, using a support agent as the example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An AI engineer doesn't train their own model. They build a system around a ready-made one: feed it the right data, give it tools, check the result and watch the cost.&lt;/li&gt;
&lt;li&gt;The model remembers nothing and does nothing by itself. On every step the harness sends it everything again: the tools, the rules and the whole history.&lt;/li&gt;
&lt;li&gt;That's why, over 30 steps, the agent read 1.63 million tokens, even though it was never given more than 100 thousand at once.&lt;/li&gt;
&lt;li&gt;The cache reads the repeating start of a request at 5–10% of the price. But only if it matches the previous request down to the character. So put what never changes at the start and what is new at the end.&lt;/li&gt;
&lt;li&gt;Russian text costs about 1.27 times more Claude tokens than English.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  What AI engineering is and why it concerns every developer
&lt;/h2&gt;

&lt;p&gt;Chip Huyen explains the difference from machine learning well in her book "AI Engineering". An ML engineer trains the model: collects and labels data, trains, evaluates. An AI engineer takes a ready-made model that someone else trained, such as Claude or GPT. Their job is to ask the right question, give the model the data it needs and sometimes fine-tune it a little. For them the model is just an external service, like a database or a payment gateway. With one difference: it answers in text and sometimes gets things wrong.&lt;/p&gt;

&lt;p&gt;For an ordinary developer this is no longer exotic. In the 2026 Stack Overflow survey, 73% of respondents said they write code with assistants and agents every day. The agents named most often were Claude Code (66%) and GitHub Copilot (59%). And in the 2025 survey the top complaint was "AI answers that are almost right, but not quite". 66% said so.&lt;/p&gt;

&lt;p&gt;The gap between "almost" and "right" rarely hides in the prompt. For an agent to solve the task without eating the budget, you need to understand four things. What the model receives on each step. Who actually performs the actions. Where the agent usually goes wrong. And what each step costs.&lt;/p&gt;
&lt;h2&gt;
  
  
  Glossary
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Term&lt;/th&gt;
&lt;th&gt;In short&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Token&lt;/td&gt;
&lt;td&gt;a piece of text; the model reads in tokens, and money is counted in them&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Context window&lt;/td&gt;
&lt;td&gt;how many tokens the model reads in one request&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;System prompt&lt;/td&gt;
&lt;td&gt;rules for the model, sent with every request&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Tool use&lt;/td&gt;
&lt;td&gt;the model asks for a function to be called, your code runs it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Chain and agent&lt;/td&gt;
&lt;td&gt;the steps are written in code, or the model picks them itself&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Agent loop&lt;/td&gt;
&lt;td&gt;request → tool call → result → request again, until the task is done&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Harness&lt;/td&gt;
&lt;td&gt;all the code around the model: Claude Code, Cursor, your service&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;MCP&lt;/td&gt;
&lt;td&gt;a standard for connecting tools and data to any AI application&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Skill&lt;/td&gt;
&lt;td&gt;a folder of instructions the agent reads only when it needs them&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Subagent&lt;/td&gt;
&lt;td&gt;a helper with its own context that returns only the result&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Hook&lt;/td&gt;
&lt;td&gt;your script on a harness event: block, ask a human, add context, check&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;RAG&lt;/td&gt;
&lt;td&gt;find the right documents and put them into the request before answering&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Eval&lt;/td&gt;
&lt;td&gt;a set of tasks used to check that the agent has not broken&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Prompt cache&lt;/td&gt;
&lt;td&gt;the repeating start of a request at 5–10% of the price&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  The model and its context
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Token.&lt;/strong&gt; The model reads text not letter by letter and not word by word, but in pieces. These pieces are called tokens. Everything is counted in tokens: how much fits into a request, what the limits are and how much you pay. More on them in the section about tokens.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Context window.&lt;/strong&gt; How many tokens the model reads at once, including its own answer. For most new Claude models it's 1 million. Filling the window to the brim is a bad idea. Every token costs money, and the longer the context, the worse the answers. Anthropic calls this "context rot".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;System prompt.&lt;/strong&gt; Rules for the model that come before the user's messages: who it is, what's allowed, what form the answer takes. In Claude Code, the repo's &lt;code&gt;CLAUDE.md&lt;/code&gt; lands here too. The system prompt goes out with every single request, so you pay for each extra line in it again and again.&lt;/p&gt;
&lt;h3&gt;
  
  
  How the model acts
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tool use.&lt;/strong&gt; This is how the model gets hands to work with. You describe a function: its name, what it does, what parameters it takes. For example, &lt;code&gt;get_weather&lt;/code&gt; with a &lt;code&gt;location&lt;/code&gt; parameter. The model doesn't run the function itself. It answers: "call &lt;code&gt;get_weather&lt;/code&gt; for Paris". Your code calls the function and returns the result to the model. Anthropic calls this a contract: you decide what the model may do, and it decides when.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chain (workflow, agents chain) and agent (AgentsLLM).&lt;/strong&gt; In a chain the order of steps is written in code. For example: figure out what the request is about and send it down the right branch. An agent picks the order itself: which steps to take and which tools to call. A chain is more predictable and cheaper, an agent is more flexible. Anthropic advises starting with the simplest option. Often one well-built request to the model is enough.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Agent loop.&lt;/strong&gt; The same thing repeats: request, tool call, result, request again. It goes on until the model answers with text. This loop is what turns a model with tools into an agent. Pseudocode and a diagram are below, in the section on how the system works.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Harness.&lt;/strong&gt; All the code around the model. It builds the request, runs the loop, calls the tools, keeps the history and checks the actions. Claude Code, Cursor, the Agent SDK and your Python service are all harnesses. The same model behaves differently in different harnesses. In practice, the harness is what an AI engineer builds most of the time. Firecrawl's article "&lt;a href="https://www.firecrawl.dev/blog/what-is-an-agent-harness" rel="noopener noreferrer"&gt;What Is an Agent Harness?&lt;/a&gt;" covers its parts in detail.&lt;/p&gt;
&lt;h3&gt;
  
  
  What extends an agent
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;MCP (Model Context Protocol).&lt;/strong&gt; An open standard for connecting external systems to AI applications. It's often compared to USB-C. An application, for example Claude Code, connects to MCP servers. A server gives it tools, data and ready-made prompt templates. An integration with GitHub, a database or Jira is written once and works in any application that supports MCP. The standard changes fast. I rely on the version from July 28, 2026.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Skill (Agent Skill).&lt;/strong&gt; A folder with a &lt;code&gt;SKILL.md&lt;/code&gt; file, sometimes with scripts and reference files as well. At first the model sees only the skill's short description, about 100 tokens. It reads the full text, up to 5 thousand tokens, when the task matches the description. The other files cost nothing until they are opened. And if there's a script inside, only what it prints gets into the context.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmqkw1qmqiwbl9m4azmqo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmqkw1qmqiwbl9m4azmqo.png" alt=" " width="800" height="474"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;How a skill gets into the context. Numbers from Anthropic's Agent Skills documentation.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Subagent.&lt;/strong&gt; A helper with its own context and its own tools. The main agent gives it a task and gets back only the result. Why this matters: noisy work, such as searching the code or reading logs, doesn't clutter the main context. A subagent can be given a cheaper model. But its requests count toward the same limits.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hook.&lt;/strong&gt; Your script that the harness runs by itself when something happens. The model has nothing to do with it. There are many triggers: session start, a new user prompt, the moment before a tool call and after it, the end of a response, context compaction, a subagent launch.&lt;/p&gt;

&lt;p&gt;The script receives JSON with the details as input: for example, which tool is being called and with which parameters. In response it can block the action: exit with code 2 or return &lt;code&gt;deny&lt;/code&gt; with a reason, and the model will see it. It can hand the question to a human (&lt;code&gt;ask&lt;/code&gt;) or allow it without an extra question (&lt;code&gt;allow&lt;/code&gt;). It can add text to the model's context. Or it can simply do its own job: run a linter after a file edit, write the action to a log, send a notification.&lt;/p&gt;

&lt;p&gt;Project hooks live in &lt;code&gt;.claude/settings.json&lt;/code&gt;. Hooks that are mandatory for the whole company go into managed settings: a developer can't turn them off. There are also hooks that ask a model themselves when judgment is needed. But an ordinary hook works without a model and behaves the same way every time. That's how it differs from a line in the prompt: the model may skip an instruction, but a hook always fires. Rule of thumb: a skill advises, a hook guarantees.&lt;/p&gt;
&lt;h3&gt;
  
  
  Quality and data
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;RAG (retrieval-augmented generation).&lt;/strong&gt; Before calling the model, the system finds the relevant pieces of documents and puts them into the request. The model answers from what was found, not from memory. More and more often agents are simply given a search tool and look things up themselves.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Eval (evaluation).&lt;/strong&gt; These are tests for an agent. You collect tasks for which you know the right answer and run them after every change of model, prompt or tools. A normal test expects an exact result, while the model answers a little differently every time. That makes checking an agent harder. Huyen considers evaluation the main difficulty of AI engineering.&lt;/p&gt;

&lt;p&gt;The cache got a single line in the glossary table. Judging by the job ads, it's asked about least of all, so it gets a section of its own.&lt;/p&gt;
&lt;h2&gt;
  
  
  How the system works
&lt;/h2&gt;

&lt;p&gt;The model remembers nothing between requests. Everything the agent "knows" about the task, the harness collects and sends again on every step. A request is always built the same way: first the tool descriptions, then the system prompt, then the whole conversation history.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fri4ufa5mg8a84rngo82c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fri4ufa5mg8a84rngo82c.png" alt=" " width="800" height="589"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;What an LLM system consists of. The model receives the assembled request and returns text or a request to call a tool.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In Anthropic's documentation the agent loop itself is an ordinary &lt;code&gt;while&lt;/code&gt;. Here it's in pseudocode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="c1"&gt;# Agent loop pseudocode&lt;/span&gt;
&lt;span class="n"&gt;history&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;user_task&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;model&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;system_prompt&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stop_reason&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"tool_use"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;break&lt;/span&gt;
        &lt;span class="c1"&gt;# the model answered with text: done&lt;/span&gt;
    &lt;span class="n"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;call&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
    &lt;span class="n"&gt;history&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;results&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;# tool_result blocks&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;stop_reason&lt;/code&gt; field explains why the model stopped. If it's &lt;code&gt;tool_use&lt;/code&gt;, the model wants to call a tool, and the loop goes on. Any other value, such as &lt;code&gt;end_turn&lt;/code&gt; or &lt;code&gt;max_tokens&lt;/code&gt;, means the model has finished or hit a limit. Then the loop ends.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fl20go86l90fjr4pap6n0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fl20go86l90fjr4pap6n0.png" alt=" " width="800" height="480"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Step 3 is run by the application code. This is exactly where a hook can block an action.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The loop itself is short. Almost all the work happens around it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;tools:&lt;/strong&gt; your own, those connected through MCP, and server-side ones that the vendor runs itself, such as web search or code execution;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;subagents:&lt;/strong&gt; take a part of the work and return a short report;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;hooks:&lt;/strong&gt; check actions before and after;&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;memory:&lt;/strong&gt; kept not in the model but in files and in git.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Anthropic explains why memory is needed in its article about long-running agents. Every new session starts from a blank slate. So the agent leaves the next session a progress file, a task list with statuses and the commit history.&lt;/p&gt;

&lt;p&gt;You can see this in an ordinary Claude Code setup. In my personal repository, a hook before every &lt;code&gt;Bash&lt;/code&gt;, &lt;code&gt;Write&lt;/code&gt; and &lt;code&gt;Edit&lt;/code&gt; call writes risky actions to a log. Another hook suggests, on every prompt, which model fits the task. There are three subagents: a cheap read-only one, a medium one and a strong one. And more than a dozen skills that load only when needed. It's all plain config files, yet they decide what reaches the model and what the agent may do.&lt;/p&gt;

&lt;p&gt;A common trap: the agent confidently says "done", and only half the work is finished. In the same article Anthropic describes two typical failures. The agent tries to do everything in one go. Or it declares too early that it has finished. Pleading in the prompt barely helps. What helps is the harness: a list of requirements with statuses and a way to check the result. For example, running the tests or opening the application in a browser.&lt;/p&gt;

&lt;h2&gt;
  
  
  How tokens are counted
&lt;/h2&gt;

&lt;p&gt;You pay for an LLM in tokens, and input and output tokens are priced differently. As of October 28, 2026, a million input tokens for Claude Sonnet 5.5 cost $2, and a million output tokens cost $10. Output is 5 times more expensive. Tool descriptions also count as input. In an example from the documentation, one tool with a short schema plus the user's question take 403 tokens together.&lt;/p&gt;

&lt;p&gt;The model remembers nothing, so on every step it's sent the whole history again. Let's count on an illustrative example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;at the start of every request there are 12 thousand tokens: tool descriptions and the system prompt;&lt;/li&gt;
&lt;li&gt;the user's first message takes 200 tokens;&lt;/li&gt;
&lt;li&gt;on each step the model replies with 400 tokens, and the tool returns another 2,500;&lt;/li&gt;
&lt;li&gt;30 steps in total, on Sonnet 5.5.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0wm0oqn94uokp2tl46xh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0wm0oqn94uokp2tl46xh.png" alt=" " width="800" height="616"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Illustrative scenario. Sonnet 5.5 prices as of 2026-10-28.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;On the last step the request weighs 96,300 tokens. That's less than a tenth of the window. But over all 30 steps the model read 1.63 million tokens, 17 times more. Every step pays again for everything that came before it, and the sum grows faster than it seems. Without the cache this task costs $3.38. The model's answers across all steps take only 12 thousand tokens together. Almost all the money goes to input.&lt;/p&gt;

&lt;p&gt;A separate question is how many tokens Russian text takes. Different languages are split into tokens differently. In the study by Petrov et al. (NeurIPS 2023), the same text in different languages took up to 15 times more tokens. For Russian and English I ran a small measurement of my own. I took three pairs of identical texts: documentation, prose and code with comments. About 1,000 characters per language, Claude tokens.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwgkm8nc1x51earl2kcfl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwgkm8nc1x51earl2kcfl.png" alt=" " width="800" height="397"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Measured 2026-10-28. The sample is small; this is a reference point, not a study.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;On the older models (Sonnet 4.6, Haiku 4.5), Russian text took 1.6 times more tokens than English. On the new Sonnet 5.5 the difference is only 1.27 times.&lt;/p&gt;

&lt;p&gt;The interesting part is why. Russian barely changed: it was 402 tokens and became 415. English grew from 252 to 327, by 30%. This matches Anthropic's documentation: starting with Opus 4.7, the models split text in a new way and give about 30% more tokens for the same text.&lt;/p&gt;

&lt;p&gt;So count tokens with the model you'll actually use. Anthropic has a free &lt;code&gt;count_tokens&lt;/code&gt; endpoint for this. It gives an estimate, though, and doesn't take the cache into account.&lt;/p&gt;

&lt;h2&gt;
  
  
  How the prompt cache works
&lt;/h2&gt;

&lt;p&gt;Back to the 1.63 million tokens. Almost everything the model reads on step 30, it already read on step 29: the same tools, the same system prompt, the same history. Only the piece at the end is new. The cache lets the server skip processing the repeating start again.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr0lxmllgeda30gvnoax9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fr0lxmllgeda30gvnoax9.png" alt=" " width="800" height="541"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Block order and what resets the cache, per Anthropic's documentation as of 2026-10-28.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;How it works. A request is always read in the same order: tools, system prompt, messages. You put a mark in the request showing how far to cache. There can be up to four such marks. Everything up to the mark is saved. The next request hits the cache only if its start matches the saved one completely, down to the character and down to the image. The cache lives for 5 minutes, and every hit extends it for free. For an extra fee it can be kept for an hour. Short requests aren't cached: new Claude models need at least 512 tokens. There's no error in that case; the cache simply doesn't turn on.&lt;/p&gt;

&lt;p&gt;In our example with the cache, each step reads the old part at $0.10 per million and writes only the new piece to the cache. The total is $0.51 instead of $3.38, 6.6 times cheaper. The requests are exactly the same; only the way the server processes them changes. TensorMesh's "&lt;a href="https://tensormesh.ai/learn/anthropic-prompt-caching-pricing/" rel="noopener noreferrer"&gt;Prompt Caching Pricing at Anthropic&lt;/a&gt;" works out in detail when a paid cache write pays off. With Anthropic's five-minute cache, it pays off from the second request with the same start.&lt;/p&gt;

&lt;p&gt;The cache is easy to break. Any difference at the start of a request wipes out everything after it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;you changed a tool description: the whole request resets;&lt;/li&gt;
&lt;li&gt;you turned on web search or put the current time into the system prompt: the system prompt and the history reset;&lt;/li&gt;
&lt;li&gt;you changed &lt;code&gt;tool_choice&lt;/code&gt; or added an image: the history resets.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One rule covers all of this: put what never changes at the start and what is new at the end. The start of a request must not contain dates, random IDs or reordered tools.&lt;/p&gt;

&lt;h2&gt;
  
  
  Checklist: ten practices for your first agent
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Start with a single request to the model. A chain beats an agent as long as the task's steps can be written in code.&lt;/li&gt;
&lt;li&gt;Put what never changes at the start of the request and what is new at the end. The system prompt must not contain the time, random IDs or other changing data.&lt;/li&gt;
&lt;li&gt;Don't change the set or order of tools in the middle of a session.&lt;/li&gt;
&lt;li&gt;Look at &lt;code&gt;usage&lt;/code&gt; in every response. If &lt;code&gt;cache_read_input_tokens&lt;/code&gt; is almost always zero, your cache isn't working.&lt;/li&gt;
&lt;li&gt;Count tokens with the model you'll actually use. Different models have different tokens, and the difference reaches 30%.&lt;/li&gt;
&lt;li&gt;Keep the history short. Hand noisy work like search and logs to subagents, and keep state in files, not in the conversation.&lt;/li&gt;
&lt;li&gt;Move long instructions into skills, not the system prompt. Then every request carries only their short descriptions.&lt;/li&gt;
&lt;li&gt;Make whatever must always happen a hook, not a line in the prompt.&lt;/li&gt;
&lt;li&gt;Give the agent a way to check itself: tests, a build, a browser. Otherwise it will say "done" too early.&lt;/li&gt;
&lt;li&gt;Connect MCP servers and skills only from sources you trust, and give the agent only the permissions it needs. Anthropic's documentation compares a third-party skill to a third-party program you install on your machine.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Which of these ten did you learn the hard way?&lt;/p&gt;

&lt;h2&gt;
  
  
  Series "AI Engineering for Newbies"
&lt;/h2&gt;

&lt;p&gt;This is a series of three articles.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;"AI Engineering for Newbies: Agents, MCP, Tokens and Caching, With Numbers" (you are reading it now)&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/muratover/ai-agents-in-production-for-newbies-tools-rag-reliability-and-evals-4boa"&gt;"AI Agents in Production for Newbies: Tools, RAG, Reliability and Evals"&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/muratover/agent-systems-for-newbies-building-a-support-agent-from-one-file-to-temporal-sagas-and-a-circuit-2fhf"&gt;"Agent Systems for Newbies: Building a Support Agent From One File to Temporal, Sagas and a Circuit Breaker"&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>agents</category>
      <category>ai</category>
      <category>beginners</category>
      <category>llm</category>
    </item>
    <item>
      <title>Team Metrics Lie in Isolation: Why I Now Read Them in Pairs</title>
      <dc:creator>Eldar Muratov</dc:creator>
      <pubDate>Fri, 30 Oct 2026 19:04:27 +0000</pubDate>
      <link>https://dev.to/muratover/team-metrics-lie-in-isolation-why-i-now-read-them-in-pairs-41la</link>
      <guid>https://dev.to/muratover/team-metrics-lie-in-isolation-why-i-now-read-them-in-pairs-41la</guid>
      <description>&lt;p&gt;One day my dashboard showed that bugs in one module had gone up by 65%. The explanation was right on the surface: the developers had gotten sloppy, time to tighten up code review. It was convenient, easy to understand, and wrong. The real cause was somewhere else, and I would never have found it if I had looked at that number apart from the others.&lt;/p&gt;

&lt;p&gt;For about two years I have been using a metrics dashboard that I built myself in my spare time, and over that time I learned a simple thing: almost any metric on its own can lie. Not because the data is bad, but because a single number knows nothing about its context. Below I will show which metrics I watch, which of them I read together in pairs, and how to check in one minute whether your own dashboard is fooling you. There is a short checklist at the end.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TL;DR&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Read metrics in pairs: review speed with MR size and defects, Cycle Time with WIP, a "green" rate with the number of events behind it.&lt;/li&gt;
&lt;li&gt;"Lead Time" and "Cycle Time" mean different things in different sources. Until the boundaries are written down, the numbers are not comparable.&lt;/li&gt;
&lt;li&gt;Little's Law checks your dashboard for honesty in one minute.&lt;/li&gt;
&lt;li&gt;A metric for an individual person is, for me, a reason for a one-on-one talk, not a line in a ranking.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What my dashboard is
&lt;/h2&gt;

&lt;p&gt;It is not a product and not a SaaS, it is my working tool. At first it pulled data from Yandex Tracker, Notion and GitLab; now Jira has been added. Changes land in a separate database through CDC (change data capture) and a few workers, and everything else is computed from there. On top of it run analysis scripts, the dashboard itself, and an AI agent that I ask pointed questions like "why did this release slip", and that uses the database for RAG.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ceqa1iacc20rxeazd9j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0ceqa1iacc20rxeazd9j.png" alt="dashboard pipeline" width="800" height="336"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The sources changed; the database and the metrics stayed.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The metrics fall into four groups: planning and estimates, flow speed, quality, and review and releases. The set itself is ordinary; similar lists have been published by &lt;a href="https://habr.com/ru/companies/alfa/articles/1043524/" rel="noopener noreferrer"&gt;Alfa-Bank&lt;/a&gt; and &lt;a href="https://habr.com/ru/companies/simpleone/articles/1007380/" rel="noopener noreferrer"&gt;SimpleOne&lt;/a&gt; (both in Russian). The interesting part starts when the metrics begin to argue with each other.&lt;/p&gt;

&lt;p&gt;A disclaimer up front. All numbers in this article, except the ones linked to research, are illustrative. I have used this approach in several companies, some of them under NDA, and not all of them are on my résumé. So I do not show real team data, and the examples are chosen to show only the general logic.&lt;/p&gt;
&lt;h2&gt;
  
  
  How the dashboard lied to me after a move
&lt;/h2&gt;

&lt;p&gt;The most useful lesson came when I moved the dashboard to another company. Same code, same formulas, fresh data. And the metrics started showing nonsense.&lt;/p&gt;

&lt;p&gt;The reason was mundane. Processes in the new company were set up differently, and the same formulas were now measuring different stretches of work. The status names matched, the meaning did not. I had to adapt the dashboard to the process. Until then Cycle Time honestly showed a number, it was just a number about something else.&lt;/p&gt;

&lt;p&gt;After that I stopped trusting metrics whose boundaries are not written down. And it turned out I was not the only one confused. In the &lt;a href="https://kanbanguides.org/english/" rel="noopener noreferrer"&gt;Kanban Guide&lt;/a&gt;, Cycle Time is the time from when work on an item starts until it is finished. &lt;a href="https://dora.dev/guides/dora-metrics/" rel="noopener noreferrer"&gt;DORA&lt;/a&gt; has Change Lead Time, which runs from commit to production. Same word "lead", different intervals. This is how I define them now:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4kwe6bwun048rph97xof.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F4kwe6bwun048rph97xof.png" alt="time boundaries" width="800" height="459"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Wait Time is the difference between Lead Time and Cycle Time.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I measure all flow metrics in calendar time and kept working hours only for estimate accuracy. It sounds like a detail, but the next section shows what it costs.&lt;/p&gt;
&lt;h2&gt;
  
  
  A one-minute lie detector
&lt;/h2&gt;

&lt;p&gt;There is Little's Law: average Cycle Time equals average WIP (work in progress, the number of items being worked on) divided by Throughput (the number of items finished per day). It holds on historical data and for a stable flow, where work does not pile up endlessly (&lt;a href="https://scrumorg-website-prod.s3.amazonaws.com/drupal/2018-05/Little%E2%80%99s%20Law%20for%20Professional%20Scrum%20with%20Kanban.pdf" rel="noopener noreferrer"&gt;Vacanti, Scrum.org&lt;/a&gt;). For a team lead it is a free lie detector.&lt;/p&gt;

&lt;p&gt;For example: on average 40 items are in progress, and 280 were closed in four weeks.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;wip&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;closed&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;days&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;280&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;28&lt;/span&gt;
&lt;span class="n"&gt;throughput&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;closed&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;days&lt;/span&gt;          &lt;span class="c1"&gt;# 10 items per day
&lt;/span&gt;&lt;span class="n"&gt;cycle_days&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;wip&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;throughput&lt;/span&gt;       &lt;span class="c1"&gt;# 4.0 days
&lt;/span&gt;&lt;span class="nf"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cycle_days&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;24&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;              &lt;span class="c1"&gt;# 96 hours
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Little says: 96 hours per item on average. The dashboard shows a Cycle Time of 32 hours. One of them is lying, and it is usually not the math.&lt;/p&gt;

&lt;p&gt;I check three things. First, units: 32 working hours and 32 calendar hours are different durations. Then windows: WIP and Throughput must be computed over the same period. Finally, what counts as "in progress": if the queue got into WIP, it is closer to Lead Time than to Cycle Time. The mismatch almost always turns up at one of these steps.&lt;/p&gt;

&lt;p&gt;Little's Law is also useful for forecasting. If Throughput stays flat and WIP grows, every item will take longer. That is not "the team got slower", that is arithmetic.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2o3dxlvux920hjoj62qc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2o3dxlvux920hjoj62qc.png" alt="little wip cycle" width="800" height="453"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The team works at the same speed; items just wait in the queue longer.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So I never read a rise in Cycle Time on its own. First I look at WIP. If it went up by half, what needs fixing is the number of parallel items, not people's speed.&lt;/p&gt;

&lt;h2&gt;
  
  
  The pairs I never open the dashboard without
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Time to First Review, MR Size and Escaped Defects
&lt;/h3&gt;

&lt;p&gt;Fast review is pleasant to look at. But picture a chart where the time to first review dropped over a quarter from six hours to 36 minutes. You want to praise the team. Now put next to it the size of merge requests (MRs) in lines and the defects found after release.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7jnlpsaljxgzn71n7v07.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7jnlpsaljxgzn71n7v07.png" alt="review vs defects" width="800" height="653"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;The top chart without the two below looks like a success.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If MRs get bigger while review gets faster, review has almost certainly turned into a formality. Research backs this up. Kemerer and Paulk, on data from 371 and 246 student programs, showed that at review rates up to 200 lines per hour more than half of the defects in the code are found; going slower does not improve it further, and going faster makes it drop (&lt;a href="https://sites.pitt.edu/~ckemerer/PSP_Data.pdf" rel="noopener noreferrer"&gt;IEEE TSE, 2009&lt;/a&gt;). A 500-line MR approved in ten minutes is not speed, it is a miss. And given the AI slop all around us these days, some very interesting things can make it into the repository.&lt;/p&gt;

&lt;p&gt;That said, fast review is not evil in itself. At Google the median wait for a first response is under an hour for small changes, and the median change is only 24 lines (&lt;a href="https://sback.it/publications/icse2018seip.pdf" rel="noopener noreferrer"&gt;Sadowski et al., 2018&lt;/a&gt;), and that was before the AI boom. It is fast there because the changes are small. DORA's 2023 report links fast code review to higher software delivery performance, but warns that if review is already fast, speeding it up further is pointless (&lt;a href="https://dora.dev/research/2023/dora-report/2023-dora-accelerate-state-of-devops-report.pdf" rel="noopener noreferrer"&gt;DORA 2023&lt;/a&gt;).&lt;/p&gt;

&lt;h3&gt;
  
  
  A green metric and the number of events
&lt;/h3&gt;

&lt;p&gt;Twelve deployments in a month, none rolled back, Change Failure Rate 0%. Great result? In fact 0 out of 12 proves almost nothing. One failed deployment next month gives 8%, and the team will not have gotten any worse.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fs9bdaf9nlfjs9qnvpgkj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fs9bdaf9nlfjs9qnvpgkj.png" alt="small sample" width="800" height="376"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;One deployment separates "excellent" from "alarming".&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;MTTR is even funnier: no incidents, no metric. So next to every rate I show n, the number of events, and metrics with a small sample are labeled "not enough data". Boring, but it saves you from celebrating nothing.&lt;/p&gt;

&lt;h3&gt;
  
  
  Reopened tasks and defects
&lt;/h3&gt;

&lt;p&gt;The share of reopened tasks is low, and that looks like quality. But if a bug that is found gets filed as a new task instead of reopening the old one, the reopen counter simply does not see it. A low reopen rate with a high number of defects means one thing: bugs are going around that counter.&lt;/p&gt;

&lt;h3&gt;
  
  
  Estimate accuracy and delivery time
&lt;/h3&gt;

&lt;p&gt;A team can accurately estimate a task at eight hours or 3 story points and deliver it a week later. Because it waited three days in the queue and then sat in review for two more. Good estimates with bad delivery times point to a flow problem, not an estimation problem. To calibrate expectations: according to a review of surveys, 60–80% of projects overrun their effort or schedule, by 30–40% on average (&lt;a href="https://cms.simula.no/sites/default/files/publications/SE.3.Moloekken-Oestvold.2004.pdf" rel="noopener noreferrer"&gt;Moløkken, Jørgensen, 2003&lt;/a&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  You can see an overloaded release in advance
&lt;/h2&gt;

&lt;p&gt;The most practical pair for a team lead: team capacity and the release plan. Capacity comes from the people and their availability, the plan from the estimated tasks. When more is planned than there is capacity for, or one person is loaded twice over, you see it before the release starts, not at the retro afterwards. I have had such cases, and the overload was visible on the dashboard in advance.&lt;/p&gt;

&lt;p&gt;There is a catch: tasks without an estimate do not count toward the load. So the real load is higher than what is on the screen. That is why next to the load I always show the number of unestimated tasks.&lt;/p&gt;

&lt;h2&gt;
  
  
  A person's metric is a reason to talk
&lt;/h2&gt;

&lt;p&gt;The dashboard has a breakdown by developer. It is its most controversial part, and I understand why. DORA warns directly: these metrics work at the team or service level, and once they are turned into targets, people start gaming them (&lt;a href="https://dora.dev/guides/dora-metrics/" rel="noopener noreferrer"&gt;DORA&lt;/a&gt;). People quickly learn to split tasks, take the easy ones and put off the hard ones. The metric goes up, the work does not.&lt;/p&gt;

&lt;p&gt;So I do not compare people by these numbers. For me it is a signal. If someone's output dropped or their bug count went up, it is time for a one-on-one to ask what is bothering them. In my experience, a drop in output is often not about work but about what is going on in the person's life outside it. That is an opinion, not research. But a plain conversation between two people always shows much more than any chart.&lt;/p&gt;

&lt;h2&gt;
  
  
  How the module story ended
&lt;/h2&gt;

&lt;p&gt;Back to the 65% more bugs. I think every team has run into a situation like this. I did not tighten up review. It turned out that tasks for the module were arriving half-baked. The PM was rushing the team toward a deadline that had been badly planned from the start, and requirements were worked out in a hurry. The code was reviewed, but review does not cure a bad task definition.&lt;/p&gt;

&lt;p&gt;We fixed the input. We started working out requirements together with the analysts and the PM before a task goes into development. And we deliberately slowed development down so that features could be thought through before any code was written. Roughly, it looked like this: two months later bugs in the module were down by about 40%, and the average time per task in the module was up by about 15%. I was happy with that trade.&lt;/p&gt;

&lt;p&gt;The conclusion for me is simple. A module's bug rate is not only a development metric. Often it shows planning problems, and it needs to be discussed not only with the developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  What changed
&lt;/h2&gt;

&lt;p&gt;In short, this dashboard helped reduce the number of bugs and people's overload, speed up fixing production bugs, shorten time-to-market and raise Throughput. The real data is under NDA, so below is an illustrative order of magnitude of the changes over a year in one of the teams:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;Before&lt;/th&gt;
&lt;th&gt;After&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Defect Rate (share of tasks with defects)&lt;/td&gt;
&lt;td&gt;43%&lt;/td&gt;
&lt;td&gt;18%&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;People loaded above capacity in a release&lt;/td&gt;
&lt;td&gt;8 of 15&lt;/td&gt;
&lt;td&gt;2 of 15&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Median time to fix a production bug&lt;/td&gt;
&lt;td&gt;3+ days&lt;/td&gt;
&lt;td&gt;&amp;lt;1 day&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Lead Time (from task creation to production)&lt;/td&gt;
&lt;td&gt;14 days&lt;/td&gt;
&lt;td&gt;7 days&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Throughput (tasks per week)&lt;/td&gt;
&lt;td&gt;32&lt;/td&gt;
&lt;td&gt;115&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The numbers in the table are illustrative and show the direction of the changes, not the result of a specific team.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where I might be wrong
&lt;/h2&gt;

&lt;p&gt;The research I rely on is not final. McIntosh and colleagues found a link between review coverage and post-release defects, but a &lt;a href="https://web.eecs.utk.edu/~audris/papers/ReviewBayes.pdf" rel="noopener noreferrer"&gt;re-analysis&lt;/a&gt; could not confirm it. Kemerer and Paulk worked with student PSP data, not with team code review in GitLab. The DORA reports are based on surveys and show correlation, not causation.&lt;/p&gt;

&lt;p&gt;The popular figure "flow efficiency in most teams is 5–15%" comes from consultants' experience, not from research. There is a good &lt;a href="https://medium.com/asos-techblog/our-survey-says-uncovering-the-real-numbers-behind-flow-efficiency-e54f136b1fab" rel="noopener noreferrer"&gt;critique based on data from 63 teams&lt;/a&gt;, so I do not turn such benchmarks into targets. Most importantly, in our teams we always want to build great things, and this story shows how one tool can make life a little better for everyone.&lt;/p&gt;

&lt;p&gt;And the main point: my conclusions come from my teams, my experience and my definitions, which give repeatable results.&lt;/p&gt;

&lt;h2&gt;
  
  
  Checklist: check your dashboard in ten minutes
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;For Lead Time, Cycle Time and Change Lead Time, it is written down from which status to which status the clock runs.&lt;/li&gt;
&lt;li&gt;All flow metrics use the same units, with no mixing of working and calendar hours.&lt;/li&gt;
&lt;li&gt;Little's Law holds: WIP divided by Throughput is roughly equal to the average Cycle Time.&lt;/li&gt;
&lt;li&gt;Every rate shows the number of events next to it; small samples are flagged.&lt;/li&gt;
&lt;li&gt;Time to First Review is shown together with MR Size and Escaped Defects.&lt;/li&gt;
&lt;li&gt;The reopen rate is checked against the total number of defects.&lt;/li&gt;
&lt;li&gt;Release load is shown together with the number of unestimated tasks.&lt;/li&gt;
&lt;li&gt;Individual metrics are used for conversations, not for rankings.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If three of the eight are not met, your dashboard is more likely to reassure you than to help. Metrics are best read as a system, where one number explains another. A board full of green lights is pleasant, but it holds less truth than it seems.&lt;/p&gt;

&lt;p&gt;Which pair of metrics has fooled you the most when you looked at it alone?&lt;/p&gt;

</description>
      <category>management</category>
      <category>productivity</category>
      <category>analytics</category>
      <category>softwareengineering</category>
    </item>
  </channel>
</rss>
