v1.0

v1.0

/

/

AI agent state management: persistent memory, safe retries and crash recovery in production

AI agent state management: persistent memory, safe retries and crash recovery in production

AI agent state management: persistent memory, safe retries and crash recovery in production

Persisting chat history is not enough to recover an AI agent safely. Production systems must separate memory, workflow state, execution history and real-world side effects so a crash does not cause amnesia—or duplicate actions on replay.

Aucun heading trouvé dans #cible

Anis Meziani

AI agent memory and AI agent state are not the same thing and confusing them can make recovery dangerous.

A conversation can survive a restart while the workflow still has no safe way to continue. A run can have perfect traces while the system has forgotten the input needed to reproduce it. And a failed agent can “recover” by repeating an email, database write or API action that already happened before the crash.

This guide separates four concepts that production systems need to model independently: conversation memory, workflow state, execution history and real-world side effects. It is based on failures we encountered while operating ApowerB, but it is written as a general production architecture rather than a duplicate of our original DEV.to incident report, “Amnesia and déjà vu”.

What is AI agent state management?

AI agent state management is the practice of persisting the information required to understand, continue, replay or safely terminate an agent run independently of the process currently executing it.

That state may include run ID, original input, current status, session reference, completed transitions, tool calls, approvals, external identifiers, idempotency keys, error information and retry metadata.

Memory vs state vs execution history vs business state


Concept

Question it answers

Example

Conversation memory

What has the user and agent discussed?

Messages and model events

Long-term memory

What should the agent remember across sessions?

User preference or learned fact

Workflow state

Where is this run in its lifecycle?

Running, waiting for approval, failed

Execution history

What did the runtime actually attempt?

Tool calls, outputs, timestamps

Business state

What is now true in the external system?

Email sent, invoice paid, CRM updated

A chat transcript can help reconstruct intent. It is not a reliable ledger of external side effects.

Failure mode 1: amnesia after a process restart

In development, an in-memory session service is convenient. In production, the process is disposable.

During one internal ApowerB deployment audit, we observed roughly eight application restarts per day through ordinary deploys and cluster activity. When sessions lived in process memory, every restart could erase conversational context.

The fix is conceptually straightforward: move state that must survive the process into durable external storage.

In our case, short-term sessions were moved to Postgres, long-term memory to the application database with user/agent scoping, and artifacts to durable object storage with an appropriate fallback path.

Persisting memory does not make the run resumable

A database-backed conversation means the next worker can reconstruct what was said. It does not necessarily know which runtime step had completed, which tool call had crossed the network, whether an external system committed a write, or whether it is safe to perform the action again.

You therefore need a run record separate from conversation memory.

Failure mode 2: the run disappears but the side effect survives

Consider a customer-service agent:

  1. read the request;

  2. draft a response;

  3. send the email;

  4. update the CRM.

If the process dies after the email is sent but before the CRM update completes, blindly restarting from the beginning may send the email twice.

This is the production version of “déjà vu”: the software has lost confidence about where the run stopped, while the outside world remembers what already happened.

Why “resume from step 3” is harder for LLM agents

Traditional deterministic workflows often have stable program counters. Agentic execution may not.

A model can choose a different path after replay because context, provider behavior, model version or intermediate outputs differ. “Step 3” is not always a stable coordinate in a probabilistic plan.

Checkpointing should therefore be defined around validated state transitions and external effects, not simply around numbered model turns.

The safe-replay decision

Before replaying a failed run, ask three questions:

  1. Do we have the original input?

  2. Do we know which side-effecting tools were invoked?

  3. Can we prove that repeating them is harmless or deduplicated?

If the answer to the third question is “unknown,” automatic replay should usually stop.


Decision tree for safely replaying a failed AI agent run after checking input, tool calls and side effects.

Tool classification: reads, reversible writes and irreversible writes

Class

Example

Default replay policy

Read-only

Fetch customer record

Usually safe, subject to freshness and cost

Idempotent write

PUT desired configuration with stable key

Safe when idempotency is guaranteed

Deduplicated event

Process provider event ID once

Safe when dedupe key is authoritative

Reversible write

Create draft record

May retry with compensating action

Irreversible / high-impact

Send email, issue refund, publish externally

Require idempotency proof or human decision

Unknown outcome

Timed-out request after dispatch

Read external state before retry

Idempotency keys need stable intent

Hashing generated tool arguments is not always enough. On replay, the model may phrase or structure equivalent arguments differently.

Where possible, derive idempotency from stable business identity: provider message ID, business operation ID, order/payment identifier, content checksum or an explicit request ID generated before reasoning begins.

The idempotency key should describe the business action, not the exact text the model happened to generate.

Unknown outcomes are the dangerous middle state

A network timeout does not tell you whether the remote service committed the action.

The safe pattern is:

  1. send a stable operation ID where the API supports it;

  2. persist that ID before dispatch;

  3. if the response is ambiguous, query the system of record;

  4. retry only when external state confirms the operation did not complete.

