TUTORIAL17 min read

ClickHouse for Agent Memory: Build Fast Context Retrieval

Build a scoped, versioned memory store in ClickHouse, then test retrieval speed, tenant isolation and stale-state handling.

P
PADISO teamPublished 16 Nov 2026

ClickHouse for agent memory can bring conversation events, structured state and vector search into one SQL-backed system. This tutorial builds a scoped memory table, writes new and superseding facts, retrieves relevant context, and checks whether the design is both fast and correct. Start with the AI agents and automation service if you are designing a production agent and need to weigh the storage choice against the rest of its runtime.

The point is not to replace every vector database. As detailed in the case against external vector databases for agent memory, ClickHouse is worth testing when your agent memory needs structured filters, frequent writes, auditability and analytics alongside semantic retrieval. It may not be the right fit when your only requirement is a highly tuned, low-latency vector lookup with a small, stable dataset.

The goal here is a working prototype for persistent, multi-session memory. You will define what the agent can remember, store each change as a new version, filter by tenant and session, and measure real query behaviour instead of assuming that an index guarantees a latency target.

What are you building, and what do you need?

The example is a support agent that remembers useful facts about a customer and a conversation. A memory might say that a customer prefers email, that a booking was cancelled, or that a particular issue is still unresolved. The system must retrieve relevant facts without returning another customer’s memory or treating an old fact as current.

You need:

  • A ClickHouse deployment that supports the table engine, SQL functions and vector index syntax you plan to use. Check the ClickHouse approximate vector search documentation for the version you run.
  • A query embedding from your chosen embedding model. Its vector dimension must match the table and index definition. The SQL below uses 1,536 dimensions as an example, not as a recommendation for every model.
  • A client that can insert rows and send a query vector as a typed parameter.
  • A small test set with several users, sessions, active facts and superseded facts.
  • A way to inspect query plans and record latency, such as your client instrumentation plus ClickHouse query logs.

For production work, also decide where data will be hosted, who may read it, how long it should remain, and how a user’s information can be erased. Those are design requirements, not details to leave until after the retrieval demo.

This example uses ReplacingMergeTree(version). It is an append-oriented design: when a fact changes, insert a newer row with the same key and a larger version. It is not a magic instant-update mechanism. Background merges eventually consolidate parts, and queries that need the latest version must account for that behaviour.

Step 1: Choose the memory unit and scope

Before creating a table, settle what one row means. Here, one row represents one named fact for one organisation, user and session. The stable identity is the combination of org_id, user_id, session_id and memory_key.

For example, memory_key = booking_status_4821 can represent the status of a particular booking. If it changes from active to cancelled, insert a new version using the same key. Do not make the status itself part of the key, or the old and new status will look like unrelated facts.

A useful memory row separates four concerns:

  • Scope: organisation, user and session identify whose context this is.
  • Identity and version: memory_key identifies the fact; version orders its changes.
  • Lifecycle: status says whether the fact is active, superseded, contradicted or archived.
  • Retrieval material: content, tags and embedding support different ways to find it.

Keep durable user preferences distinct from temporary working state. A short-lived checkpoint of a tool call has different retention and retrieval needs from a preference that should carry across sessions. You can keep these in separate tables, or add an explicit memory class and enforce different policies. Do not silently make every conversation turn a permanent memory.

The ORDER BY key below starts with organisation, user and session. ClickHouse uses this sorting key to organise data and skip ranges during queries. Put the fields you filter on consistently near the beginning. A table ordered for per-session recall will not necessarily be ideal for global analytics, so test both important access patterns.

Step 2: Create a versioned memory table

The following schema follows the pattern in ClickHouse’s Loom agent memory announcement and the supplied production schema. Confirm the vector-index syntax against your deployed ClickHouse version before using it. Index support and syntax can change, and a declared index is not proof that a particular query will use it.

CREATE DATABASE IF NOT EXISTS agent_memory;

