TUTORIAL17 min read

Agent Memory Architecture: State Across Sessions

A practical guide to keeping the right agent state, retrieving it safely, and controlling the context sent to your model.

P
PADISO teamPublished 27 Oct 2026

An agent memory architecture separates temporary working context from durable information that an agent may need in later turns or sessions. Build it as a small set of purpose-specific layers, retrieve only relevant state, and measure the tokens and quality each layer adds. In this tutorial, you will implement a practical pattern with a thread checkpoint, a namespaced long-term memory store, a bounded prompt, and an asynchronous memory-write path. If you are still choosing which agent work is worth productionising, start with our AI strategy and solutioning service.

Goal: preserve useful state without resending the whole transcript

We will build the memory path for a support agent that helps a user troubleshoot a product issue. The agent needs to remember the current troubleshooting steps within a conversation, recall a durable preference in a later conversation, and avoid treating old or conflicting facts as current.

The target request flow is:

  1. Load the current thread checkpoint.
  2. Retrieve a small set of relevant cross-session memories for the correct user and organisation.
  3. Assemble a bounded model prompt from stable instructions, recent turns, and selected memories.
  4. Return the response without waiting for long-term memory extraction.
  5. Queue a background job to identify durable facts and update memory after the response.

The key design choice is not which vector database to buy. It is deciding which information belongs in which layer, how it gets there, and how you know it helped. A vector database is one retrieval tool. It is not a complete state model.

The examples below are provider and framework neutral. They map to LangGraph's distinction between thread-scoped checkpoints and cross-thread stores, described in the LangGraph persistence documentation. If your system uses another orchestration framework, keep the scopes and responsibilities even if the implementation names differ.

What you need before you build

Start with a simple service that can make a model call and persist a conversation. Add these components:

Component Responsibility A reasonable first choice
Thread checkpoint store Save resumable state for one conversation PostgreSQL, Redis, or a framework checkpointer
Long-term memory store Save and retrieve durable facts across threads PostgreSQL with a vector extension, or a dedicated vector service
Queue and worker Extract and update memories off the response path Your existing queue and worker stack
Identity and policy layer Enforce user, organisation, access, and retention rules Your application service and database constraints
Evaluation set Check recall, conflict handling, and unwanted retrieval A versioned set of realistic test conversations

Do not choose a storage engine from a latency table alone. Performance depends on filters, index settings, data shape, hardware, and workload. The pgvector, Qdrant, and Pinecone comparison can help frame the trade-offs, but test your own query patterns before committing.

You also need an answer to a product question: what is the agent allowed to remember? Write that down before you add extraction. A preference such as a preferred response format might be useful across sessions. A password, payment detail, or sensitive support transcript usually should not become persistent conversational memory. Your application policy, privacy obligations, and retention schedule must decide what is allowed. For regulated Australian use, review the relevant controls with your legal, privacy, security, and risk owners. Our AI for financial services page covers the sector context, but this tutorial is not legal advice.

Agent memory architecture: define the tiers and their boundaries

Use four logical tiers. You do not have to deploy four separate products. In a small system, a single PostgreSQL deployment might hold checkpoints, structured facts, and vectors. The point is to keep different lifecycles and access rules explicit.

Tier Scope Store Put here Do not put here
Working context One model request Prompt and provider cache where available Stable instructions and the small selected context for this call An ever-growing transcript
Thread state One conversation ID Checkpointer or relational record Recent messages, tool progress, approvals, resumable workflow state Facts assumed to apply to every future conversation
Long-term memory User or organisation across threads Structured records plus optional vector index Confirmed preferences and useful episodic summaries Raw unfiltered transcripts as a default
Temporal facts A fact whose value can change Records with validity and provenance, or a temporal graph Current and prior values, when each applied, and source A single undated embedding that hides contradictions

Think of the thread checkpoint as the agent's working notebook. It lets a run continue or recover. It does not automatically provide memory for a new conversation. LangGraph documents this separation between checkpointers and stores in its memory concepts. Give the new conversation a new thread identifier, then retrieve cross-session state explicitly from a store keyed by the authenticated identity.