Checkpoints should follow committed transitions

A useful checkpoint says more than “the model finished a turn.” It captures a validated transition:

{
  "run_id": "run_123",
  "status": "waiting_for_approval",
  "completed_actions": ["lookup_customer"],
  "pending_action": "send_email",
  "external_refs": {"customer_id": "C-481"},
  "version": 7
}
{
  "run_id": "run_123",
  "status": "waiting_for_approval",
  "completed_actions": ["lookup_customer"],
  "pending_action": "send_email",
  "external_refs": {"customer_id": "C-481"},
  "version": 7
}

The exact schema varies by runtime. The principle is stable: checkpoints should be small enough to reason about and authoritative enough to resume from.

Concurrency and state versioning

Durability alone does not prevent two workers from updating the same run.

Use optimistic versioning, row locks, leases or queue ownership so only one executor can advance a run transition at a time. Otherwise two “recovery” workers can create the duplicate side effect you were trying to prevent.

Memory retention becomes a data-governance problem

Once memory moves from RAM to durable storage, it becomes retained user data.

  • define tenant and user isolation;

  • set retention periods;

  • define deletion behavior;

  • encrypt sensitive state;

  • audit access;

  • control what enters long-term memory;

  • allow correction where required.

In our production work, we also had to bound database growth because session/event histories can expand indefinitely if retention is never designed.

Observability is not state management

Traces tell you what happened. State management lets the system continue correctly afterward.

You can have excellent traces and still be unable to retry because the original run input was never stored. Conversely, you can persist run input but have no explanation for why the run failed.

Production agents need both. See AI observability.

A practical run-state schema

  • run: id, owner, input, status, timestamps, parent/workflow reference;

  • tool invocation: tool, business key, arguments, status, external reference;

  • transition: from state, to state, reason, version;

  • approval: requested action, approver, decision, time;

  • error: class, retryability, raw trace reference;

  • checkpoint: recoverable state snapshot/version.

How ApowerB approached the problem

The ApowerB production work that inspired this article followed a conservative rule: persist sessions and run inputs, record tool activity, and avoid automatic replay when a previous tool call makes the outcome uncertain.

That rule intentionally refuses some replays that might have been harmless. It trades convenience for safety until tool-level idempotency semantics are strong enough to make a better decision.

The original incident narrative includes the code-oriented details and discussion that led to further hardening: read the DEV.to field note.


Inspect how the runtime persists and recovers agent work

ApowerB is open source, so its session, run and tool-execution paths can be reviewed directly.


State management checklist

Question

Required before automatic recovery?

Is the original run input durable?

Yes

Can the runtime identify the run owner/tenant?

Yes

Are tool calls recorded server-side?

Yes

Can side-effecting tools be distinguished from reads?

Yes

Do high-impact writes support idempotency or verification?

Yes for auto-replay

Can the system detect unknown outcomes?

Yes

Can only one worker advance a transition?

Yes

Is human escalation available?

Yes

Are memory retention and isolation defined?

Yes

How this fits into the broader production architecture

State management is one layer of a production agent runtime. It depends on infrastructure that can persist data and a deployment model that expects processes to disappear.

For the full stack, read Production-ready AI agents: architecture, runtime, orchestration and deployment. If you operate the runtime on Kubernetes, see How to deploy AI agents on Kubernetes.


AI agent state architecture separating conversation memory, workflow state, execution history and external business state.

The practical takeaway

The safest recovery question is not always “where did the agent stop?”

What do we know has already happened, and what can we prove is safe to do again?

That shift changes state management from a convenience feature into a production control. It also explains why durable memory alone is not enough: memory preserves context; safe recovery preserves consequences.

Frequently asked questions

What is AI agent state management?

AI agent state management is the durable storage and coordination of run information needed to understand, continue, replay or safely terminate an agent execution independently of the process running it.

What is the difference between agent memory and agent state?

Memory stores context or knowledge the agent may reuse. State tracks the lifecycle and progress of a specific execution, including completed transitions, tool calls and pending actions.

Can an AI agent simply resume from its last LLM step?

Not always. Agent paths can be probabilistic and external side effects may already have occurred, so recovery should be tied to validated transitions and real-world effects.

How do you prevent duplicate tool actions after a retry?

Use stable idempotency keys, execution journals, tool-side deduplication, external-state verification and human approval when the outcome of a previous write is uncertain.

Where should AI agent state be stored?

State that must survive process failure should live in durable external storage such as a relational database, durable workflow store or another managed persistence layer appropriate to the workload.

An open-source foundation for building your own agents.

ApowerB is the open-source agentic framework developed by thaink² to build, orchestrate, and operate AI agents on your own stack, using your models, tools, and data.

What if your next analysis were ready before your next meeting?

Show us your environment and a use case. See how thaink² can query, monitor, and act on your data.

Our mission
Our vision

Move from data you look at to data that works continuously for your business.

