How to persist AI agent memory across sessions: Redis for session state, a vector database for long-term recall, and a hybrid pattern with code.

TL;DR: Agent memory persistence across sessions works best as two stores with different jobs. Redis holds the current session's state and recent turns with a TTL, keyed by tenant and session. A vector database such as pgvector holds distilled long-term facts, filtered by user before similarity ranking. A background worker moves facts from the first store to the second, so the agent's reply never waits on extraction.
A session is one bounded interaction: a chat thread, a support ticket, a single run of a coding agent. Inside a session, the model sees its context window, and the framework usually keeps the message list in process memory. When the process restarts, the user comes back tomorrow, or a second replica picks up the next request, that in-process memory is gone. Persistence across sessions is the work of saving what the agent needs and loading the right subset back into the next context window.
It helps to split memory by lifetime and access pattern, because each split points to a different storage choice:
The first two are keyed lookups with a natural expiry. The last two are retrieval problems. That difference, more than any vendor feature list, is what decides the Redis vs vector database question. Our earlier piece on agent memory management covers the conceptual taxonomy; this article is about the storage and code.
Replaying the full transcript is the simplest form of persistence, and for short-lived assistants it is fine. It breaks down in three predictable ways.
First, it does not fit. A user with fifty prior sessions has more history than any context window should carry, and truncating from the front throws away exactly the old facts that made persistence worthwhile.
Second, it costs on every turn. Every token reloaded into the prompt is paid for again on every model call in the session, whether or not it matters to the current question.
Third, it does not bind. As we found when analysing the binding problem in agent memory, a fact buried on page forty of a transcript is technically present and practically ignored. A short, relevant list of facts placed near the instruction is more likely to change what the agent does than the same fact in a long scrollback.
So production systems keep the raw transcript (for audit and for re-extraction later), but they load a selection: current state, the recent tail, and the top few relevant long-term memories.
Use Redis for the parts of memory that are keyed by session and read on every turn. Its strengths line up with that workload:
Its weakness is durability and cost per gigabyte. Redis keeps the dataset in memory. With append-only-file persistence set to appendfsync everysec, the Redis documentation says a crash can lose about one second of writes; with snapshots only, the loss window is the time since the last snapshot. That is an acceptable trade for a session tail that can be rebuilt. It is a poor one for a user's accumulated preferences that took months to learn.
The example uses redis-py 5.x and Python 3.11+. It assumes REDIS_URL points at a Redis instance you control.
Two details matter more than they look. The version check turns a lost update into a visible StateConflict that the caller can retry by reloading state, instead of two replicas each writing their own plan and the later one winning. And the xadd sits inside the same transaction as the turn, so a turn that reaches the session history is guaranteed to reach the memory pipeline too.
Use a vector database for memory that must be found rather than fetched. When a user says "set it up the way I like", nothing in that message names the key "preferred_language". The agent needs whatever stored facts are semantically close to the message, filtered to that user. That is approximate nearest-neighbour search plus a metadata filter, which is what a vector database is built to do. Our vector database comparison covers engine choice in depth; the example here uses pgvector because many teams already run PostgreSQL, and a relational table makes supersession, uniqueness and deletion straightforward.
Store distilled facts, not raw turns. Each row carries its owner, its type, where it came from, which embedding model produced the vector, and whether a newer fact replaced it.
embedding_model exists because vectors from two different models are not comparable. When you change models, you re-embed into new rows and filter queries to one model at a time, rather than mixing distances that mean different things.
The filter is a security boundary, not a relevance tweak. The query below ranks only rows owned by the current tenant and user. With an HNSW index, PostgreSQL scans the graph and then applies the WHERE clause, which can return fewer rows than requested when the filter is selective. pgvector 0.8.0 added iterative index scans (hnsw.iterative_scan) to keep scanning until enough rows pass the filter; on older releases, raise hnsw.ef_search or use a partial index per large tenant.
Supersession keeps history honest. When a user who "prefers Python" later says "we've moved everything to Go", the extractor writes the new fact and points the old row at it. Recall stops returning the stale preference, but an audit can still show what the agent believed and when it changed.
The framing "Redis vs vector database" is partly a false choice. Redis's query engine can also index vector fields, and PostgreSQL can hold session state. The real question is which store's defaults match each memory type's lifetime, durability need and query shape.
If your agent only needs continuity within a conversation that lasts a day, Redis alone is enough. If it needs to remember users across months but has no live multi-turn state, a vector store alone is enough. Most assistants that users return to need both, which is where the hybrid pattern comes in.
The hybrid pattern separates the hot path, which must be fast, from consolidation, which must be careful.
Nothing on the reply path waits for fact extraction, which is usually the slowest and least reliable step because it calls a model.
Three properties make this safe to run unattended. The unique content_hash constraint means a retried event cannot insert the same fact twice. XAUTOCLAIM gives an event abandoned by a crashed worker to a live one. And the supersedes check refuses an id the extractor invented, so a hallucinated reference cannot retire an unrelated memory. Add a retry counter or dead-letter stream before production, so one malformed event cannot loop forever.
Place the recalled memories in a short, labelled block near the instruction, not mixed into the history. Keep the similarity threshold and k as configuration, and log which memory ids went into each prompt. When an agent misbehaves, that log is how you tell a retrieval failure from a reasoning failure.
Tenant isolation. Every key and every query must carry the tenant and user. A memory query without an owner filter is a data leak, and a test should prove the filter is applied, for example by seeding two users with similar facts and asserting that neither sees the other's.
Deletion that misses copies. A "forget me" request has to reach the vector rows, the Redis session keys, the stream entries that still hold raw turns, and any backups or analytics exports. Bounded stream retention (MAXLEN or MINID) limits how long raw turns linger there.
Embedding model changes. Re-embedding is a migration. Write new rows under the new embedding_model, switch reads once backfill completes, then remove the old rows.
Memory poisoning. Anything a user, web page or tool output says can become a stored "fact". Extract from user turns rather than from retrieved documents, validate the extractor's output like any untrusted input, and consider requiring confirmation for memories that change permissions or billing.
Stale and contradictory facts. Without supersession, recall returns both the old and new preference and the model picks one. Expiry dates suit facts with a natural lifetime ("on call this week").
Evictions. If Redis runs with an eviction policy such as allkeys-lru, session keys can disappear under memory pressure. That is tolerable for a cache and surprising for session state; use noeviction or a volatile policy and alert on memory use.
You do not always need to build both stores yourself. Several frameworks ship the same split under their own names:
A managed or framework store removes code, not decisions. You still choose what gets extracted, how owners are scoped, how long data lives and how deletion works. Check those against the current documentation for the version you install.
Whichever you pick, start by writing down each memory type's owner, lifetime and deletion path. The storage choice usually follows directly from that list.
For most production agents, use two stores. Keep session state and recent turns in a fast keyed store such as Redis with a TTL. Keep distilled long-term facts in a vector database filtered by user, and move facts between them with an asynchronous extraction worker.
Neither is better overall; they suit different memory types. Redis suits per-session state that is read every turn and can expire. A vector database suits long-lived facts that must be found by meaning. Redis can index vectors too, but its in-memory cost and durability model favour short-lived data.
Yes. Redis's query engine supports vector fields with HNSW and flat indexes, so one Redis deployment can hold both session data and embeddings. Before relying on it for long-term memory, confirm your persistence configuration, memory budget and eviction policy match how long those facts must survive.
Put the tenant and user identifiers in every key and every vector query, and apply them as filters before results reach the prompt. Test it by seeding two users with near-identical facts and asserting that each query returns only its owner's rows.
Write the new fact as a new row and mark the old one superseded rather than overwriting it. Recall then returns only current facts, while an audit can still show what the agent believed earlier and when it changed.
Usually not. Extraction calls a model and is the slowest, least reliable step. Publish the turn to a queue such as a Redis Stream and extract in a background worker, accepting that a fact stated this turn becomes recallable a few seconds later.
Start with a small number, such as three to five above a similarity threshold, and tune with logged examples. Too many memories dilute the instruction, and an irrelevant memory can mislead the model more than a missing one.
Aaron is an engineering leader, software architect, and founder with 18 years building distributed systems and cloud infrastructure. Now focused on LLM-powered platforms, agent orchestration, and production AI. He shares hands-on technical guides and framework comparisons at fp8.co.
Add long-term memory to a LangChain AI agent. LangChain, AgentCore and Strands compared on architecture, persistence and scaling limits.
Agent Memory ManagementCompare pgvector, Pinecone, Qdrant, Weaviate, and Milvus on indexing, filtering, scale, and cost to pick the right vector database for RAG.
AI EngineeringDiscover why AI agent memory fails at binding, not recall. 500+ experiments reveal architecture patterns that fix context-action gaps.
AI Engineering