A vector search is useful when the user asks a question that resembles a saved fact or episode. It is not enough for all state. If the user moved from one city to another, a similarity search may return both statements. Store changing facts with dates, source, and status, or use a temporal graph when the relationships and change history justify the extra complexity. The Qdrant, Pinecone, and pgvector comparison is one reference for storage trade-offs, not proof that a particular product is right for your workload.

Step 1: write the memory contract

Before schema design, define rules that both the extraction worker and the read path can enforce. Keep the first version small and concrete.

For the support agent, a memory contract might say:

  • Save only information that is likely to improve a later support interaction.
  • Prefer a short, attributable fact over a copied message or full transcript.
  • Store the source thread and the time the fact was observed.
  • Mark facts that may change as time-sensitive, and retain a previous value when audit or product needs require it.
  • Do not save secrets, authentication data, or information outside the approved categories.
  • Apply the same tenant and user access checks on reads, writes, updates, and deletion.
  • Give the user a way to inspect or request removal of saved information where the product requires it.

Decide what counts as a durable memory. For example, the user repeatedly asks for step-by-step instructions and confirms that preference. That could be a preference record. A one-off error message is usually episode context, not a stable profile fact. The agent should not infer a permanent preference from a single request without a confidence rule or confirmation.

Write down the retention and deletion behaviour too. If a user requests deletion, the system may need to remove the source record and its vector representation, invalidate derived summaries, and prevent queued jobs from recreating it. Build deletion as a system operation, not as an instruction to the language model. For privacy and security engineering, our AI agents and automation service focuses on turning these controls into production workflows.

What you should see: a short, reviewable policy with allowed categories, prohibited categories, identity scope, update rules, and deletion behaviour. If the policy says only ‘remember useful things’, it is not specific enough to build against.

Step 2: model thread state separately from long-term memory

Create different records for the current run and cross-session facts. A minimal relational design could look like this:

CREATE TABLE agent_memory (
  memory_id UUID PRIMARY KEY,
  org_id TEXT NOT NULL,
  user_id TEXT NOT NULL,
  memory_type TEXT NOT NULL,
  content TEXT NOT NULL,
  source_thread_id TEXT NOT NULL,
  observed_at TIMESTAMPTZ NOT NULL,
  valid_from TIMESTAMPTZ,
  valid_to TIMESTAMPTZ,
  status TEXT NOT NULL,
  sensitivity TEXT NOT NULL,
  embedding VECTOR,
  created_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX agent_memory_owner_idx
  ON agent_memory (org_id, user_id, status);

Treat this as a shape, not a production-ready schema. The vector column and index syntax depend on your database. Add constraints, encryption, access controls, migration strategy, and audit fields for your actual environment. If using a separate vector service, keep an authoritative record in a system where you can enforce lifecycle and deletion rules, and treat the vector index as a derived retrieval structure.

For thread state, use a separate table or framework checkpointer keyed by a thread ID. Store the organisation and user identity alongside it, and verify ownership before loading it. A thread ID is a locator, not an authorisation mechanism. A client must not be able to swap IDs and read another person's conversation.

For long-term memory, use a namespace such as (org_id, user_id, memory_type). Apply the namespace filter inside the database query, not after retrieving a mixed result set. This prevents a ranking result from another tenant entering application memory even briefly. Add a test that attempts cross-user and cross-organisation reads.

What you should see: a checkpoint lookup requires a validated thread scope, while a memory lookup requires the authenticated organisation and user. A new thread can retrieve approved long-term facts without loading the previous thread's full transcript.

Step 3: build a bounded read path

The read path decides what the model sees on every turn. Keep it deterministic enough to inspect and test.

A straightforward sequence is:

  1. Authenticate the user and resolve the organisation from trusted server-side identity.
  2. Load the checkpoint for the requested thread after verifying its ownership.
  3. Read a compact profile block from structured memory, if one exists.
  4. Search episodic or semantic memories using the current user request and a strict namespace filter.
  5. Apply status, time, sensitivity, and relevance rules before selecting results.
  6. Assemble the prompt with stable instructions first, then the selected memory and bounded recent context.
  7. Record token estimates and retrieval identifiers for observability.

Do not blindly put every retrieved result into the prompt. Set a budget for each part: system instructions, tool descriptions, recent conversation, structured profile, retrieved episodes, and current request. The exact budget depends on the model, task, and service-level target. Measure actual tokenisation with the model's tokenizer or provider usage fields rather than assuming character count equals token count.

A prompt builder could follow this shape:

SYSTEM: stable policy and task instructions
PROFILE: approved, compact facts for this user
MEMORY: only relevant retrieved items, with dates and sources
RECENT: bounded recent turns from this thread
CURRENT REQUEST: the latest user message

Keep stable content before variable content when your provider's prompt caching depends on matching a stable prefix. Avoid putting a timestamp, user ID, or per-request value at the top of otherwise reusable instructions. Caching behaviour and pricing vary by provider and can change. The Eden AI prompt caching guide outlines provider differences; check your provider's current documentation and billing details before estimating savings.

A sliding window is a practical default for recent conversation. Keep the most recent turns needed to resolve references, and checkpoint older progress as a concise summary if the workflow needs it. Do not truncate blindly at a character boundary. You can lose a user constraint or an unresolved decision. Summaries should retain open questions, decisions, tool outcomes, and required next actions, with links or IDs to authoritative records where relevant.

What you should see: each model request has a bounded, inspectable prompt. A memory retrieval miss does not break the workflow, and an irrelevant result can be excluded without losing the current thread's essential state.

Step 4: retrieve with filters, not similarity alone

Embeddings rank text by semantic similarity. They do not establish that a fact is true, current, authorised, or relevant to the user's organisation. Add metadata and business rules to the query.

A useful retrieval filter includes:

  • Exact org_id and user_id from authenticated server context.
  • status = active, or an explicit status policy for historical questions.
  • An allowed memory type for the current task.
  • Sensitivity and retention eligibility.
  • Time validity when the query asks about the current state.

Then rank the eligible candidates. Start with a small result count, inspect relevance, and measure how often each result contributes to a correct answer. If your database supports hybrid search, combine lexical matching for exact names or identifiers with vector similarity for paraphrases. Do not assume hybrid search is automatically better. Evaluate it against the questions your agent actually receives.

For changing facts, represent the change rather than hoping the newest sentence wins a similarity contest. For example, store a location fact with valid_from, valid_to, source, and status. When a new confirmed fact supersedes the old one, mark the prior fact as no longer current while retaining its history if your policy requires it. A question about the present should filter to the currently valid record. A question about a previous state should query the history explicitly.

If you need to answer questions about complex relationships and change over time, a temporal knowledge graph may be justified. Graphiti and Zep are discussed in the supplied research notes as options for representing temporal relationships. Do not introduce a graph just because facts can change. First see whether structured rows with validity intervals meet the product requirement.

What you should see: the retrieval log shows the exact namespace and filters, and every returned memory has a source and status. A query for current state returns the current record, while a historical question can retrieve a previous record with its validity dates.

Step 5: write long-term memory asynchronously

Do not make every user-facing response wait for an LLM to summarise the conversation and write embeddings. That can add latency and an extra model call to the critical path. Instead, after the response is committed, enqueue a job containing the permitted source data and identifiers needed to apply the memory contract.

The worker should:

  1. Load the canonical conversation events from authorised storage.
  2. Remove or redact content that is prohibited from memory.
  3. Extract candidate facts into a constrained schema, including type, content, source, and time.
  4. Validate the candidates against policy and known structured facts.
  5. Deduplicate or update an existing fact rather than creating near-identical records on every turn.
  6. Generate embeddings only for records that need semantic retrieval.
  7. Write the authoritative memory record and update the vector index transactionally or through a retryable outbox pattern.
  8. Record job status and errors without logging unnecessary sensitive content.

The worker should be idempotent. If the queue delivers the same event twice, the second run should not create a duplicate memory. Use a stable source event or extraction ID as an idempotency key. Handle failed embedding calls and database timeouts with retries and a dead-letter path. A failed memory update should not silently corrupt the conversation checkpoint.

Extraction does not make a statement true. Treat model-produced facts as candidates. For high-impact facts, require user confirmation or rely on a verified application source. Keep provenance so an operator can trace a memory back to the conversation event or system of record that produced it.

What you should see: the user receives the response before extraction completes. A queue dashboard shows pending, completed, and failed jobs. Replaying a job does not create duplicate facts, and a worker failure can be retried without changing the already-delivered response.

Step 6: keep context and costs under control

The cost problem is repeated input, not memory storage in isolation. If each turn sends the entire conversation so far, earlier messages are paid for again on later requests. A bounded window and selective retrieval limit that repetition. Prompt caching can reduce the price of eligible repeated prefixes, but it does not make an unbounded prompt a good design. Long context still affects latency, retrieval quality, and the chance that important instructions are overlooked.

Use a token ledger for each request. Record, where available:

  • Input tokens for stable instructions and tool definitions.
  • Cached input tokens and uncached input tokens.
  • Recent conversation tokens.
  • Retrieved memory tokens.
  • Output tokens.
  • Retrieval count, latency, and selected memory IDs.

Then compare architectures using the same model, task, and evaluation set. The following is an illustrative token-accounting example, not a provider quote or a guaranteed saving. It uses the scenario from the supplied research notes: 5,000 stable instruction and tool tokens, 1,000 new tokens per turn, and a 20-turn session. The notes estimate 310,000 input tokens for resending the accumulating transcript, before accounting for provider-specific cache billing. A tiered approach caps recent context and adds only a small retrieved memory set. The important result to validate is not the particular estimate. It is whether your measured prompt stops growing with every turn while task quality remains acceptable.

Design What goes into each call What to measure
Full transcript All prior messages and tool traces Cumulative input tokens, latency, missed constraints
Cache only Same growing history, with eligible repeated prefix cached Cache hit rate, billed input, total context length
Tiered memory Stable prefix, bounded recent turns, selected memory Total input tokens, retrieval precision, task success, write cost

Run this comparison against your own requests. Include short sessions, long sessions, a session with a correction, and a session with a new thread. Count the cost of background extraction and embedding as well as the main model call. If a memory layer saves prompt tokens but adds expensive writes or retrieves irrelevant facts, the total system may not improve.

For storage choice, begin with the database your team can operate and the query constraints you need. PostgreSQL with vector support can be a sensible starting point if you already operate Postgres and your scale and retrieval needs fit. A dedicated vector service can suit workloads that need its operational or filtering characteristics. Validate total cost, backup, deletion, tenant filters, and failure behaviour. The vector database pricing comparison is a starting reference, not a substitute for a workload-specific estimate.

What you should see: the context token count reaches a predictable ceiling for long sessions. You can explain the cost of a normal interaction, an extraction job, and a retrieval miss. You can also see whether caching is occurring rather than assuming it is.

Step 7: test that memory helps and stays safe

Build a small evaluation set before rollout. Include cases where memory should be used, should be ignored, and should be corrected.

Test case Expected behaviour How to check
New thread, known preference Use the permitted preference without loading old transcript Inspect retrieved IDs and response
Unrelated request Do not inject unrelated memories Check relevance and prompt contents
Changed preference Use the latest confirmed value Check status, provenance, and answer
Historical question Distinguish former value from current value Check time-aware retrieval
Cross-tenant identifier attempt Return no other tenant's memory Assert at query and API layers
Delete request Remove or invalidate memory and derived index entry Verify read path and queued-job behaviour
Memory service unavailable Continue safely with current thread or fail by policy Simulate outage and inspect response

Track at least four kinds of quality: whether the right memory was retrieved, whether an irrelevant one was retrieved, whether the answer used the memory correctly, and whether the system respected access and deletion rules. Keep a human review path for errors that could materially affect a user. A successful vector query is not the same as a successful answer.

Also test failure modes. Make the vector store slow, make the queue unavailable, and make the checkpoint store fail. Decide what the agent should do in each case. A support agent may continue without long-term memory but disclose that it cannot access prior preferences. A workflow that relies on approval state may need to stop rather than proceed without its checkpoint. The failure policy depends on the consequence of getting state wrong.

What you should see: a repeatable test run reports retrieval and answer outcomes, with failures you can trace to a query, filter, extraction, or prompt assembly decision. A deploy is blocked if tenant isolation or deletion tests fail.

Step 8: roll out in stages and observe the system

Start with a small cohort or a non-critical workflow. Keep the transcript-only or no-memory path available as a comparison. Use feature flags so you can disable retrieval or writes independently.

A practical rollout sequence:

  • Baseline: Log token use and task quality without adding long-term memory.
  • Read-only experiment: Populate candidate memories, but do not send them to the model. Review extraction quality and filtering.
  • Limited retrieval: Enable retrieval for a narrow memory type and a small cohort. Compare against the baseline evaluation set.
  • Write-behind: Enable asynchronous extraction with monitoring, retries, and deletion handling.
  • Broaden carefully: Add new memory types only when you have a product need and tests for them.

Monitor prompt size, cache hit behaviour, retrieval latency, empty results, duplicate rate, stale-memory rate, extraction failures, queue age, and deletion completion. Watch for quality changes, not just infrastructure health. An agent that answers quickly using stale context is not healthy.

Keep an operator view that can show a memory's type, source, dates, status, and access scope without exposing more sensitive content than necessary. Provide a way to correct bad memories. If people cannot understand why the agent recalled something, trust will erode even if the retrieval score looked good.

For architecture decisions that span model providers, identity, storage, and operational ownership, PADISO's platform engineering service can help shape the system boundary and delivery plan. We build what we recommend, so the first step is usually to map the agent's current state flow, token use, and failure requirements before choosing a database or framework.

Common mistakes to avoid

One vector collection for everything. Mixing transcripts, tool schemas, user preferences, and product documentation makes retrieval harder to reason about. Separate by purpose or use strict metadata filters and distinct retrieval logic.

Treating a checkpoint as cross-session memory. A checkpoint supports one thread's continuity. A new thread needs an explicit lookup into a user- or organisation-scoped store. LangGraph's persistence reference describes the checkpoint interface and is useful when implementing that layer.

Trusting similarity as truth. Similar wording does not mean a fact is current or authoritative. Track provenance, status, and time for facts that change.

Blocking the response on extraction. Keep long-term write work off the synchronous path unless the user experience truly needs a confirmed write before proceeding.

Assuming a cache eliminates context design. Cache eligible repeated tokens when the provider supports it, but keep the prompt bounded and useful. Provider cache rules differ, and a dynamic prefix can reduce cache reuse.

Forgetting the deletion path. A delete endpoint must cover source records, derived vectors, summaries, and in-flight jobs. Test the full path rather than deleting one database row and assuming the memory is gone.

Where PADISO fits

PADISO helps teams design and build agent systems, including memory boundaries, retrieval and evaluation, asynchronous automation, and platform integration. Our AI agents and automation service is relevant when you are moving from a prototype to a monitored production workflow. The sensible first step is to map what state the agent needs, what it must never retain, and how you will prove the memory improves the task.

Your next step

Take one agent workflow and measure its prompt tokens, session state, and cross-session recall before adding another store. If you want a structured starting point, complete PADISO's AI readiness test and use the result to prioritise the architecture work.

WANT TO TALK THROUGH YOUR SITUATION?

Talk it through with us. Thirty minutes, no slides.

P
Written by the PADISO TeamSydney-based technology leaders who build what they advise on. Seven years of fractional CTO, architecture and AI work for enterprise, government and private equity.

Keep reading

All posts →

Let's talk.

Tell us what you are weighing up, whether it is a build, a roadmap or a deal. You will leave the call knowing your next step.

Book a 30-min callhi@padiso.co