Why Every AI Agent Is Still a `while(true)` Loop
Most AI agents still use while(true) loops. Learn why this costs money, what breaks in production, and the architecture that fixes it.
Open the source code of almost any AI agent shipping today and you will find the same skeleton: a while (true) loop that calls a language model, runs a tool, updates some in-memory object, and goes around again. It is the "hello world" of agent building, and it works fine in a demo. The problem starts the moment that agent has to run for days, survive a crash, pause for a human, or explain what it did three hours ago.
This post is about why that loop keeps showing up, what it quietly costs a business, and the architecture — event sourcing — that a growing number of engineering teams are reaching for instead. We build products for a living, so we will keep this in the language that actually matters: timelines, risk, and money.
The loop is easy to write and expensive to own
The while (true) pattern is popular for the same reason a single-file script is popular. It is fast to write, easy to read, and demos beautifully. The trouble is that it treats interruption as an exception — the thing that goes wrong — when for a real agent, interruption is the normal state of affairs.
As the DEV Community guide Building Persistent AI Agents puts it bluntly: "In traditional software, interruption is an exception case. In persistent agents, interruption is the normal case." An agent doing real work pauses for human approval, hits a rate limit, waits on an external system, or gets bumped by a higher-priority task. A plain loop has nowhere to put any of that. When it dies, it dies mid-thought, and there is no clean way to pick up where it left off.
The same guide names four capabilities that separate a toy from a production agent: it maintains state across sessions, it can pause and resume without losing its place, it can start actions on its own, and it recovers from failures without a human babysitting it. Its sharpest line reframes the whole job: "Think less 'chat interface' and more 'background worker with reasoning capabilities'." That single shift — from chat to background worker — is what breaks the while (true) model.
Put simply: the loop is cheap to build and expensive to operate. The cost shows up later, in the on-call rotation, not in the sprint where it was written.
Where the bugs actually live
Most agents keep a working-memory object and mutate it in place: agent.state['approved'] = True. It feels natural. It is also, according to the analysis in Agent State as Event Stream, a trap. The article calls it the "mutable state trap," and its diagnosis is worth quoting: "The gaps between those states are where the bugs live."
Think of it like a whiteboard. You write a number, erase it, write a new one, erase again. At the end you have the final answer — but no record of how you got there, which value was wrong, or when it changed. If a customer disputes a decision, or an auditor asks why the agent approved a refund, the whiteboard is already wiped.
Event sourcing flips this. Instead of overwriting the whiteboard, the agent emits an event and never erases anything:
{ "type": "ApprovalDecisionMade", "decision": "approved",
"rationale": "...", "input_context_hash": "..." }
The current state is no longer the source of truth. The log of events is, and the state becomes what that article calls a "projection" — "disposable and reconstructible on demand." You can always rebuild "what the agent believes right now" by replaying the events. You can never lose the trail of how it got there.
This is the one architecture note we will show as code, because it is the whole business case in three lines: an append-only fact instead of an erasable variable.
Event sourcing, in plain terms
Event sourcing is not new — banks have kept ledgers this way for centuries. Your bank account balance is a projection; the list of transactions is the truth. The academic write-up ESAA: Event Sourcing for Autonomous Agents applies exactly this idea to agents, defining it as "recording every state change as an immutable event in an append-only log," paired with CQRS, which "separates write and read models to optimize consistency and queries."
The ESAA paper is direct about why the loop falls short for serious work. It lists three auditability gaps in typical frameworks: state is stored as mutable snapshots rather than a change log; there is no native way to deterministically replay the full decision trail; and "the blast radius of a compromised agent is not formally bounded by contracts." Its proposed fix changes the agent's job description entirely — "the agent does not 'write state'; it emits intentions and proposed diffs that are validated and applied by a deterministic orchestrator." The agent proposes; a deterministic layer disposes. That separation is what makes the whole thing auditable and safe.
The stakes get concrete in what the paper calls "brownfield scenarios" — an agent working across a large, interdependent codebase. There, state drift becomes dangerous: "the agent may believe it has fixed a bug while the actual system remains unchanged, or it may rewrite specifications to bypass local compilation failures." An agent confidently reporting success on work it never did is not a hypothetical; it is the failure mode a mutable loop makes hard to detect. This is the same reliability gap we wrote about in why your AWS DevOps agent is only as good as its log — the log is not a nice-to-have, it is the agent's grip on reality.
The payoff: time-travel debugging without burning credits
Here is where the architecture stops being academic and starts saving money.
When every event is recorded, you get what the event-sourcing community calls "perfect recall." As the talk Event Sourcing: The Backbone of Agentic AI describes it, because every change is an immutable event, "we can reliably reproduce the state of any agent at any given point." The same talk makes a point we see confirmed constantly: agentic systems are really distributed systems, since "communication with LLMs is event-based and streaming," and those systems already "separate the read and write models, which is a perfect match for event sourcing."
Real numbers: the operational win is measured in API credits and engineer hours. Teams described in Agent State as Event Stream deploy "stream recorders" that persist every event to a .jsonl file. When something breaks at 3 AM, an on-call engineer can "replay a failed session without re-triggering the failure, without burning API credits, and without disturbing any external system." Compare that to debugging a while (true) agent: you re-run it, pay for every token again, hope the non-deterministic model reproduces the bug, and risk firing off a real email or a real database write in the process. One approach is a controlled replay; the other is a live grenade.
Forking gets cheap too. The Developers Digest piece The Log Is the Agent describes a real implementation from Lightspeed that stores every context-affecting event in the log, making branching trivial — you "just set a pointer to another sequence number." Want to explore two different next steps from the same conversation state? Point two agents at the same event and let them diverge. No copying, no snapshot juggling.
The honest trade-offs
We do not sell architecture as a silver bullet. Event sourcing has real costs, and the sources are honest about them.
Cost of replay. The Developers Digest article surfaces the obvious objection directly: "wouldn't feeding that log for each request/response iteration get expensive really fast?" LLM calls cost money, and naively replaying a conversation means paying for those tokens again. The common workaround — storing model responses in the log so you do not regenerate them — is characterized honestly as "replay-as-recording, not true deterministic replay." That distinction matters: you are replaying a recording, not re-deriving the answer, and the two are not the same when the model is non-deterministic.
Agents cannot read raw logs. An LLM has a context window, not infinite memory. As Agent State as Event Stream acknowledges, agents cannot operate on a raw event log directly. The bridge is the projection layer that folds the event stream back into compact working state the model can actually consume. That projection is extra code you have to build and maintain.
Multi-agent systems raise the stakes. Once several agents share a workflow, corruption gets more dangerous, not less. Galileo's guide on multi-agent data corruption warns that agents can produce "silent corruption where agents receive valid-looking but meaningless data, spreading incorrect conclusions throughout the system," and that heterogeneous agents create vulnerability at every interface because "each component uses different validation rules." An immutable log helps you detect and trace this — but it does not prevent it. You still need schema validation at the boundaries.
Honest take: for a weekend prototype or a single-turn assistant, the while (true) loop is the correct choice. The overhead of event sourcing is not worth it until your agent runs long enough to crash, touches systems where a wrong action has consequences, or has to answer "why did you do that?" The mistake is not using the loop early — it is keeping it once the agent graduates to real work.
Where the loop hurts most: long-running and voice agents
Two categories expose the loop's weakness fastest.
The first is anything long-horizon. The ESAA paper frames the shift precisely: LLM-based work is "shifting from conversational interactions to agentic workflows that require long-horizon consistency — that is, maintaining coherence between goals, contracts, and effects over dozens of cycles and artifacts." A loop that holds everything in volatile memory cannot maintain coherence over dozens of cycles; one bad restart and the goal is gone.
The second, surprisingly, is voice. Voice agents live or die on interruption handling. The Famulor guide to turn detection calls barge-in "perhaps the most important feature for a conversation," and names the worst mistake plainly: when a user tries to speak and the agent keeps talking, it "almost always leads to an immediate call termination." That is a lost lead and lost revenue. Hamming AI's interruption-handling runbook frames the tuning as a genuine trade-off — "lower thresholds make the agent feel responsive, but they create false interruptions; higher thresholds reduce false positives, but callers feel trapped" — and insists you treat it "as a runbook, not a toggle," recording caller input, agent speech state, the interruption decision, and the recovery outcome for every call.
Notice what that requires: an event trail. Hamming's own quality bar is a filter — if you cannot answer "did the caller intentionally interrupt, or did we fire on noise?" from a single call record, your handling "is not observable enough yet." You cannot meet that bar with a mutable loop that erases its own history. You need the log.
Key takeaways for business
Key takeaway for business: the while (true) loop is a prototyping tool, not a production architecture. It is the right first step and the wrong final one. Budget for the rewrite before the on-call pages start, not after.
Three things worth acting on:
- Ask where your agent's decisions go. If the answer is "into a variable that gets overwritten," you have no audit trail and no cheap replay. For anything touching money, customer data, or production systems, that is a liability, not a detail.
- Buy observability, not just autonomy. The teams sleeping through the night are the ones who can replay a failure without re-running it. As the persistent-agents guide stresses, human-in-the-loop oversight for real work is "regulatory, ethical, and practical table stakes" — and human oversight is only possible if the agent can pause, resume, and explain itself.
- Match the architecture to the lifespan. Short-lived, low-stakes agent? Keep the loop. Long-running, high-stakes, or auditable? The event log becomes the agent, and the code you thought was the agent becomes a disposable projection of it.
Here is what we recommend: if you are past the prototype stage, stop treating state as a thing you store and start treating it as a thing you derive from a log of what actually happened. The same discipline pays off well beyond agents — it is why we lean on rich event trails in hybrid code review and in reading the feedback users never type. A recorded history is not overhead. It is the product's memory, and memory is what turns a clever demo into something you can actually run at 3 AM.
Frequently Asked Questions
How do you manage state in agents that run for days without forcing a reset?
Store state as an append-only event log rather than a mutable object, and derive current state as a "projection" reconstructed on demand. This lets the agent pause and resume across sessions without losing its place — the four capabilities the persistent-agents guide names as the line between a toy and a production agent.
Why an immutable event log instead of a mutable state bag?
Because "the gaps between those states are where the bugs live." A mutable bag gets overwritten, erasing the decision trail; an immutable log keeps every step, enabling deterministic replay and trivial forking (Lightspeed forks a conversation by pointing to a different sequence number). For multi-agent work, the log is also your best tool for tracing silent data corruption across agent interfaces.
Doesn't replaying the log get expensive with paid LLM calls?
It can. The common mitigation is storing model responses in the log so you do not regenerate them on replay — though as Developers Digest notes, that is "replay-as-recording, not true deterministic replay." The savings are real: on-call engineers replay failed sessions without re-triggering the failure or burning fresh API credits.
How should tool use balance integration against unintended side effects?
Separate the proposal from the execution. In the ESAA model the agent "emits intentions and proposed diffs that are validated and applied by a deterministic orchestrator" — so the model never directly mutates production. Add schema validation at every agent-to-agent and agent-to-tool boundary, since heterogeneous components with different validation rules are where corruption slips in.
Can branching and task forking be first-class instead of an afterthought?
Yes, and event sourcing is what makes it cheap. When all context-affecting events live in an append-only log, forking a conversation is just setting a pointer to an earlier sequence number — no snapshot copying, no state juggling. Two agents can diverge from the same historical state and explore different paths in parallel.
This article is based on publicly available sources and may contain inaccuracies.


