Skip to content

    Agentic AI for Java

    Observability, cost and production architecture

    Trace every agent step, estimate tokens and cost, stop a run at a budget, and design the production setup around the loop, with a plain-Java lab.

    By Published 24 min read

    Share

    This lesson is part of Agentic AI for Java Developers: Build and Ship Agents. Enroll for free, then sign in, to read it in full.

    What you'll learn: how to wrap the agent loop with traces, counters, a cost meter and a budget that stops a run, why the cost of a run grows faster than its step count, and what production plumbing a real agent needs around the loop.

    The demo went well. The agent answered in five steps and everyone clapped. Then it met real traffic. One run took twelve steps, another looped on a failing tool until a timeout, and a bill arrived that nobody had predicted. When someone asked "what did it actually do?", the only answer was a final sentence.

    An agent is a loop, and a loop's cost and failure modes grow with every pass. The single idea of this lesson: instrument the trajectory, meaning every model call and every tool call, put a budget on it, and then give it the same production plumbing you would give any service that does slow, expensive, unreliable work.

    Parcelo, the delivery company, and its incidents are invented. The lab uses scripted models, a fake clock and an invented price table, so every number below is a demonstration of arithmetic. None of it is a measurement of a real model, and none of the prices is real.

    The idea in one picture

    The agent loop from the earlier lesson stays untouched. Observability is added around it with decorators: a wrapper that looks like a model and a wrapper that looks like a tool. Everything the loop does passes through one of them.

    Figure 1. Decorators around an unchanged loop

    The agent loop calls a traced model and traced tools, which write spans, counters, cost and logs and check a budgetAgent loop to Traced model (reply); Agent loop to Traced tools (execute); Traced model to Model; Traced tools to Parcelo tools; Traced model to Cost meter (usage); Cost meter to Telemetry; Traced tools to Telemetry (spans)Agent loop: unchangedAgent loopunchangedTraced model: decoratorTraced modeldecoratorTraced tools: decoratorTraced toolsdecoratorModel: scripted hereModelscripted hereParcelo tools: read onlyParcelo toolsread onlyTelemetry: spans, counters, logsTelemetryspans, counters,logsCost meter: tokens, budgetCost metertokens, budgetreplyexecuteusagespans

    How to read this: follow the moving packets from the loop to the model and the tools. The dashed arrows are the side channel: usage goes to the cost meter, and spans, counters and log lines go to telemetry, without changing what the loop sees.

    TIP

    Picture it: A parcel with a tracking number gets scanned at every depot. The courier does not change how it drives, yet you can later see every stop and how long it waited. Spans are those scans. The analogy stops at one point: a parcel moves forward only, while an agent can go back to the same tool ten times.

    What to trace: the trajectory

    A web request has one path. An agent run has many steps whose number and order are not known in advance, so the useful unit of observation is the run as a tree. A span is one named piece of work with a start, an end and a parent. The run is the root span, and each model call and each tool call is a child.

    For every run you want to be able to answer: which steps happened, in what order, how long each took, how many tokens each model call used, which tools failed, and why the run stopped. The lab's tracer records exactly that, with deterministic ids (s1, s2, ...) and a fake clock, so the output is the same on every run.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/Tracer.java

        public record Span(String id, String parentId, String kind, String name, long startMs, long endMs, boolean error,
                           Map<String, String> attributes) {
            public Span {
                attributes = Map.copyOf(attributes);
            }
    
            public long durationMs() {
                return endMs - startMs;
            }
        }

    A real tracer such as OpenTelemetry uses random ids and sends spans to a backend. The shape is the same, and the Micrometer lesson linked below shows how to produce spans from a Spring application. The lab keeps its own tiny tracer so you can read all of it.

    Figure 2. One run as a span tree

    flowchart TD accTitle: The span tree of one observed run accDescr: The run span s1 has ten children in time order. Model calls s2, s4, s7, s9 and s11 alternate with tool calls s3, s5, s6, s8 and s10, and the tool call s8 is an error. S1[s1 run agent.run 0 to 4600 ms] S2[s2 model_call 0 to 800 ms] S3[s3 tool get_alert] S4[s4 model_call 920 to 1720 ms] S5[s5 tool query_metric] S6[s6 tool search_logs] S7[s7 model_call 1960 to 2760 ms] S8[s8 tool get_alert ERROR] S9[s9 model_call 2880 to 3680 ms] S10[s10 tool search_runbook] S11[s11 model_call 3800 to 4600 ms] S1 --> S2 S1 --> S3 S1 --> S4 S1 --> S5 S1 --> S6 S1 --> S7 S1 --> S8 S1 --> S9 S1 --> S10 S1 --> S11

    How to read this: this is the run you will see in the output below, drawn as a tree. All ten children hang under the run span s1. The failing get_alert call (s8) is a sibling of the others, which is how a trace viewer lets you find the one bad step among eleven spans.

    Build it: decorators

    TracedModel implements the same ChatModel interface as the model it wraps, so the loop cannot tell the difference. For each call it estimates the input tokens, checks the cost cap, starts a span, calls the real model, records usage and cost, increments a counter and writes one log line.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/TracedModel.java

        @Override
        public ModelReply reply(List<Message> conversation, List<ToolSpec> tools) {
            long inputTokens = TokenEstimator.estimateInput(conversation, tools);
            CostMeter cost = telemetry.cost();
            if (cost.costMicro() + cost.price().costMicro(inputTokens, 0) > telemetry.budgetMicro()) {
                telemetry.counters().increment("budget_stops");
                telemetry.log().log("WARN", "budget_stop", "spent_micro", cost.costMicro(), "cap_micro", telemetry.budgetMicro(),
                        "next_input_tokens_est", inputTokens);
                throw new BudgetExceededException("the next model call would take the run past its cap of " + telemetry.budgetMicro() + " micro-units");
            }
            Tracer.Open span = telemetry.tracer().start("model_call", "llm.reply", telemetry.runSpanId());
            try {
                ModelReply reply = inner.reply(conversation, tools);
                long outputTokens = TokenEstimator.estimateOutput(reply);
                cost.record(inputTokens, outputTokens);
                long callCost = cost.price().costMicro(inputTokens, outputTokens);
                span.attr("input_tokens_est", inputTokens).attr("output_tokens_est", outputTokens).attr("cost_micro", callCost);
                telemetry.counters().increment("model_calls");
                telemetry.log().log("INFO", "model_call", "span", span.id(), "input_tokens_est", inputTokens,
                        "output_tokens_est", outputTokens, "cost_micro", callCost);
                return reply;
            } catch (RuntimeException e) {
                span.fail();
                telemetry.counters().increment("model_errors");
                telemetry.log().log("ERROR", "model_call_failed", "span", span.id(), "error", e.getClass().getSimpleName());
                throw e;
            } finally {
                span.end();
            }
        }

    Read it in three parts. The first if is the budget guard and runs before any money is spent. The try block is the normal path: call, measure, record. The catch marks the span as an error and rethrows, so the failure still reaches the loop. The finally always closes the span, even on an exception.

    TracedTool does the same for a tool. It has the same spec and the same result, so the model sees nothing different. The class comment records an honest limitation: the agent validates arguments and looks up the tool before calling execute, so an unknown tool or invalid arguments never reach this decorator.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/TracedTool.java

        @Override
        public String execute(Map<String, Object> arguments) throws Exception {
            Tracer.Open span = telemetry.tracer().start("tool_call", inner.name(), telemetry.runSpanId());
            try {
                String result = inner.execute(arguments);
                span.attr("result_chars", result.length());
                telemetry.counters().increment("tool_calls");
                telemetry.log().log("INFO", "tool_call", "span", span.id(), "tool", inner.name(), "result_chars", result.length());
                return result;
            } catch (Exception e) {
                span.fail();
                telemetry.counters().increment("tool_calls");
                telemetry.log().log("WARN", "tool_call_failed", "span", span.id(), "tool", inner.name(), "error", e.getClass().getSimpleName());
                throw e;
            } finally {
                span.end();
            }
        }

    That is why ObservedAgent counts errors a different way. It wraps the whole run in a root span, wraps every tool, runs the unchanged Agent, and then counts tool errors from the run's own trace, which includes unknown tools and invalid arguments.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/ObservedAgent.java

            Tracer.Open run = telemetry.tracer().start("run", "agent.run", null);
            telemetry.startRun(run.id());
    // ...
            List<Tool> traced = tools.stream().<Tool>map(t -> new TracedTool(t, telemetry)).toList();
            Agent agent = new Agent(new TracedModel(model, telemetry), new Tools(traced), config);
            try {
                AgentResult result = agent.run(goal);
                long errors = result.trace().events().stream().filter(e -> e.kind() == Trace.Kind.TOOL_ERROR).count();
                telemetry.counters().add("tool_errors", errors);
                telemetry.counters().add("steps", result.steps());

    Every log line the lab writes is structured: a fixed set of key=value pairs, one event per line, so a log system can filter and count them. The lab logs sizes, ids and costs. It never logs the text of prompts or tool results, which can hold personal or secret data. Spring AI follows the same default: the properties that log prompt and completion content are off unless you turn them on (details below).

    TIP

    Picture it: A ship's logbook has a fixed format: time, event, position. Anyone can scan it after a storm, and nobody writes the cargo owner's private letters in it. Structured logs are that logbook: same fields each time, so a machine can read them, and no private content. The analogy stops at retention: a logbook is kept forever, while logs of user data need a deletion policy.

    Tokens, cost and a budget

    A token is the unit a language model reads and writes, roughly a few characters of text. Providers bill by tokens, separately for what you send (input) and what the model writes (output). Usage is the provider's report of both numbers for each call. The lab cannot call a provider, so it estimates: one token per four characters. That is crude and labelled as such in the code.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/TokenEstimator.java

        public static long estimate(String text) {
            return (text.length() + 3) / 4;
        }

    The estimate of one call counts every message in the conversation, because the whole conversation is sent on each call, plus the description of every tool, because those are sent too. Prices come from a table of invented numbers: a small model and a large one that costs ten times as much per token.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/Price.java

    public record Price(String model, long inputUnitsPerMillion, long outputUnitsPerMillion) {
    
        /** The cost in micro-units of a call with this many input and output tokens. */
        public long costMicro(long inputTokens, long outputTokens) {
            return inputTokens * inputUnitsPerMillion + outputTokens * outputUnitsPerMillion;
        }
    
        /** A small, cheap tier (invented). */
        public static final Price SMALL = new Price("model-small", 100, 400);
    
        /** A large, expensive tier (invented): ten times the small one. */
        public static final Price LARGE = new Price("model-large", 1000, 4000);

    The arithmetic is integer on purpose: tokens times units per million gives micro-units (a millionth of an invented unit), so the lab prints the same digits on every machine. Real prices are on the provider's pricing page and change. Never copy a price from a lesson, including this one.

    Figure 3. The budget check before every model call

    Before each model call the estimated input cost is added to the spend so far and compared with the capAgent loop to Estimate input; Estimate input to Cap check; Cost meter to Cap check (spent); Cap check to Model call (under cap); Model call to Cost meter (usage); Cap check to Stop the run (over cap)Agent loop: next stepAgent loopnext stepEstimate input: chars over fourEstimate inputchars over fourCap check: spent plus nextCap checkspent plus nextCost meter: spent so farCost meterspent so farModel call: then record usageModel callthen record usageStop the run: budget stopStop the runbudget stopspentunder capusageover cap

    How to read this: the run moves left to right through the check. Under the cap, the call goes ahead and its usage flows back to the meter. Over the cap, the red dashed path stops the run before the money is spent.

    Two limits are worth saying out loud. The check can only see the input it knows about, so output tokens can still push the run a little past the cap: a cap is a guard rail, not an exact ceiling. And the check uses the estimate, not the provider's bill, which you should still alert on separately.

    TIP

    Picture it: A taxi meter ticks up with every kilometre, and a prepaid card refuses the next ride when the balance is too low. The cost meter is the ticking, and the budget is the card. The analogy stops at one point: a taxi's meter is exact, while the lab's meter is an estimate until you replace it with the provider's usage report.

    Why the cost of a run grows faster than its steps

    Here is the most important number in the lesson. A chat model keeps no memory between calls, so on every step the agent sends the whole conversation again: the instructions, the goal, every earlier request and every earlier tool result. Each step adds a little text, but every later call pays for everything that came before.

    Add up the input tokens over a run, and the sum grows faster than the number of steps. The lab measures it on scripted runs of 3, 6 and 12 steps. Each run asks for a fixed cycle of Parcelo's four read-only tools, then answers.

    Verified: examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/GrowthExperiment.java

        public static Result run(int steps) {
            List<ModelReply> script = new ArrayList<>();
            for (int i = 0; i < steps - 1; i++) {
                script.add(toolCall(i));
            }
            script.add(ModelReply.say("Likely cause: the payments-gateway deploy v412 exhausted its database pool."));
    
            Telemetry telemetry = Telemetry.uncapped(new FakeClock(), Price.SMALL);
            ObservedAgent.run(telemetry, new ScriptedModel(script), Parcelo.readOnlyTools(),
                    new AgentConfig("You are an on-call assistant. Read only.", steps), "Alert A-1042 is firing. What is going on?");
            CostMeter cost = telemetry.cost();
            return new Result(steps, cost.calls(), cost.inputTokens(), cost.outputTokens(), cost.costMicro());
        }

    Figure 4. The history is sent again on every call

    Estimated input tokens of each model call in a six-step run, each larger than the one beforeCall 1 to Call 2 (plus 32); Call 2 to Call 3 (plus 30); Call 4 to Call 5 (plus 53); Call 5 to Call 6 (plus 32)Call 1: 308 tokens estCall 1308 tokens estCall 2: 340 tokens estCall 2340 tokens estCall 3: 370 tokens estCall 3370 tokens estCall 4: 409 tokens estCall 4409 tokens estCall 5: 462 tokens estCall 5462 tokens estCall 6: 494 tokens estCall 6494 tokens estplus 32plus 30plus 53plus 32

    How to read this: read the top row, then the bottom row, as one run of six calls. Every call sends everything the previous call sent, plus the new request and result, so the input never shrinks. The numbers are the lab's estimates.

    Expected output, captured from a real run (token numbers are estimates, prices are invented):

    Run 3. The whole history is resent on every step (token numbers are estimates)
      steps  input tokens per call
      3      [308, 340, 370]
      6      [308, 340, 370, 409, 462, 494]
      12     [308, 340, 370, 409, 462, 494, 524, 563, 616, 648, 678, 717]
    
      steps  total input  total output  cost (micro-units, model-small)
      3      1018         42            118600
      6      2383         69            265900
      12     6129         141           669300
      twice the steps (6 to 12): input tokens x2.57, cost x2.52 (a linear run would be x2.00)

    Read the first table down: call 1 sends 308 estimated tokens, and call 12 sends 717. The second table is the point: doubling the steps from 6 to 12 multiplied the input by 2.57, not 2. The reason it is not 4 is that about 300 tokens of every call are a fixed cost (instructions, goal, tool descriptions) that does not grow, and the lab's tool results are short. The longer the tool results and the more steps, the more the growing part dominates.

    In general terms: if each step adds about the same amount of text, call number k sends the fixed part plus about k times that amount, and the sum over n calls has a term that grows with n squared. The lab shows the direction with real arithmetic. It does not claim a formula for your agent, whose tool results will not be this regular.

    TIP

    Picture it: A book club that re-reads all the minutes from the first meeting at the start of every meeting. Meeting 12 takes far longer than meeting 1, and the whole year takes far longer than twelve times a short meeting. Each call to a model is a meeting that starts with the full minutes. The analogy stops at the reader: a model reads fast and charges by the token, not by the hour.

    NOTE

    On call, 3 a.m.: Wiktor Szymanski runs the support agent at Kestrel Freight, an invented company. One request makes the agent retry a failing lookup, and a run that normally takes four steps takes thirty. Nothing is down, so no alert fires, yet that run uses many times the input of an ordinary one. Wiktor adds a per-run cost cap and an alert on steps per run. The next stuck run is stopped after a few calls, with a clear log line. Invented example.

    Run it

    From examples/backend:

    ./gradlew :labs:agent-observability:test       # 13 tests
    ./gradlew -q :labs:agent-observability:run     # the whole lab

    Expected output, captured from a real run (an observed run: the span tree, with each model call set to take 800 ms and each tool 120 ms on a fake clock):

    Run 1. One observed run: span tree, cost, counters, log lines
      span tree (times from a fake clock; each model call is set to take 800 ms, each tool 120 ms)
        s1   parent=-    run        agent.run            0-4600  ms steps=5 stop=FINAL_ANSWER
        s2   parent=s1     model_call llm.reply            0-800   ms cost_micro=35200 input_tokens_est=324 output_tokens_est=7
        s3   parent=s1     tool_call  get_alert          800-920   ms result_chars=100
        s4   parent=s1     model_call llm.reply          920-1720  ms cost_micro=47200 input_tokens_est=356 output_tokens_est=29
        s5   parent=s1     tool_call  query_metric      1720-1840  ms result_chars=54
        s6   parent=s1     tool_call  search_logs       1840-1960  ms result_chars=102
        s7   parent=s1     model_call llm.reply         1960-2760  ms cost_micro=45300 input_tokens_est=425 output_tokens_est=7
        s8   parent=s1     tool_call  get_alert         2760-2880  ms  ERROR
        s9   parent=s1     model_call llm.reply         2880-3680  ms cost_micro=47000 input_tokens_est=442 output_tokens_est=7
        s10  parent=s1     tool_call  search_runbook    3680-3800  ms result_chars=183
        s11  parent=s1     model_call llm.reply         3800-4600  ms cost_micro=66700 input_tokens_est=495 output_tokens_est=43

    Read the tree top to bottom. s1 is the run and every other span names it as its parent. The model calls are 800 ms each and the tools 120 ms each, because the lab told its fake clock so; in a real trace the numbers would be measured, and a slow span would stand out at once.

    Span s8 is marked ERROR: the model asked for alert A-9999, which does not exist, and the tool threw. Notice also that s5 and s6 follow each other, although the model asked for them in one reply: this loop runs a reply's tool calls one after the other. The concurrency lesson changes that.

    Expected output, captured from a real run (cost, counters and the structured log lines of the same run):

      per call (estimates): [#1 in 324 out 7, #2 in 356 out 29, #3 in 425 out 7, #4 in 442 out 7, #5 in 495 out 43]
      total: input 2042 tokens, output 93 tokens, cost 241400 micro-units on model-small
      the same tokens on model-large would cost 2414000 micro-units
      counters: model_calls=5 steps=5 tool_calls=5 tool_errors=1
      outcome: FINAL_ANSWER after 5 model calls
      log lines:
        t=0ms level=INFO event=run_started span=s1 max_steps=8 budget_micro=none
        t=800ms level=INFO event=model_call span=s2 input_tokens_est=324 output_tokens_est=7 cost_micro=35200
        t=920ms level=INFO event=tool_call span=s3 tool=get_alert result_chars=100
        t=1720ms level=INFO event=model_call span=s4 input_tokens_est=356 output_tokens_est=29 cost_micro=47200
        t=1840ms level=INFO event=tool_call span=s5 tool=query_metric result_chars=54
        t=1960ms level=INFO event=tool_call span=s6 tool=search_logs result_chars=102
        t=2760ms level=INFO event=model_call span=s7 input_tokens_est=425 output_tokens_est=7 cost_micro=45300
        t=2880ms level=WARN event=tool_call_failed span=s8 tool=get_alert error=IllegalArgumentException
        t=3680ms level=INFO event=model_call span=s9 input_tokens_est=442 output_tokens_est=7 cost_micro=47000
        t=3800ms level=INFO event=tool_call span=s10 tool=search_runbook result_chars=183
        t=4600ms level=INFO event=model_call span=s11 input_tokens_est=495 output_tokens_est=43 cost_micro=66700
        t=4600ms level=INFO event=run_finished span=s1 stop=FINAL_ANSWER steps=5 tool_errors=1

    Look at the counters: tool_calls=5 counts the tools that actually ran (including the one that threw), and tool_errors=1 counts failed requests. The same total on the invented large tier is ten times the small one, which is the whole point of the "cheaper model for easy steps" lever below. The log line for s8 carries the exception class and no message text.

    Now the budget. The same agent, with a model that never answers and a cap of 100,000 micro-units:

    Expected output, captured from a real run (the cap stops a model that never answers):

    Run 2. A cost cap stops a model that never answers
      cap 100000 micro-units, step limit 50
      call #1: input 324 tokens, cost 35200 micro-units
      call #2: input 356 tokens, cost 38400 micro-units
      spent 73600 micro-units
      outcome: BUDGET_EXCEEDED after 2 model calls (the step limit of 50 was never reached)
      counters: budget_stops=1 model_calls=2 steps=2 tool_calls=2
      t=1600ms level=WARN event=budget_stop spent_micro=73600 cap_micro=100000 next_input_tokens_est=388
      t=1600ms level=WARN event=run_stopped span=s1 stop=BUDGET_EXCEEDED model_calls=2

    The step limit of 50 was never reached, because the money ran out first. After two calls the lab had spent 73,600; the next call's input alone was estimated at 388 tokens, which is 38,800 more, which would cross 100,000. So the guard stopped the run before the third call, and the warning log line says why.

    Cost, steps and a budget (interactive when JavaScript is on)

    A run under its budget

    1. 1. Run starts. The run span s1 opens, with max_steps=8 and no budget (budget_micro=none).
    2. 2. Model call. s2: 324 estimated input tokens, 7 output tokens, cost 35200 micro-units. The model asks for get_alert.
    3. 3. Tool call. s3: get_alert runs for 120 ms and returns 100 characters.
    4. 4. An error. s8: the model asks for get_alert on A-9999. The tool throws and the span is marked ERROR.
    5. 5. Finished. Five model calls, 2042 input tokens and 93 output tokens in total, cost 241400 micro-units, counters tool_errors=1.

    The cap stops a run

    1. 1. Cap set. The cap is 100000 micro-units and the step limit is 50.
    2. 2. Call 1. 324 input tokens, cost 35200 micro-units.
    3. 3. Call 2. 356 input tokens, cost 38400 micro-units. Spent so far: 73600.
    4. 4. The guard. The next call would need 388 input tokens. Spent plus that call would cross the cap, so the guard logs budget_stop.
    5. 5. Stopped. The outcome is BUDGET_EXCEEDED after 2 model calls. The step limit of 50 was never reached.

    History grows

    1. 1. A 3-step run. Input per call: 308, 340, 370. Total 1018 estimated tokens.
    2. 2. A 6-step run. The same first three calls, then 409, 462 and 494. Total 2383.
    3. 3. A 12-step run. Call 12 sends 717 estimated tokens. Total 6129.
    4. 4. The ratio. From 6 to 12 steps, input tokens grew by x2.57 and cost by x2.52. A linear run would be x2.00.

    Under the hood: what the provider reports

    Your decorators work with estimates, but the provider's response carries the real numbers. Anthropic's prompt-caching page, for example, documents a usage object in the response with input_tokens, cache_creation_input_tokens and cache_read_input_tokens. It states that total input is the sum of the three, and that if both cache fields are zero the prompt was not cached.

    So in production, TracedModel would read the usage from the response and record that, and the character-based estimate would survive only as the pre-call guess the budget guard needs, because a guard has to decide before the call is made. Bill and alert on the provider's numbers. A model call is plain HTTP: you send the conversation and tool descriptions as JSON, you get back a reply and a usage report. Nothing else is happening behind the decorators.

    Where Spring AI and Micrometer fit

    If you build on Spring AI, much of what the lab does by hand is already instrumented. The Spring AI reference page on observability says it is built on Micrometer and covers ChatClient (including advisors), ChatModel, tool calling, embeddings and vector stores. It names the observations: spring.ai.chat.client for a ChatClient call, spring.ai.advisor, gen_ai.client.operation for model calls, and spring.ai.tool for tool calling. A metric named gen_ai.client.token.usage reports input and output tokens per call.

    The page also separates low-cardinality keys, which go onto metrics and traces, from high-cardinality keys, which go onto traces only. That is the same rule as in the Micrometer lesson linked below: put an unbounded value, such as a prompt, in a metric label and your metrics store grows without limit. Finally, the properties that log prompts, completions and tool content default to false, and the page warns that turning them on can expose sensitive or private information. Examples are spring.ai.chat.observations.log-prompt and spring.ai.tools.observations.include-content.

    Treat these names as what the current reference page said when this lesson was written, and check them against the version you use. The page lists them per component, with provider-specific limits for some models. Whichever way you collect the signals, the questions are the ones in the table below.

    What to watch Why it matters An alert idea (choose your own numbers)
    Steps per run A rising count means loops or confused tool use Steps per run above its usual range
    Tool calls and tool errors A failing tool makes the model retry A rise in the error share of tool calls
    Input and output tokens per call The input grows with the history Tokens per run well above the usual
    Latency per model call and per tool Tells you where a slow run spent its time The tail of run latency above your target
    Errors from the provider Rate limits and outages come from outside A sustained rise in provider errors
    Cost per completed task The number the business cares about Cost per task above its budget
    Budget stops A stop is a sign of a stuck or abused run Any rise in the count of stopped runs

    For the general picture of dashboards, golden signals and incident response for LLM systems, read the LLM observability guide. Its examples are about one model call per request, so the table above is what you add for the loop.

    TIP

    Picture it: A dashboard of a delivery fleet shows the number of trucks out, the average delay and the fuel used. When fuel use doubles, you ask which route changed, and you need the per-trip log to find out. Counters are the fleet view, spans are the per-trip log. The analogy stops at the sampling: you can often keep every truck's log, but storing every run's prompt text is a privacy decision.

    Cost levers

    If the cost is the product of calls, tokens per call and price per token, there are four levers, and each pulls on one factor. None of them has a fixed saving: the right choice depends on your traffic and your provider, so measure with the meter you just built.

    Figure 5. Four levers on the cost of a task

    Four cost levers: trimming results and caching the prefix, a cheaper model for easy steps, and stopping earlyTrim tool results to Tokens per call; Cache the prefix to Price per token; Cheaper model to Price per token; Stop early to Calls per run; Tokens per call to Cost per task; Price per token to Cost per task; Calls per run to Cost per taskTrim tool results: send lessTrim toolresultssend lessCache the prefix: if documentedCache theprefixif documentedCheaper model: for easy stepsCheaper modelfor easy stepsStop early: caps, limitsStop earlycaps, limitsTokens per callTokens percallPrice per tokenPrice pertokenCalls per runCalls per runCost per task: product of threeCost per taskproduct of three

    How to read this: each green lever on the left pulls on one factor in the middle, and the three factors multiply into the cost per task on the right. Trimming and stopping early lower the quantity. Caching and a cheaper model lower the price of what is left.

    • Send less. Because the history is resent, a tool result that is twice as long is paid for on every later call. Truncate and summarise tool output before it goes into the conversation, and return only the fields the model needs.
    • Cache the shared prefix, where the provider documents it. Anthropic's prompt-caching page says the cache covers the full prefix (tools, system, then messages), that a cache read is priced as a fraction of the base input price (a multiplier that depends on the model, so read the page), that the default lifetime is five minutes, and that prompts shorter than a model-specific minimum cannot be cached. An agent loop resends an identical prefix on every step, which is exactly the shape caching is for. Check the provider's page for the model you use, because the rules differ by provider.
    • Use a cheaper model for easy steps. Routing a simple classification step to a smaller model and keeping the large model for the hard step lowers the price per token, at the cost of more moving parts and a quality check on the cheap step.
    • Stop early. A step limit, a cost cap and a "no progress" check (the same tool with the same arguments twice) bound the number of calls. Run 2 shows the cap doing its job.
    WARNING

    A loop with no step limit and no cost cap is an uncapped bill. A model that keeps asking for a failing tool will keep paying for it until something outside the loop stops it. Put a cap in code, and an alert on top of it, before the first real user.

    Production architecture around the loop

    The loop is small. The service around it is where most of the engineering goes. An agent run can take many seconds, uses an unreliable remote model, and can have side effects, so it fits the shape of any slow, expensive background job. Run it behind a queue, not inside a web request.

    Figure 6. An agent in production

    A production setup: API and rate limit in front, a job queue, workers that run the agent with retries and timeouts, an audit log and a kill switchClient to API (task); Rate limit to API; API to Job queue (enqueue); Job queue to Agent workers; Kill switch to Agent workers (stop); Agent workers to Model provider; Agent workers to Tools; Agent workers to Audit log; Agent workers to Result store (answer); Result store to Client (poll)Client: asks for a taskClientasks for a taskAPI: 202 and job idAPI202 and job idRate limit: per tenantRate limitper tenantJob queue: retry, dead letterJob queueretry, deadletterAgent workers: loop plus timeoutsAgent workersloop plustimeoutsKill switch: checked each stepKill switchchecked each stepModel provider: retry with backoffModel providerretry withbackoffTools: idempotency keysToolsidempotency keysAudit log: every tool callAudit logevery tool callResult store: poll or callbackResult storepoll or callbacktaskenqueuestopanswerpoll

    How to read this: the request goes in at the left and comes back out at the bottom. The API answers at once and the work travels along the dashed queue path, so no web request waits for a model. The red dashed arrow is the kill switch reaching the workers.

    Figure 7. One task as a message exchange

    sequenceDiagram accTitle: One agent task through an API, a queue and a worker accDescr: The client submits a task and receives a job id at once. A worker takes the job from the queue, runs the agent with retries on model errors, stores the answer, and the client later polls for it. participant C as Client participant A as API participant Q as Job queue participant W as Agent worker participant M as Model provider participant R as Result store C->>A: submit task with an idempotency key A->>Q: enqueue the job A-->>C: 202 and a job id Q->>W: deliver the job W->>M: model call M-->>W: error, rate limited W->>W: wait with backoff W->>M: model call again M-->>W: reply W->>R: store the answer C->>A: poll with the job id A->>R: look up the job A-->>C: the answer

    How to read this: the client never waits on the model. The one failure in the middle is a transient provider error, which the worker absorbs by waiting and retrying. The client sees only a job id and, later, an answer.

    Each box answers a specific problem.

    • API and queue. The API validates the request, checks the rate limit and returns a job id at once. The job waits in a queue, so a burst of tasks becomes a backlog instead of an outage, and workers scale independently. A job that keeps failing goes to a dead-letter queue for a human.
    • Timeouts at three levels. A timeout on each model call, one on each tool call, and one on the whole run. The step limit bounds steps, and the run timeout bounds wall-clock time, and you need both.
    • Retries with backoff. Transient provider errors such as rate limits are retried with exponential backoff and jitter, with a limit on attempts. Retries multiply load during an outage, so cap them and see the retry lessons linked below.
    • Idempotency. A retry must not do a side effect twice. Give a task an idempotency key at the API, and give tools that change things a key too, so a repeated roll_back is recognised as the same request.
    • Rate limits. Per tenant and per user, so that one customer's runaway agent does not use everyone's model quota.
    • Fallbacks. Decide in advance what happens when the model is down or the budget is gone: a smaller model, a cached answer, or a clear "a human will follow up" result. A graceful failure is a feature.
    • Audit log. Record every tool call that matters: who asked, which tool, which arguments, which result and the run id. For tools that change production this is not optional, and it must not hold secrets.
    • Kill switch. A flag the worker checks before each step, so you can stop one run, one tenant or all agents in seconds without a deploy.
    TIP

    Picture it: A restaurant kitchen has a ticket rail. Waiters never wait at the stove: they hang a ticket and return to the floor. Cooks take tickets in order, a manager can pull the plug on the fryer, and every order is written down. The queue is the rail and the kill switch is the plug. The analogy stops at ordering: a restaurant works tickets in order, while a job queue may retry and reorder them.

    TIP

    Picture it: When a phone line is busy, you do not redial every second. You wait, try again after a short pause, then a longer one, and give up after a few tries. That is retry with backoff. The jitter part is that you also vary the pause a little, so a thousand callers do not redial in the same instant. The analogy stops at the phone: a retried model call costs money each time.

    NOTE

    On call, 3 a.m.: Dalia Ferreira is the on-call engineer at Tidewater Parcels, an invented company. Latency alerts fire for the support agent, and the dashboard shows only that runs are slow. She opens one trace. The model calls are quick, but one tool span takes most of the run, because a downstream service is slow. She turns the tool's timeout down and sets a fallback message, and the queue drains. Without the span tree she would have blamed the model. Invented example.

    In practice: Parcelo

    Parcelo's on-call assistant runs as a worker behind a queue. The API accepts an alert id and returns a job id. The worker runs the agent from the earlier lessons with the decorators on, with a cost cap per run and a step limit, and writes every tool call to the audit log.

    Two of its dashboards matter most. Steps per run shows when the agent has started to loop or a prompt change made it chattier. Cost per resolved alert tells the business what the assistant costs. When the first rises before the second, the team has a warning, and the per-run trace shows which step changed. The tools that change production, restart_service and roll_back, are covered by the guardrails lesson, and the evals lesson shows how a regression gate keeps them from creeping in.

    Break it

    Three experiments, each run for real. Restore the file after each one.

    1. Make the cap smaller than one call. In Run 2 of Demo.java, switch the price to Price.LARGE and keep the cap at 100,000. The run stops before its first model call: BUDGET_EXCEEDED after 0 model calls, with spent_micro=0 and next_input_tokens_est=324. That first input alone would cost 324,000 micro-units on the invented large tier, so the guard refused it. A cap below the price of one call means the agent never starts. See that in a log line, not in a support ticket.

    2. Make the cap tight. Keep Price.SMALL and set the cap to 40,000. The first call is allowed (35,200 micro-units) and the guard stops the second: BUDGET_EXCEEDED after 1 model calls, with spent_micro=35200 and next_input_tokens_est=356. The cap is checked before each call against what the call is known to cost, so a stuck run costs at most one call more than the cap allows for.

    3. Unwrap the tools. In ObservedAgent.java, build the Agent with new Tools(tools) instead of new Tools(traced). The run still finishes with the same answer, but the span tree now has only the five model calls: no tool spans, no tool_calls counter, and the span ids shift. Three tests fail (theSpansFormATreeUnderTheRunSpan, countersCountCallsAndEveryKindOfToolError and aToolThatThrowsMarksItsSpanAsAnError). The counter tool_errors=1 is still correct, because it comes from the run's own trace and not from the decorator. That is the reason the lab counts errors there.

    Architect's notes

    • Instrument the loop from the first day. A run is a tree, and a final answer alone cannot tell you what it cost or why it was slow.
    • Treat token numbers from decorators as estimates and bill from the provider's usage report. Keep the estimate only for the pre-call guard.
    • Put a cost cap and a step limit in code, then an alert on top. A cap bounds one run; an alert catches a pattern.
    • Keep prompt text and tool output out of logs by default. Log sizes, ids and costs, and turn content on deliberately and redacted.
    • Keep metric labels low-cardinality. Put a tool name on a metric; put a prompt in a trace, if anywhere.
    • Run agents behind a queue with idempotent submissions. A web request is the wrong place to wait on a model.
    • Every automatic retry needs a limit, a backoff and an idempotency story for tools with side effects.

    Common mistakes

    • Logging the whole prompt "for debugging". It leaks personal and secret data into a log store. Log sizes and ids, and sample content only with redaction.
    • Alerting on the average only. A run that costs a hundred times the average hides in it. Watch the tail and the maximum per run too.
    • Trusting the estimate as the bill. A character count is not a tokenizer. Read usage from the provider's response.
    • A cap with no alert. Runs stop quietly and nobody asks why. Count budget stops and alert on a rise.
    • Retrying a tool that changes things. A repeated restart is two restarts. Use idempotency keys, or do not retry.
    • Waiting on the model inside a web request. Timeouts and bursts become user-facing errors. Queue the work.
    • Putting an unbounded value in a metric label. A prompt or a user id as a label grows the metrics store without limit. Use traces and logs for that.
    IMPORTANT

    Remember this:

    • Trace the trajectory: a run is a tree of model calls and tool calls.
    • The history is resent on every step, so input cost grows faster than the number of steps.
    • A budget check before each call stops a stuck run; an estimate is not a bill.
    • Log ids, sizes and costs, never prompt text by default.
    • Production means a queue, timeouts, backoff, idempotency, rate limits, an audit log and a kill switch.

    Key takeaways

    • Wrap the model and every tool in decorators and the unchanged loop produces spans, counters, cost and structured logs.
    • Count tool errors from the run's trace, because validation failures never reach a tool decorator.
    • Input tokens summed over a run grow faster than the number of steps, because the conversation is sent again on every call.
    • The four levers are sending less, caching the shared prefix, a cheaper model for easy steps and stopping early.
    • Spring AI instruments chat calls, tool calls and token usage through Micrometer, and keeps prompt logging off by default.
    • A production agent runs behind an API and a queue, with timeouts, retries with backoff, idempotency, rate limits, fallbacks, an audit log and a kill switch.

    Practice exercises

    Starter. In examples/backend/labs/agent-observability/src/main/java/buildingai/labs/observability/Demo.java, change the step counts in run3 from 3, 6 and 12 to 4, 8 and 16 and run the lab. Does the ratio for doubling change? Explain why in one sentence.

    Intermediate. Add a no_progress counter to ObservedAgent.java that increments when the model asks for the same tool with the same arguments twice in a row, and a test in ObservedAgentTest.java. Use ToolCall.describe() to compare calls.

    Advanced. Replace the character estimate with a provider-style usage report: add a Usage record (input, output) that a model wrapper can return, make TracedModel prefer it when present, and keep the estimate as the fallback for the budget guard. Write the test with a scripted usage report that disagrees with the estimate.

    Enroll to keep reading

    Lesson 13 of 15 · Agentic AI for Java Developers: Build and Ship Agents

    Trace every agent step, estimate tokens and cost, stop a run at a budget, and design the production setup around the loop, with a plain-Java lab.

    In the rest of this lesson

    • Why the cost of a run grows faster than its steps
    • Run it
    • Under the hood: what the provider reports
    • Where Spring AI and Micrometer fit
    • Cost levers
    • Production architecture around the loop

    Enrolling is free. It unlocks every lesson in Agentic AI for Java Developers: Build and Ship Agents, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments