Agent Memory Systems

Production-grade guide to agent memory systems covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Orientation

Agent Memory Systems encompass the patterns, data structures, and infrastructure that let an AI agent retain information across individual request‑response cycles. Without deliberate memory, every user interaction begins stateless: the model receives the prompt, generates a response, and the conversation is discarded. Memory systems reattach context, persist state, and enable agents to reference prior turns, user preferences, or task history. They matter whenever an agent must maintain continuity beyond a single exchange – multi‑turn customer‑support bots, orchestration workflows that resume after a restart, or any agent that needs to avoid re‑computing work it has already done. This reference page covers the concrete mechanisms for storing, querying, and pruning agent memory, the commands and configuration patterns that work across typical stacks, and the failure modes that catch teams off guard when memory grows unbounded or becomes inconsistent.

Storing a Conversation Turn

The most basic memory operation is persisting a single turn – the user prompt or the agent’s reply – so it can be linked back later. In a typical deployment the agent writes to a relational table or a key‑value store immediately after the LLM response is generated.

Using psql to insert a turn into a PostgreSQL‑backed memory table

INSERT INTO agent_memory (
  agent_id,
  turn_id,
  role,
  content,
  embedding,
  created_at,
  metadata
) VALUES (
  'ws-412',
  't-87',
  'user',
  'What is the status of order 309?',
  '[0.12, -0.45, 0.78, -0.33, 0.91, -0.07, 0.22, 0.55, -0.18]',
  '2025-03-15 12:34:56',
  '{"source": "web-chat", "session": "sess-99a"}'
);

Using curl to POST a turn to a generic agent‑memory HTTP endpoint

curl -X POST http://agent.local/api/v1/memory \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "ws-412",
    "turn_id": "t-87",
    "role": "user",
    "content": "What is the status of order 309?",
    "metadata": {
      "source": "web-chat",
      "session": "sess-99a",
      "timestamp": "2025-03-15T12:34:56Z"
    }
  }'

Both patterns assume the receiving system normalises the embedding field – a numeric array representing the semantic content of the turn. If the agent does not use embeddings, the embedding column can be NULL and retrieval will rely on exact‑match or LIKE/ILIKE queries on content.

Retrieving Relevant Past Context

Once turns are stored, the agent must be able to pull the most pertinent ones when a new prompt arrives. The retrieval strategy depends on whether the system uses exact‑match filtering, time‑based ordering, or semantic similarity.

Exact‑match retrieval by agent and turn identifier

SELECT turn_id, role, content, created_at
FROM agent_memory
WHERE agent_id = 'ws-412'
  AND turn_id = 't-87'
ORDER BY created_at DESC
LIMIT 1;

Time‑ordered history – useful for “last N turns” contexts

SELECT turn_id, role, content, created_at
FROM agent_memory
WHERE agent_id = 'ws-412'
ORDER BY created_at DESC
LIMIT 10;

Semantic retrieval via vector similarity – many production systems store a pre‑computed embedding for each turn and use the database’s native distance function to rank results. The exact operator varies by extension (e.g., <=> for pgvector, <-> for TimescaleVector, cosine_distance for Milvus), but the pattern is consistent: compute the embedding for the new query, store it alongside the turn, and order by distance.

A generic curl request to a semantic‑search endpoint might look like this:

curl "http://agent.local/api/v1/memory/search?agent_id=ws-412&query=[0.21,-0.03,0.77,-0.44,0.18,0.55,-0.12,0.33,0.01]" \
  -H "Accept: application/json" \
  | jq '.results | map({turn_id, role, content, score})'

The endpoint internally performs SELECT … ORDER BY embedding <=> $1 LIMIT 5 (or the equivalent for the deployed vector store) and returns the most similar turns along with a similarity score. The reader can map this shape to their platform’s API – the HTTP contract (POST/GET with JSON body, query parameters for filters, JSON array of results with an attached distance metric) is virtually universal across vector‑enabled agents.

Pruning and Invalidation

Memory that grows unchecked inflates context windows, drives up token costs, and can even cause retrieval to return stale or irrelevant results. Pruning strategies fall into three categories: time‑to‑live (TTL), size‑based caps, and content‑based expiry.

Deleting turns older than a threshold with psql

DELETE FROM agent_memory
WHERE agent_id = 'ws-412'
  AND created_at < NOW() - INTERVAL '90 days';

Enforcing a per‑agent turn cap – keep only the most recent N turns

DELETE FROM agent_memory
WHERE ctid NOT IN (
  SELECT ctid
  FROM (
    SELECT ctid,
           ROW_NUMBER() OVER (
             PARTITION BY agent_id ORDER BY created_at DESC
           ) AS rn
    FROM agent_memory
    WHERE agent_id = 'ws-412'
  ) sub
  WHERE rn <= 50
);

Invalidating a specific turn by ID

curl -X DELETE http://agent.local/api/v1/memory/t-87 \
  -H "Content-Type: application/json"

TTL via database‑native features – if the deployment uses PostgreSQL with the pg_cron extension, a scheduled job can automate expiry:

SELECT cron.schedule('0 3 * * *',
  'DELETE FROM agent_memory WHERE created_at < NOW() - INTERVAL ''30 days''');

Each of these commands assumes the agent_memory table has a created_at timestamp column. If the store is a NoSQL or key‑value system, the equivalent operations are a delete by primary key, a TTL set on the entry, or a periodic compaction job – the logical pattern is the same.

Sharp Edges – What Silently Fails

Embedding drift without re‑indexing – When an agent’s embedding model is upgraded (e.g., text-embedding-3-small replacing text-embedding-ada-001), existing embeddings in the memory table no longer reflect the same vector space. Queries for “similar” turns return garbage, and the agent appears to “forget” previously relevant context. The failure is silent because the WHERE/ORDER BY clause still executes without error; the distance metric simply no longer maps to semantic similarity. Mitigation: store the model name or version alongside each embedding, and rebuild the similarity index when the model changes.

Concurrent writes racing past TTL cleanup – In high‑throughput agents, two requests may insert a turn at nearly the same moment, and a cron‑based TTL job may delete rows based on a timestamp snapshot taken seconds earlier. The result is that recently inserted turns are pruned, breaking continuity for the very user who just interacted. The only observable symptom is “the agent suddenly doesn’t remember our last conversation.” Mitigation: use database‑level ROW‑level locking or advisory locks around the delete batch, or employ a write‑ahead log that records intent before commit.

Metadata bloat – If every turn stores a free‑form metadata JSON blob without a schema, the table grows wide and sparse. Query performance degrades because PostgreSQL must scan wider rows, and backup sizes increase disproportionately. Some teams discover the problem only after a pg_dump takes hours longer than expected. Mitigation: define a strict metadata schema (e.g., source, session, request_id) and store extensible fields in a separate agent_metadata table keyed by turn_id.

Vector store mis‑configuration causing “all‑results‑or‑none” – When a similarity search is performed without a LIMIT clause, or with a limit that exceeds the number of stored turns, the query may return the entire table or, in some vector engines, throw an error about dimension mismatch. In production, a missing LIMIT 5 in a frequently‑called search endpoint can balloon CPU usage and push the database into a read‑only state. Mitigation: always cap semantic queries with an explicit LIMIT, and validate that the query embedding’s dimensionality matches the stored column before execution.

TTL granularity finer than the storage granularity – Some key‑value stores only support TTL at the second or minute granularity. If an agent inserts a turn at 12:34:59 and the TTL is set to 30 seconds, the turn may persist for up to a full minute beyond the intended expiry. The agent then “remembers” a turn it should have forgotten, leading to subtle context contamination. Mitigation: either round timestamps to the TTL bucket on insert, or use a store that supports sub‑second TTL (e.g., Redis with PEXPIRE).

Configuration Patterns Worth Naming

While the exact keys differ between products, most agent‑memory deployments expose a handful of orthogonal knobs. Treat these as conceptual categories rather than vendor‑specific values:

Key / ConceptTypical Range / SemanticsFailure Mode if Mis‑set
memory_ttlInteger seconds; common values: 300 (5 min), 3600 (1 hr), 86400 (1 day)Too short → loss of cross‑session state; too long → unbounded growth, cost explosion
max_turns_per_agentInteger ≥ 0; 0 means “unbounded”Unbounded → context window overflow, every new prompt consumes more tokens
embedding_dimensionInteger matching the model’s output size (e.g., 1536 for text-embedding‑ada‑001)Mismatch → vector distance operators throw dimension‑error, or silently compute meaningless distances
similarity_metric"l2", "cosine", "dot_product"Wrong metric → ranked results are ordered incorrectly, agent appears “confused”
memory_index_refresh_intervalSeconds between re‑building the vector index (if the store requires periodic refresh)Stale index → similarity queries return outdated results even though new turns are inserted

These keys are not tied to any single product’s CLI or UI; they appear in documentation across the ecosystem (LangChain vector stores, LlamaIndex retrievers, custom PostgreSQL schemas, Redis‑JSON setups, etc.). The reader’s task is to locate the equivalent keys in their chosen platform and map the semantics accordingly.

When to Reach for a Dedicated Memory Service

Simple INSERT/SELECT patterns work for prototypes and low‑traffic agents, but production systems often outgrow inline tables. Consider migrating to a dedicated memory service when any of the following become true:

In each case the migration path typically involves exporting existing agent_memory rows into the new service’s format, updating the agent’s write/read hooks to target the new endpoint, and pruning the old table once invariants are verified. The concrete commands for that export vary – pg_dump + psql to a Pinecone/Weaviate/Qdrant import format, a curl batch of JSON lines to a RedisJSON cluster, or a docker cp of a SQLite file into a Cloud‑SQL instance – but the logical pattern of “dump → transform → load → validate” is universal.

Summary

Agent memory is the bridge between a stateless LLM call and a stateful, context‑aware application. The concrete mechanisms – inserting turns into a relational or vector‑enabled store, retrieving them by exact match, time, or similarity, and pruning them with TTL or size caps – are expressible with standard tools (psql, curl, systemctl‑managed cron jobs) and generic SQL/HTTP patterns. The sharp edges – embedding drift, concurrent‑write races, metadata bloat, vector‑store mis‑configuration, and TTL granularity – are not obvious from the happy‑path code but are the reasons production agents suddenly “forget” or “confuse” prior context. Treat configuration keys as orthogonal knobs (TTL, turn cap, embedding dimension, similarity metric) rather than product‑specific flags, and migrate to a dedicated memory service only when scale, cross‑client continuity, or index‑freshness demands it.

This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.