Stateful vs. Stateless AI Architecture
Where should conversation history, tool results and workflow progress live? A practical comparison of stateless, stateful and external-state designs for AI applications — with the trade-offs and a working pattern.
Every AI application has to answer one question early, often without noticing: where does the state live? A chatbot must remember the conversation. An agent must remember which steps it has completed. A document assistant must remember which files a user uploaded. The answer shapes how the system scales, how it fails, what it costs and how it handles personal data.
This article explains what “stateless” and “stateful” mean for AI systems, compares three common designs, and shows the pattern most production systems settle on.
What counts as state in an AI application
“State” is anything the system must remember between requests. In AI applications it usually includes:
- Conversation history — the messages so far, including the model’s own replies.
- Tool and retrieval results — data fetched during a task that later steps depend on.
- Workflow progress — which steps of a multi-step task are done, pending or waiting for approval.
- User context — preferences, permissions, uploaded files, long-term memory.
- Caches — embeddings, retrieved passages or responses kept to save time and money.
The model itself is stateless
A language model does not remember earlier requests. Each call produces output only from the input it receives. Chat APIs make this explicit: Anthropic’s documentation, for example, describes its Messages API as supporting “stateless multi-turn conversations” — you send the prior turns in the messages parameter with every request.
Some providers add optional server-side state on top. OpenAI’s Responses API can chain turns with previous_response_id, and its Conversations API stores a durable conversation object that later requests reference by ID. That is convenient, but it is a storage feature of the API, not memory in the model — and it moves your conversation data, its retention and its deletion into the provider’s system. Decide deliberately whether that fits your privacy and compliance requirements.
The same applies to the web layer around your app. HTTP is defined as a stateless protocol (RFC 9110), so any memory across requests is something your application chooses to build.
Three places the state can live

A. The client holds the state
The browser or app keeps the conversation and sends the full history with every request. The server is purely stateless: any replica can answer any request.
It is the simplest design and scales trivially. The costs grow with the conversation: larger requests, more input tokens per call, and history you cannot trust blindly, because the client can modify it. It also cannot support anything that continues without the client — background jobs, approvals, scheduled follow-ups.
B. The server holds the state in memory
Each server process keeps sessions in RAM. Requests carry only a session ID. It feels fast and natural, and it is how many prototypes start.
The problems appear at scale. A session lives on one replica, so the load balancer must route every request for that session to the same place (sticky sessions). When that replica restarts, deploys or crashes, the session is lost. Scaling down drops conversations. The Twelve-Factor App methodology puts it bluntly: sticky sessions “should never be used or relied upon”.
C. Stateless compute with an external state store
Application servers stay stateless, but they read and write state in a shared store — Redis for short-lived session data, a database for anything durable. Any replica can serve any request because the state is never in the replica.
This is the pattern most production systems end up with. It scales horizontally, survives restarts and deploys, and gives you one place to apply retention, deletion and access rules. The price is an extra network hop per request and the need to handle concurrent updates.
Comparing the three
| A. Client holds state | B. Server memory | C. External store | |
|---|---|---|---|
| Horizontal scaling | Easy | Needs sticky sessions | Easy |
| Survives restarts | Yes (client keeps it) | No | Yes |
| Request size / tokens | Grows with history | Small request | Small request |
| Trust in history | Low — client can alter it | High | High |
| Background work and approvals | Not possible | Fragile | Supported |
| Data retention and deletion | On every client device | Lost unpredictably | One controlled place |
| Complexity | Lowest | Low at first | Moderate |
The common pattern in practice
The sketch below keeps conversation history in Redis with an expiry time, using an optimistic transaction so that two requests for the same session cannot overwrite each other’s turns. It uses the redis-py client; call_model stands in for your model provider’s SDK.
import json
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
TTL_SECONDS = 60 * 60 * 24 # forget idle sessions after a day
def load_history(session_id: str) -> list[dict]:
raw = r.get(f"chat:{session_id}")
return json.loads(raw) if raw else []
def append_turns(session_id: str, *turns: dict) -> None:
key = f"chat:{session_id}"
with r.pipeline() as pipe:
while True:
try:
pipe.watch(key) # fail if someone else writes first
raw = pipe.get(key)
history = json.loads(raw) if raw else []
history.extend(turns)
pipe.multi()
pipe.set(key, json.dumps(history), ex=TTL_SECONDS)
pipe.execute()
return
except redis.WatchError:
continue # retry with the fresh value
def handle_message(session_id: str, user_text: str, call_model) -> str:
history = load_history(session_id)
messages = history + [{"role": "user", "content": user_text}]
reply = call_model(trim_to_budget(messages)) # see "Managing the context window"
append_turns(session_id,
{"role": "user", "content": user_text},
{"role": "assistant", "content": reply})
return reply
A few design choices are worth copying even if your stack is different:
- The session ID is the only thing the client sends. History is never trusted from the client.
- State has a lifetime. The TTL means abandoned sessions disappear on their own; durable records belong in a database with an explicit retention policy.
- Writes are safe under concurrency. Two tabs or a retried request must not silently drop turns.
Managing the context window
Keeping history is only half the job; you also decide what the model sees. The trim_to_budget step in the sketch is where that happens. Typical strategies, often combined:
- Sliding window — keep the system prompt and the most recent turns that fit the budget.
- Summarise older turns — replace the oldest part of the conversation with a short summary, stored alongside the history.
- Retrieve long-term memory — store facts and past interactions separately and retrieve only what is relevant to the current question, as in a RAG system.
Whatever you choose, count tokens with the tokenizer of the model you use, and keep the full history in storage even when the prompt only carries part of it — you will need it for support, audits and debugging.
Agents and long-running workflows
Agents raise the stakes because their state includes progress: which tool calls have run, what they returned, and what is waiting for a person. Treat that as durable workflow state, not as chat history:
- Checkpoint after each step, so a crash resumes from the last completed step instead of starting over.
- Make side effects idempotent — give each action (send an email, create an invoice) an idempotency key, so a retry cannot do it twice.
- Persist pauses. A task waiting for approval may wait hours; it must not depend on a process staying alive. Workflow tools such as n8n handle this by storing waiting executions in their database.
How to choose
- Prototype or single-turn tool? Stay stateless and let the client send what is needed.
- Multi-turn chat in production? Stateless servers with an external session store.
- Agents, approvals or background jobs? External store plus durable, checkpointed workflow state.
- Considering provider-side conversation state? Check where the data is stored, for how long, and how you delete it — then decide.