BUILD · 5 MIN READ

Use PostgreSQL and pgvector for agent memory

Keep explicit facts, metadata, and vector retrieval close to application data.

Download example files Code + setup + checks in a ZIP
Jump to a section 9 sections

EXAMPLE USE CASE

Retrieve a user preference beside relational application data

An application already uses PostgreSQL and needs searchable preference records with explicit ownership.

Input
A tenant-scoped memory row, its toy vector and a query vector of the same dimension.
Expected output
The matching preference and cosine distance from a filtered SQL query.
  • Success check: The returned content belongs to the selected tenant; dimension mismatches fail visibly.
  • Try a failure: Add an equally close other-tenant row and verify that the query filter excludes it.

Example scope: A three-dimensional pgvector SQL demonstration. Real embeddings, application roles and row-level security require their own setup.

PostgreSQL examplepgvector example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
candidateapprovedretrieverecallcontextmaintainConversationAuthenticated subjectMemory policyExtract and validatePostgreSQL + pgvectorScoped durable recordsRelevant queryScope before rankingSelected contextSmall evidence setCorrection + expiryPropagate changes
  1. Resolve tenant, user, and thread from the application session.

  2. Decide which supported facts or preferences can be retained.

  3. Store content with provenance, subject, timestamps, and a lifecycle policy.

  4. Retrieve only data the authenticated subject is permitted to access.

  5. Rank useful memories within a context budget; do not include every past conversation.

  6. Correct conflicting facts and remove expired or deleted records from derived stores.

PostgreSQL + pgvector

Store content with provenance, subject, timestamps, and a lifecycle policy.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Separate the records

  • Store messages, checkpoints, user facts, and knowledge chunks in tables with explicit ownership and retention fields.
  • PostgreSQL provides the relational store; pgvector adds vector types and similarity operators.
  • The application still decides what becomes a memory.

A tiny SQL example

  • This example uses three-dimensional toy vectors to illustrate the query shape.
  • A real embedding column must match the dimensions of your embedding model.
  • The pgvector extension must already be installed on your PostgreSQL server.
SQL · demonstration schema
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE agent_memories (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tenant_id text NOT NULL,
    content text NOT NULL,
    embedding vector(3) NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO agent_memories (tenant_id, content, embedding)
VALUES ('demo', 'Prefers concise answers', '[0.2,0.8,0.1]');

SELECT content, embedding <=> '[0.1,0.9,0.2]' AS distance
FROM agent_memories
WHERE tenant_id = 'demo'
ORDER BY distance
LIMIT 3;

Educational example. Uses your configured environment and credentials; no paid model call is made by this website.

Enforce the real boundary

  • The sample filter illustrates scoping.
  • In an application, use parameterized queries and derive the tenant identifier from authenticated context.
  • Apply database access controls or row-level security with properly configured roles.
  • Evaluate retrieval recall with your actual filtering and index settings.

Set up the lab

  • Install Docker; this container is an isolated local demonstration database.
  • Save the SQL example as memory.sql. It uses toy vectors with three dimensions.
Shell
docker run --name asg-memory -e POSTGRES_PASSWORD=local-demo-only \
  -p 127.0.0.1:5432:5432 -d pgvector/pgvector:pg17

Run and verify

Shell
docker exec -i asg-memory psql -U postgres -v ON_ERROR_STOP=1 < memory.sql
  • The query returns the demo preference and a cosine distance.
  • Insert a different tenant and verify that the original tenant filter excludes it.

Troubleshooting and failure tests

  • Extension not found: use a PostgreSQL image or server with pgvector installed.
  • Dimension mismatch: regenerate embeddings or create a column matching the embedding model; do not silently truncate vectors.

Before production

  • Use parameterized SQL and a restricted application role. A WHERE clause in copied SQL is not a complete authorization design.
  • Test row-level security with the actual non-owner application role, then benchmark filtered retrieval and deletion.
  • Back up source records and metadata; rebuild derived vector indexes from the source of truth.

Keep exploring

A layered architecture for agent memoryAdd a dedicated memory layer with Mem0