CREATE TABLE agent_memory.session_state
(
    org_id LowCardinality(String),
    user_id String,
    session_id String,
    memory_key String,
    version UInt64,
    status Enum8(
        'active' = 1,
        'superseded' = 2,
        'contradicted' = 3,
        'archived' = 4
    ),
    content String,
    embedding Array(Float32),
    tags Array(LowCardinality(String)),
    created_at DateTime64(3, 'UTC') DEFAULT now64(3),
    updated_at DateTime64(3, 'UTC') DEFAULT now64(3),
    INDEX idx_emb embedding
        TYPE vector_similarity('hnsw', 'cosineDistance', 1536, 'f32', 32, 256)
        GRANULARITY 2,
    INDEX idx_tags tags TYPE set(100) GRANULARITY 2,
    INDEX idx_content content TYPE tokenbf_v1(10240, 3, 0) GRANULARITY 2
)
ENGINE = ReplacingMergeTree(version)
ORDER BY (org_id, user_id, session_id, memory_key)
SETTINGS index_granularity = 8192;

The vector index uses HNSW, a graph-based approximate nearest neighbour method. Approximate means it can return a close set of candidates without comparing the query to every vector. The tokenbf_v1 and set definitions are skipping indexes. They can help ClickHouse avoid reading some granules for eligible filters; they do not guarantee that every text or tag query becomes fast.

The example stores vectors as Array(Float32). Ensure your embedding service always returns the expected number of values and the same model family for a given index. Mixing vectors from incompatible models can make distance scores meaningless even if the dimensions happen to match.

For a real workload, decide whether the embedding belongs on every version of a fact. Keeping it on each version makes inserts simple and preserves the exact content-vector pair. It also means every rewrite stores another vector. If facts are rewritten often, measure the storage and ingest cost, and consider whether your application should avoid re-embedding unchanged text.

What should you see?

The database should accept the table definition and show the table in agent_memory. If it rejects the vector index definition, check the documentation for the exact server version and feature availability before changing the query. Do not quietly remove the index and assume your benchmark still represents indexed vector search.

Check the table metadata and engine:

SHOW CREATE TABLE agent_memory.session_state;

Confirm the engine is ReplacingMergeTree(version), the sorting key matches the intended scope, and the vector dimension in the index agrees with your model. If the production access pattern spans sessions, do not assume that the example’s session-first ordering is automatically optimal. Add representative data and compare plans before settling the key.

Step 3: Insert a small, testable dataset

Start with a few facts for two different users. Use your real embedding service to produce vectors in an application test. The placeholder below shows the shape of an insert, not a usable semantic vector. Do not copy a made-up vector into a relevance test and conclude that the model behaves well.

INSERT INTO agent_memory.session_state
    (org_id, user_id, session_id, memory_key, version, status,
     content, embedding, tags)
VALUES
    ('org_apac_101', 'usr_9981', 'sess_3342', 'contact_preference', 1,
     'active', 'Customer prefers email updates.', [/* 1536 Float32 values */],
     ['preference', 'contact']),
    ('org_apac_101', 'usr_9981', 'sess_3342', 'booking_status_4821', 1,
     'active', 'Booking 4821 is confirmed for Friday.', [/* 1536 values */],
     ['booking', 'status']),
    ('org_apac_101', 'usr_2044', 'sess_8810', 'contact_preference', 1,
     'active', 'Customer prefers phone calls.', [/* 1536 values */],
     ['preference', 'contact']);

In an application, send rows through a supported client using typed parameters or a bulk insert format. Validate each embedding before insertion. Reject the row or send it to a failure path if the dimension is wrong, a value is non-finite, or the source text was not prepared as expected.

For repeatable testing, build a fixture with facts that include:

  1. A clear semantic match to the query.
  2. A lexically similar but incorrect match.
  3. An older version of a fact that has since changed.
  4. A similar fact belonging to another user or organisation.
  5. An unrelated fact in the same session.

This dataset catches mistakes that a single happy-path query will miss. In particular, the wrong-user row is a basic tenant-isolation check, not just a relevance test.

Step 4: Supersede a fact with a new version

Do not use frequent ALTER TABLE ... UPDATE mutations as the normal way to change agent state. Insert a replacement row with the same sorting key and a larger version. For example, when a booking is cancelled, write the new state:

INSERT INTO agent_memory.session_state
    (org_id, user_id, session_id, memory_key, version, status,
     content, embedding, tags)
