Braj Kishore
JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
Say hi

Hiring · Building · Investing

Have a system — or a team —that needs to scale?

info@avyxon.ai

Usually replies within a day · track record here

JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
LinkedInXYouTubeSubstackInstagramThreadsFacebookDiscordGitHubTopmate
© 2026 Braj Kishore · Bengaluru, INThink Big · Start Small · Scale Fast
Agentic engineering
Lesson 17Working

Production

Almost none of this is about AI. It is ordinary distributed-systems engineering pointed at a new failure surface, which is the good news: you already know most of it. The trap is assuming the framework has done it for you.

An agent holds state across many tool calls and changes the outside world part-way through. So picture the ordinary case. It is three calls into a five-call run, it has already issued a refund, and the process dies. What should happen on restart?

That question is not new. It is what every payments system, order pipeline and provisioning workflow has dealt with for decades. What is new is that the thing driving the calls is non-deterministic. That removes the one assumption most retry logic quietly depends on: that a repeat of the same operation was requested for the same reason.

So the discipline is recovery rather than restart. Checkpoint after every successful tool call, including the ledger of which idempotency keys have been consumed.

Keep that ledger separate from the conversation transcript. On resume you need to restore commitments, not just context.

Interactive · the whole apparatus at once

Five controls, and the failure each one is for

Read down a column for one control, or across a row to compare them. The chip on each column is the argument of this lesson: only the counting is new. Select any column for the detail.

The failure it prevents
A resume that restores the transcript but not the commitments
A duplicate side effect when the crash lands between the call and the write
One pathological input spending your entire month’s budget overnight
An incident nobody can reconstruct, and a vendor you cannot leave
A cost regression that first appears on the invoice
What it costs to add
Checkpoint after every successful tool call, ledger included
About forty lines, with the key derived from intent
Caps on turns, wall-clock, spend and repeated identical calls
Run id, tool sequence and token counts as JSON on day one
Divide the bill by completed tasks once — ten minutes in a spreadsheet
What a team without it experiences
The five-call run begins again with the refund already issued
A second refund that nothing in your logs distinguishes from a real one
The loop repeats an identical tool call until something else stops it
You discover the lock-in at renewal
Cost escalates past the ROI case and nobody can name the number

Two of the five have no agent in them at all. The other three are ordinary mechanisms pointed at counters that are new.

The two-phase ledger, and the write order that matters

Two details decide whether a ledger works, and both look fine in testing. The first is where the key comes from. It must be a function of what the agent intended, so that a retry of the same intent produces the same key.

Generate a random UUID inside the retry path and you have built an elaborate no-op. The retry gets a fresh key, the ledger recognises nothing, and the tool runs again.Stripe’s guidance is compatible with this and worth reading precisely. The client generates the key. A V4 UUID is fine. The point is that it is generated once per logical request and reused on every attempt.

The second detail is the write order, and it is the one teams get wrong. Picture a ledger written after the tool call. The agent issues the refund. The process dies before the write. On restart the ledger is clean, so the retry issues a second refund — and nothing in your system knows it happened twice.

So reserve the key as in_flight and checkpoint it before the side effect. Crash there and the retry finds evidence rather than a clean slate: a reserved key, which tells it to go and ask the downstream system what happened instead of firing blind.

Writing the ledger after the call only protects against an in-process retry — the case where the process is still alive, which was never the case that was going to hurt you.

Interactive · failure injection

Kill the process. See what the customer gets.

One agent, one refund of ₹1,800, three places the worker can die and three ledger designs. Pick a combination. Only one design survives all three crash points, and it is not the one most codebases have.

Ledger design
Where the process dies
Money moved twiceDuplicate side effect

The window this design leaves open is precisely the interval that matters. The refund succeeded, the ledger write never landed, and the retry sees a clean ledger and refunds again. Writing the ledger after the side effect protects only against an in-process retry — the case where the process is still alive, which is the case that was never going to hurt you.

This design survives 2 of the 3 crash points. The lesson is a write-ordering one and it is worth being able to say out loud: reserve the key and checkpoint it before the side effect, so that a crash leaves behind evidence that something may have happened. And be honest about where the real guarantee lives — the local ledger is a cache. The idempotency key reaching the downstream system is the actual protection.

ledger.py
import hashlib, json


def key_for(tool, args):
    """Derived from INTENT, not from a UUID minted at call time.
    A retry of the same intent must produce the same key."""
    blob = json.dumps({"tool": tool, "args": args}, sort_keys=True)
    return hashlib.sha256(blob.encode()).hexdigest()[:32]