We believe the next generation of Data platforms will do more than show what happened. They will monitor, explain, anticipate, and prepare decisions before some questions even need to be asked.

Image

What is an Agentic Data Platform?

An Agentic Data Platform uses specialized AI agents to work with enterprise data. Unlike a static dashboard or a simple chatbot, agents can explore multiple sources, run analyses, generate visualizations, produce deliverables, and execute recurring missions.

What’s the difference between Proactive Mode and Exploratory Mode?

In Exploratory Mode, the user asks a question and thaink² runs the analysis on demand. In Proactive Mode, a mission is defined in advance: agents monitor the data based on a set schedule or specific conditions and automatically deliver the relevant results.

Do I need to know SQL to use thaink²?

Not for business use cases. Users can ask questions in natural language and get analyses, tables, charts, and dashboards without writing SQL queries themselves.

What data sources can thaink² connect to?

The platform is designed to work with the systems already in place across your organization: databases, data warehouses, ERP, CRM, APIs, files, and document repositories. Available connectors depend on your environment and use case.

What types of outputs can the agents produce?

Depending on the agent and use case, outputs can include analyses, tables, charts, dashboards, forecasts, alerts, summaries, and reports. The goal is to deliver an actionable result, not just a text response.

Can thaink² be deployed on our own infrastructure?

thaink² supports deployment options designed around enterprise requirements, including organizations that need greater control over their infrastructure, models, and data. Our teams help define the architecture that best fits the project.

Which part of the thaink² ecosystem is open source?

ApowerB is the open-source agentic framework developed by thaink². It enables technical teams to build and operate their own agents, with support for RAG, Text-to-SQL, multi-LLM setups, and APIs.

How do I get started with thaink²?

The easiest way to start is with a concrete use case: reporting, analysis, forecasting, document search, or monitoring. An initial session helps define the available data, expected outcomes, and the most suitable deployment approach.

Join our Discord community

Connect with builders, Data teams, and AI practitioners. Share ideas, get technical help, discuss agentic architectures, and follow the latest developments around ApowerB.

Our newsletter (Soon)

Data that takes action, straight to your inbox.

Field insights, agentic architectures, benchmarks, use cases, and the latest from ApowerB. Only what’s worth reading.

© 2026 thaink² SAS — All rights reserved

An open-source foundation for building your own agents.

ApowerB is the open-source agentic framework developed by thaink² to build, orchestrate, and operate AI agents on your own stack, using your models, tools, and data.

What if your next analysis were ready before your next meeting?

Show us your environment and a use case. See how thaink² can query, monitor, and act on your data.

Our mission
Our vision

Put the power of data in the hands of decision-makers.

Today, too many business questions still depend on an export, a dashboard, or the availability of a Data team. thaink² changes that by letting teams query their data directly, while agents handle the analysis and recurring work.

Image

What is an Agentic Data Platform?

An Agentic Data Platform uses specialized AI agents to work with enterprise data. Unlike a static dashboard or a simple chatbot, agents can explore multiple sources, run analyses, generate visualizations, produce deliverables, and execute recurring missions.

What’s the difference between Proactive Mode and Exploratory Mode?

In Exploratory Mode, the user asks a question and thaink² runs the analysis on demand. In Proactive Mode, a mission is defined in advance: agents monitor the data based on a set schedule or specific conditions and automatically deliver the relevant results.

Do I need to know SQL to use thaink²?

Not for business use cases. Users can ask questions in natural language and get analyses, tables, charts, and dashboards without writing SQL queries themselves.

What data sources can thaink² connect to?

The platform is designed to work with the systems already in place across your organization: databases, data warehouses, ERP, CRM, APIs, files, and document repositories. Available connectors depend on your environment and use case.

What types of outputs can the agents produce?

Depending on the agent and use case, outputs can include analyses, tables, charts, dashboards, forecasts, alerts, summaries, and reports. The goal is to deliver an actionable result, not just a text response.

Can thaink² be deployed on our own infrastructure?

thaink² supports deployment options designed around enterprise requirements, including organizations that need greater control over their infrastructure, models, and data. Our teams help define the architecture that best fits the project.

Which part of the thaink² ecosystem is open source?

ApowerB is the open-source agentic framework developed by thaink². It enables technical teams to build and operate their own agents, with support for RAG, Text-to-SQL, multi-LLM setups, and APIs.

How do I get started with thaink²?

The easiest way to start is with a concrete use case: reporting, analysis, forecasting, document search, or monitoring. An initial session helps define the available data, expected outcomes, and the most suitable deployment approach.

Join our Discord community

Connect with builders, Data teams, and AI practitioners. Share ideas, get technical help, discuss agentic architectures, and follow the latest developments around aPowerB.

Our newsletter (Soon)

Data that takes action, straight to your inbox.

Field insights, agentic architectures, benchmarks, use cases, and the latest from ApowerB. Only what’s worth reading.

© 2026 thaink² SAS — All rights reserved