VALUES
    ('org_apac_101', 'usr_9981', 'sess_3342', 'booking_status_4821', 2,
     'active', 'Booking 4821 was cancelled by the customer.',
     [/* embedding for the new content */], ['booking', 'status']);

The previous fact is not overwritten at insert time. It remains part of the stored data until merges or query-time deduplication resolve which version is current. That history can be useful for audit and debugging, but it also means your read path must not treat every physical row as an active fact.

ReplacingMergeTree(version) chooses the row with the greatest version for a duplicate sorting key when replacement occurs. For an immediate query that must return the current version, use FINAL as in the retrieval example below, or implement and validate another deduplication strategy. FINAL has a cost. Measure it with your data size and concurrency rather than assuming it is free.

A newer row with status superseded, contradicted or archived should make that memory unavailable to ordinary active-context retrieval. The new row is a tombstone-like state: it records the change while allowing your query to exclude the fact. Keep the status vocabulary small and agree what each state means across the agent, ingestion service and support tooling.

Check that the newer version wins

After inserting version two, inspect the rows for that key with FINAL:

SELECT memory_key, version, status, content
FROM agent_memory.session_state FINAL
WHERE org_id = 'org_apac_101'
  AND user_id = 'usr_9981'
  AND session_id = 'sess_3342'
  AND memory_key = 'booking_status_4821';

You should see the newest version of that key, not both versions as separate current facts. Then insert a version three with status archived and confirm that your normal active retrieval no longer returns it. This tests lifecycle behaviour, not just sorting or vector search.

Use a monotonically increasing version per memory key. If two writers can update the same fact at once, define how they allocate versions or resolve conflicts. A timestamp may help order writes, but a timestamp alone does not resolve concurrent updates reliably. Your application should enforce one clear policy, such as a per-key sequence or a controlled write service.

Build the embedding for the current question using the same embedding model and preprocessing rules used for stored facts. Then pass it as a typed array parameter. The query filters organisation, user, session and active status before returning the closest matches:

SELECT
    memory_key,
    content,
    tags,
    cosineDistance(embedding, {query_vector:Array(Float32)}) AS distance
FROM agent_memory.session_state FINAL
WHERE org_id = 'org_apac_101'
  AND user_id = 'usr_9981'
  AND session_id = 'sess_3342'
  AND status = 'active'
ORDER BY distance ASC
LIMIT 5
SETTINGS vector_search_filter_strategy = 'prefilter';

Lower cosine distance means a closer vector match. The query returns at most five rows, but five is a starting point, not a universal context size. Your agent should use a relevance threshold or a measured context budget. If the best candidate is weak, it is safer to return no memory than to insert a plausible but unrelated fact into the prompt.

The prefilter setting asks ClickHouse to apply selective filters before vector work where supported by the execution path. That can reduce the candidate set for a user or session query. Confirm what the server actually does with your version, index and data distribution. ClickHouse’s vector search documentation describes the available search approach; the exact plan still depends on your query and table.

What should you see?

For a query such as “How should we send updates?”, the customer’s email preference should rank above unrelated facts. The other user’s phone preference must not appear, even if its vector is a closer semantic match. For a question about the booking, the cancelled state should be the only current version returned.

If results are wrong, check in this order:

  1. Scope filters: Are every tenant and user boundary present in the query? Are values supplied from authenticated application context rather than model-generated text?
  2. Version handling: Does the query use FINAL or a tested equivalent? Are version values monotonic and keys stable?
  3. Status handling: Is the query excluding inactive lifecycle states?
  4. Embedding consistency: Did the write and query use the same model and preprocessing? Does the vector have the expected dimension?
  5. Relevance: Does the test question actually express the fact you expect to retrieve? Try several phrasings.

Do not delegate access control to semantic similarity. The application must enforce tenant scope in the SQL request and in its authorisation layer. If the agent can construct its own SQL, constrain it through a controlled interface rather than relying on the prompt to behave.

Step 6: Add lexical and structured retrieval