def call_tool(tool, args, ledger):
    k = key_for(tool, args)
    prior = ledger.get(k)

    if prior == "in_flight":
        # A previous attempt died between the call and the write.
        # Ask the downstream system what it knows about this key;
        # never re-fire blind.
        return reconcile(tool, k, ledger)
    if prior is not None:
        return prior                    # already executed: replay it

    ledger[k] = "in_flight"             # reserve BEFORE the side effect
    checkpoint(ledger)

    # The local ledger is a cache. The real guarantee is that
    # idempotency_key reaches the downstream system, which is the
    # only place that can refuse a duplicate authoritatively.
    result = TOOL_FNS[tool](**args, idempotency_key=k)

    ledger[k] = result
    checkpoint(ledger)
    return result
Forty lines that decide whether a crash costs you a support ticket or a duplicate payout. The comment on the reservation is the load-bearing line: crash there and the retry finds evidence, rather than a clean slate and a second refund.

Why a resumed node discards your approvals

This one costs an afternoon the first time. Here is the afternoon, for free.

In LangGraph, when a node containing an interrupt() is resumed, the runtime restarts the entire node from the beginning. It does not resume at the line after the interrupt. The documentation says so explicitly, and it is a reasonable design: the node is a plain function, so there is no continuation to capture.

So everything before the interrupt runs again. Validation re-runs. Records created before the interrupt are created a second time.

And if you put two interrupts in one node to collect two approvals, resuming after the second one re-runs the first. That is how a system with a human gate ends up discarding the approval it just collected.

Split the gate and the action into separate nodes. One node validates, raises the interrupt, and does nothing else. A second node, entered only on resume, performs the side effect. This is the same shape as the two-phase ledger and for the same reason: put a durable boundary between the decision and the irreversible thing.
Interrupts — LangGraphLangChain docsHow we built Claude Code auto modeAnthropic · Mar 2026

Circuit breakers, and the layer people forget

Nothing about the circuit breaker is AI. Closed, open, half-open, a trial call to decide whether to close again — Fowler wrote it up in 2014 and Nygard popularised it before that.

What is agent-specific is what you count. Cap total turns, wall-clock and spend. Then add the one people forget: repeated identical tool calls. That is the single most common agent failure mode and the cheapest to detect. Trip the breaker to a human, never to a silent failure.

Budget wants three layers rather than one. A per-response token ceiling the model cannot see. A task budget the model can see, so it paces itself and finishes gracefully instead of being cut off mid-sentence. And a hard currency cap enforced outside the agent entirely, because a budget the agent enforces on itself is a budget an agent can reason its way past.

Cost engineering — the order-of-magnitude swing

Two published multipliers anchor everything. An agent uses roughly 4× the tokens of a chat interaction. A multi-agent system uses roughly 15×.

The same source reports that on BrowseComp, token usage alone explained 80% of performance variance, with tool-call count and model choice taking it to 95%. Read that carefully, because it inverts the usual instinct. You are largely buying quality with tokens. So the question is not how to use fewer, but how cheaply to buy each one.

Interactive · cost per completed task

The order-of-magnitude swing on identical output

Priced from the published Claude Opus 5 rates — $5/MTok input, $0.50/MTok cache read, $25/MTok output, batch at half — over a 12,000-token / 1,200-token unit of work. The architecture multipliers are the published 4× and 15×; everything else is arithmetic you can redo.

Cost per completed task
$0.3600
Versus a single chat call
4.0×
At a million tasks a month that is $360,000. Finance can read that line. Tokens per month is not a line finance can read.

Drag the cache slider first. It is almost always the largest single lever, it changes no behaviour, and it is the one that quietly breaks — caching is a prefix match, so a timestamp early in a system prompt invalidates everything after it. If your bill jumps and nothing else changed, look for a new prefix invalidator before you look at the architecture.

The multi-agent premium is real, but it is not what kills a project — unengineered multi-agent is. Tiering models, caching aggressively and batching everything nobody is waiting for moves the same output by roughly an order of magnitude, and none of those three changes what the product does. Do them before you touch the architecture.

Message BatchesAnthropic APIPrompt cachingAnthropic API

Instrument with OTel, not a vendor SDK

Write vendor-specific trace calls throughout your agent and you have chosen that vendor permanently. You will discover that at renewal.

OpenTelemetry is the only portable option, and every serious platform ingests OTLP. It is not finished: the GenAI semantic conventions are still marked Development and have moved out of the main OpenTelemetry semconv repository into their own. So pin the schema URL you emit and expect churn.