Vector search is useful when wording differs. It is not always the best way to find an exact identifier, status or named entity. An agent asking about booking 4821 needs the exact booking fact, not a semantically similar booking. Structured filters and lexical search address a different problem from embeddings.

The schema includes memory_key, status and tags so the application can apply exact rules. A simple lexical filter can use ClickHouse text functions, alongside the same scope and lifecycle conditions:

SELECT memory_key, content, tags
FROM agent_memory.session_state FINAL
WHERE org_id = 'org_apac_101'
  AND user_id = 'usr_9981'
  AND session_id = 'sess_3342'
  AND status = 'active'
  AND hasToken(content, '4821');

For an exact business identifier, prefer a dedicated structured column over hoping it appears in text. For example, store a booking ID as a typed field and filter by equality. Use tags for controlled categories, not as a substitute for a well-designed schema. The text skipping index can help eligible token filters skip granules, but check that the query uses it and measure the result.

A practical hybrid approach is to retrieve candidates through separate routes, then combine and deduplicate them in your application:

  • Exact lookup for identifiers and business keys.
  • Filtered lexical lookup for names, codes and phrases.
  • Vector retrieval for paraphrases and concepts.
  • A final application step that removes duplicates, applies status rules and limits the context sent to the model.

You can also combine the routes in SQL, but make the scoring rule explicit. A distance score and a lexical match score are not naturally on the same scale. Do not add them together without normalising and evaluating the result. Build a small set of representative questions with expected relevant facts, compare retrieval results, and then choose a ranking method based on evidence.

For more on ClickHouse vector patterns, the Hacker News vector search example is a useful reference for testing search techniques on a dataset. Treat its workload as an example, not as a substitute for your own session-scoped benchmark.

Step 7: Prove the index and latency with a workload test

“Sub-second” is a target to measure, not a property you get by choosing ClickHouse. Run tests with your actual vector dimension, row count, filters, concurrency and write rate. Include cold and warm behaviour if both matter for your service. Measure p50, p95 and p99 latency, and record the query settings and server configuration alongside each result.

A ChistaDATA benchmark describes ClickHouse vector retrieval in the range of 85 to 120 milliseconds on a 10-million-vector dataset with metadata filtering, compared with more than 2,200 milliseconds for unindexed brute-force scans. Those are results for the benchmark setup, not a promise for your cluster. Read the ChistaDATA vector search performance notes and their technical analysis on optimizing ClickHouse vector search index configurations before using a number in a design decision.

Use this test sequence:

  1. Load representative rows, including multiple organisations and sessions. A dataset with only one tenant cannot test pruning or isolation properly.
  2. Run exact and vector queries with the same filters your application will use.
  3. Compare indexed and unindexed behaviour, if you can do so safely in a test environment.
  4. Inspect the query plan and query log. Confirm that the vector index and other expected skipping behaviour are being used where applicable.
  5. Increase the dataset and concurrency until you reach the expected operating range.
  6. Add writes and version replacements while queries run. Observe latency and resource use during ingestion, not just when the table is idle.
  7. Check result quality against known relevant facts. A fast query that returns stale or cross-tenant context has failed.

Do not take the number of rows returned as a proxy for the amount of work done. Sorting-key design, granularity, selectivity, data part layout and index settings all affect query work. ClickHouse can prune data by its sorting key, but only when the query conditions align with how data is ordered. Inspect plans and profile the actual request.

Record a baseline table with query type, data size, concurrent requests, p50, p95, p99, rows or granules read, and whether writes were active. That gives engineering a useful comparison when changing the embedding model, table order or index parameters. It also prevents a demo run on an idle local table from becoming an unexamined production claim.

Step 8: Plan retention, deletion and operational controls

Memory is user data. Decide what can be retained, who may retrieve it, and how a correction or erasure request flows through every copy. A new archived or superseded version changes what normal reads should return, but it does not necessarily erase the older physical row immediately. TTLs, merges, backups and object storage retention need their own policies.

For a deletion requirement, define the expected meaning of “deleted” with your privacy and security teams. It might mean immediately invisible to application queries, physically removed from the active store after a process, and eventually removed from backups under a documented schedule. Do not promise immediate physical erasure based only on inserting a new status row.

For regulated Australian organisations, map the design to your obligations and internal controls. Storage in ClickHouse does not by itself establish compliance with the Privacy Act, APRA requirements or an organisation’s security policy. Review access, audit trails, backup retention, incident handling and data residency with the relevant owners. PADISO works with teams on platform engineering and enterprise architecture when the question spans storage, deployment and control boundaries.

Operational checks should include:

  • Per-tenant access tests that try to retrieve another tenant’s data.
  • Schema and embedding dimension validation at ingestion.
  • Monitoring for insert failures, query errors and unexpected empty results.
  • Latency and resource metrics under concurrent reads and writes.
  • A process for fixing incorrect memories and preventing their retrieval.
  • A documented retention and deletion workflow that includes replicas and backups.

ClickHouse’s open-source Loom repository offers an agent memory and MCP server implementation to examine. You can inspect the Loom memory concepts specification for details on its underlying design. MCP, or Model Context Protocol, is a standard interface that lets AI applications call tools and access context. Treat Loom as a reference or starting point, not as a substitute for checking its current design, supported features and operating model against your own requirements.

When is ClickHouse a better fit than a dedicated vector database?

The choice is about the whole workload, not a blanket claim that one storage type is better. Dedicated vector systems may make sense when your dominant requirement is vector retrieval and their operational model fits your product. ClickHouse is compelling when the same memory service also needs SQL filters, append-oriented event history, analytics, audit queries and existing ClickHouse operations.

Requirement ClickHouse is worth testing when A dedicated vector service may fit when
Memory shape Rows have tenant, session, status and time fields Most access is vector similarity over a focused corpus
Writes You can model changes as versioned inserts The system needs a particular update or indexing workflow
Search Structured filters and semantic retrieval must work together Vector-only search dominates and its features match your needs
Analytics Engineers need SQL over agent events and state Analytics is handled elsewhere and should remain separate
Operations Your team can run and tune ClickHouse A managed vector service reduces operational burden
Latency Measured filtered retrieval meets the service objective Its measured latency and quality better fit the target

Do not compare a carefully tuned ClickHouse query with an untuned vector service, or the other way around. Use equivalent data, filters, embedding model, concurrency, freshness expectations and result-quality checks. Include the cost of operating each system and synchronising writes across them. A lower storage line item can be offset by engineering work or extra infrastructure.

ClickHouse Cloud pricing changes by configuration and region. Check the official pricing page alongside the ClickHouse Cloud billing overview for current rates rather than relying on an old estimate. For self-hosted deployments, include compute, storage, backups, high availability and the people needed to operate the cluster in your comparison.

Common mistakes to avoid

Treating approximate search as factual truth. Similarity ranks related text. It does not know which booking is current or whether a user has authority to see a memory. Apply structured identity, status and access filters before the model receives context.

Using a vector index as a replacement for a data model. Give important facts typed fields and stable keys. Keep exact IDs exact. Store lifecycle state explicitly. Embeddings support discovery; they should not be the only representation of operational facts.

Expecting replacing rows to disappear immediately. ReplacingMergeTree is designed around merges and versioned data. Use FINAL or another validated strategy where the latest state must be read immediately, and measure the cost.

Assuming every vector query uses the ANN index. A query can still scan more data than expected. Inspect the plan, confirm the feature is supported in your server version, and test with selective filters and production-shaped data.

Benchmarking only the read path. Agents write, supersede and invalidate memories while serving requests. Test the mix. A system that looks quick after loading a static dataset may behave differently during sustained ingestion.

Persisting every turn as durable memory. Conversation logs, working state and durable facts have different value and retention needs. Filter and summarise deliberately. Too much low-value context makes retrieval less useful and increases storage and embedding work.

Where PADISO fits

We help teams design and build agent systems, including the data and platform choices behind memory retrieval. Our AI automation work covers agent workflows and production controls, while embedded analytics is relevant when agent events and operational data also need to support reporting. A useful first step is to map one agent workflow, its memory types, access rules and retrieval tests before choosing the store.

The next step

Take the PADISO AI Readiness Test to identify the capability and governance questions to resolve before you move an agent memory prototype into production.

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