The span tree to emit: an invoke_agent root per session, a chat span per model call, execute_tool spans named for the tool, plus retrieval and MCP spans.

Capture all five token attributes — input, output, cache read, cache write and reasoning. Reasoning tokens bill as output. Omit them and your cost model is not approximate, it is wrong.

And keep a stable session id, so that a bad outcome pivots to the full trajectory. Every incident investigation starts by pulling the transcript.

One team that treated latency as an architecture decision

The most useful production case in this space is not about model quality. It is about a team reading its own tail latency and concluding that the buy option could not meet the SLO.

🇸🇬 Southeast Asia

Grab — P99 is the number that decided build versus buy

3–4×
P99 over P50 on external APIs
+70 pp
Thai document accuracy
+40 pp
Vietnamese

Grab built its own vision LLM for identity-document processing rather than calling an external API, and the stated reason is tail latency: P99 on external APIs “can easily be 3 to 4× the P50”, which would not survive a large-scale rollout. The training story carries a second finding worth having. LoRA fine-tuning failed on non-Latin scripts and dense unstructured layouts. The fix was full-parameter fine-tuning plus continual pre-training on synthetic OCR data rendered from Common Crawl text. Thai accuracy moved roughly 70 percentage points, Vietnamese 40, while a LoRA-tuned model had already been accurate on Indonesian documents from the start.

Two engineering lessons, and the second is the one people miss. First: the buy-versus-build decision was made on the tail, not the mean. A P50 that meets your SLO and a P99 that does not is a system that fails for one user in a hundred and looks healthy on every dashboard you own. Second: the failure axis was the writing system, not the language. LoRA was, in Grab’s words, “promising for documents with Latin scripts” and reached high field-level accuracy on Indonesian, while struggling with Thai and Vietnamese. Worth noting that the article groups Vietnamese under “non-Latin scripts” when it is in fact Latin with dense diacritics — which suggests the real boundary is what the vision encoder has actually seen rendered, not the alphabet on paper. Either way, that is the axis your evaluation set has to be stratified on, and no amount of per-language accuracy reporting will surface it.

How we built a custom vision LLM at GrabGrab Engineering

What to build, at your size

Four of these five are cheap enough that skipping them is hard to defend even at four people. One is a real problem that a seed team genuinely does not have, and saying so out loud is a better signal than having built it.

Interactive · calibrate to your stage

What to actually do about this, at your size

Nearly all guidance on this topic is written for one company size and then read by everyone. Pick yours — the list re-sorts, and what you should deliberately not build drops to the bottom.

  • Idempotency ledgerNon-negotiable

    A key derived from the agent's intent, reserved before the side effect and checkpointed, so a crash leaves evidence rather than ambiguity.

    At this stage · Now with reconciliation for the in_flight case, because at this volume the mid-call crash stops being theoretical and starts being weekly.

  • Circuit breakers and budget layersNon-negotiable

    Caps on turns, wall-clock, spend and repeated identical calls — three layers of budget, tripping to a human rather than to a silent failure.

    At this stage · Add the per-tenant cap so one customer's bad input cannot exhaust a shared budget, and alert on cap trips — a rising trip rate is the earliest signal a tool has quietly broken.

  • OpenTelemetry tracingDo it

    An invoke_agent root span, a chat span per model call, execute_tool spans, and all five token attributes including cache and reasoning tokens.

    At this stage · Now real OTel, because you have more than one person debugging and the first incident where nobody can reconstruct the trajectory costs more than the setup did.

  • Cost per completed task on a dashboardDo it

    Not tokens per month. Dollars per finished piece of work, split by cache hit rate, so a cost regression is visible before the invoice.

    At this stage · On a dashboard now, because cost is about to become a board question and 'tokens per month' is not a sentence a CFO can act on.

  • Rainbow deploysCheap version

    Shift traffic gradually between versions so in-flight trajectories finish on the version they started on.

    At this stage · Drain rather than kill: stop routing new runs to the old version and give in-flight ones a grace period. That covers most of the value for a fraction of the machinery.

Nothing is optional at this stage. That is itself the finding — the cost of the control set is part of the cost of operating here.

What actually kills agent projects

Not model capability. Cost escalating past the ROI case. No evaluation infrastructure, so nobody can tell whether a change helped. Risk controls inadequate for sign-off. Unclear ownership. No graceful escalation path to a human.

Gartner predicts more than 40% of agentic AI projects will be cancelled by the end of 2027 for essentially that list. Treat the percentage as an analyst forecast rather than a measurement, and the reasons as the useful part. Every one of them is an engineering-management failure, not an AI failure.

Four things belong on the operating review, and none of them are novel. Cost per completed task on the dashboard, because finance can read that line. A named owner and an on-call rota, since “who owns this when it breaks at 2am” is a question every serious interviewer asks. And a kill switch that has been tested, because an untested kill switch is decoration.

The fourth is the one that gets left off: fallback rate as an SLI. Not “is the service up” but “what fraction of responses came from the real path”. A system quietly degraded for six hours with green dashboards is worse than an outage.

What to remember

  1. 1
    Reserve, checkpoint, then execute

    Derive the idempotency key from intent, and write it before the side effect. A ledger written afterwards protects only against an in-process retry — the case that was never going to hurt you.

  2. 2
    A resumed node re-runs from the top

    LangGraph restarts the whole node on resume. So validation re-runs, and an approval collected before an earlier interrupt is silently discarded. Split the gate and the action into separate nodes.

  3. 3
    Cache hit rate is the biggest lever

    Cache reads bill at a tenth of input, batch at half, and neither changes what the product does. Do them before you touch the architecture, and watch cache_read_input_tokens rather than the invoice.

  4. 4
    None of this is about AI

    Durable execution, idempotency, circuit breakers, tail latency, tracing, blast radius. The agent-specific part is only ever what you count — turns, spend, and repeated identical calls.

Sources

Every source in this lesson

Primary sources wherever one exists. Where a claim is contested or vendor-reported, the lesson says so at the point it is made.

Read
  • How we built our multi-agent research systemAnthropic · Jun 2025

    Where the 4× and 15× token multipliers come from, and the BrowseComp finding that token usage alone explains 80% of performance variance (95% with tool-call count and model choice). Also the case for resuming rather than restarting long agents.

  • Circuit BreakerMartin Fowler · 2014

    Closed, open, half-open, and a trial call to decide whether to close again. Popularised by Michael Nygard in Release It. Nothing about it is new and nothing about it is AI — which is the point of this lesson.

  • How we built a custom vision LLM at GrabGrab Engineering

    The P99-is-3-to-4×-P50 argument for owning the model, and the finding that LoRA failed on non-Latin scripts while full-parameter fine-tuning plus synthetic OCR pre-training moved Thai +70pp and Vietnamese +40pp.

  • How we built Claude Code auto modeAnthropic · Mar 2026

    Cited here for its internal incident log — deleted remote branches, an auth token uploaded to a compute cluster, migrations attempted against a production database. Each one is a durability and blast-radius problem, not a model-quality problem.

  • Over 40% of agentic AI projects will be canceled by end of 2027Gartner · Jun 2025

    An analyst prediction, not a measurement — treat it as such. The reasons given are the useful part: escalating costs, unclear business value, inadequate risk controls. All three are engineering-management failures.

Docs
  • Understanding Temporal — durable executionTemporal docs

    The definition worth borrowing: durable execution guarantees an application runs to completion despite adverse conditions, by replaying a complete Event History to reconstruct state after a worker crash.

  • Idempotent requestsStripe API

    The reference implementation. Stripe saves the status code and body of the first request per key and replays it — including 500s. Keys are client-generated, kept at least 24 hours, and a reused key with different parameters errors rather than silently proceeding.

  • Interrupts — LangGraphLangChain docs

    States it plainly: on resume “the runtime restarts the entire node from the beginning — it does not resume from the exact line where interrupt was called”, so any side effect before the interrupt re-runs. The fix in the docs is to move side effects after the interrupt, or into their own node.

  • OpenTelemetry GenAI semantic conventionsopen-telemetry/semantic-conventions-genai

    Moved out of the main semconv repo and still marked Development. Operation names include chat, embeddings, execute_tool, invoke_agent and create_agent; token attributes include input_tokens, output_tokens, cache_read, cache_write and reasoning.

  • Message BatchesAnthropic API

    Asynchronous processing at 50% of standard cost, most batches finishing inside an hour. It applies to every workload where nobody is waiting on the response — which is more of an agent estate than teams assume.

  • Prompt cachingAnthropic API

    On Claude Opus 5 the documented rates are $5/MTok input, $0.50/MTok cache read (0.1×) and $6.25/MTok for a five-minute cache write (1.25×). Caching is a prefix match, so one timestamp early in a system prompt silently invalidates everything after it. Watch cache_read_input_tokens, not the bill.

Lesson 16
Why agents fail
Lesson 18
Observability and tracing