How to Migrate Agent Memory: Import Existing User History Into a New Memory Layer Without a Gap

AI Agent MemoryLLM Cost & ProductionAgent Evals & ObservabilityGaurav Dadhich18 November 202617 min read
How to Migrate Agent Memory: Import Existing User History Into a New Memory Layer Without a Gap
On this page
  1. Define "no gap" before you touch data
  2. Raw chats, extracted facts and profile records load differently
  3. Rules for every import
  4. One import loop that works against any memory layer
  5. Getting data out: what Mem0, Zep, Letta and Cognee document
  6. Cutting over without a gap
  7. Checks to pass before you move reads
  8. A new embedding model means re-embedding every memory
  9. Migrate only for a failure you can reproduce
  10. Frequently asked questions

Published 18 November 2026. Every vendor behaviour described below was read from that vendor's own documentation on 18 November 2026.

Migrating agent memory is a data migration with one unusual constraint: the new store does not hold your records, it holds conclusions drawn from them, and those conclusions depend on when each thing was said and in what order. Get the order or the dates wrong and the import succeeds on every count you check while the agent quietly believes the wrong things. A user who said "I moved to Berlin" in March and "I live in Lisbon" two years earlier will, after a careless import, be told both are true, and a message saying "I hurt my knee yesterday" will be filed under the day you ran the script.

The method that avoids this fits in one paragraph. Sort the history you have into raw conversations (which need extraction), already-extracted facts (which load as written) and structured profile records (which mostly stay in your database). Send every record with the time it originally happened, import each user's history oldest first, send one session per call with both sides of the conversation, key every write to its source id so a crashed run can resume, and drop secrets and data you would not collect today before anything is written. Then switch with dual writes from day one, a background backfill of everything before that day, a side-by-side comparison of answers on real questions for a sample of users, reads moved over in stages, and the old store kept read-only until you are sure you will not roll back.

Mem0 published a good version of this recipe on 17 November 2026, with its last section written for Mem0's SDK. The method itself is vendor-neutral, and migrations usually fail on parts that recipe leaves out: getting data out of the old vendor, what a target does with a timestamp you pass, deletions and corrections that arrive mid-migration, a test list you can run before moving reads, and what changes when the embedding model changes.

Define "no gap" before you touch data

Define the bar before you touch data, because "the import finished" is not it. A migration has no gap when, for any user, a question the agent asks of memory on the first day after cut-over returns the same answer it would have returned from the old system, or a better one you can explain, with no stretch of time in which a new message reached one store and not the other.

That definition gives you two things to measure. Answer parity is a test over questions, so write the questions before the import (see the checks further down). Write continuity is a property of the cut-over plan, so it is settled by dual writing, not by how fast the backfill runs. Supermemory's guide to switching memory infrastructure makes a related point worth adopting: write the acceptance criteria before you see the new system's answers, and start from a failure in the current system you can reproduce, since that failure is usually why you are migrating at all.

Raw chats, extracted facts and profile records load differently

Raw conversation history is chat logs, sessions, voice transcripts, support tickets and journal entries. It has no memories in it yet, so it goes through the new system's extraction path, which reads the conversation and writes facts, preferences and events. This is the expensive path, because extraction usually means a model call per session, and it is the path where order and timestamps matter most.

Already-extracted facts are a table of user facts you built in-house, memories in another vendor's account, or a previous memory system's export. Load these as written, through whatever verbatim or no-inference write the target offers. Re-running extraction over a fact produces a summary of a summary, and detail goes missing each time, which is the same loss Mem0's post warns about.

Structured profile records are onboarding answers, plan settings, account fields and a list of completed lessons or orders. Most of this should stay in your database and be read from there, because a database row is already exact and already queryable. Copy into memory only what the agent should bring up in conversation without a lookup, such as "prefers to be contacted in Spanish", and leave the plan tier and billing date where they are.

If you have both raw chats and the facts already extracted from them, pick one source per user. Loading both gives you two copies of most facts in slightly different words, and the target's deduplication will catch exact repeats at best. The usual choice is the extracted facts for history older than some cut-off and the raw chats for recent history, where the new system's extraction is likely to be better than the old one's.

Cognee's migration documentation names this choice explicitly with three import modes: re-derive re-extracts raw content with Cognee's own pipeline, preserve maps the source's existing entities and facts in with no model calls, and hybrid keeps the source's graph and re-extracts the raw content as well. Whatever system you move to, decide which of those three you are doing for each kind of history and write it down, because it changes the cost, the run time and which checks apply.

Rules for every import

Keep the original time on every record

Pass the time each message was sent, or each fact was first written, with every record. Without it, the target dates everything at ingestion time, and relative phrases resolve against the wrong day. Zep's batch ingestion documentation says so directly: an item sent without a reference_time "is dated at ingestion time", while one sent with it sets the valid_at and invalid_at on the facts extracted from it. Mem0's add call takes a timestamp in Unix seconds for the same reason.

Then check what the target does with that time, because "accepts a timestamp" covers two different behaviours. In one, the time becomes the record's own date, the one the system reasons with when it resolves "yesterday", orders facts and answers "what changed last month". In the other, the time is stored as a metadata field beside a record that is dated today. The second is fine for filtering and useless for reasoning. Supermemory's documented import from Mem0, for example, writes the original created_at into the memory's metadata alongside a source: "mem0" tag. Vendors also change this behaviour: Zep's changelog for 25 July 2026 records that, before that release, episodes and facts derived from backfilled messages were dated when they were ingested rather than at the created_at supplied. Import one old session, read back the stored memory and look at its date before you run the whole backfill.

Store times in UTC with the offset kept, since a message sent at 23:30 in one zone is a different day in another and "yesterday" depends on it.

Import each user's history oldest first

Later statements correct earlier ones, and most memory systems decide what a new fact replaces by comparing it with what is already stored. In date order, "I moved to Berlin" arrives after "I live in Lisbon" and supersedes it. In reverse order, or in random order, the two land unlinked and a question about where the user lives can return both.

Parallelise across users, not within one. Each user's records go through in a single ordered stream; a thousand users can run at once. Watch the order of whatever you are reading from: Zep's graph read documentation states that graph.episode.list "returns the newest episodes first", so an export built on it has to be sorted before it is replayed into anything else.

Send one session per call, with both sides

One call carries one timestamp, so one call should carry one session. For long single-thread histories, such as a coaching chat that never closes, split by day. Include the assistant's turns: "ok" means nothing on its own, while "ok" after "shall I move your call to Thursday?" is an agreement the memory should keep. Check how the target treats roles, because some verbatim write paths keep user and assistant messages and drop system messages, and an assistant turn sent down a verbatim path can end up stored as a memory about the user, which Mem0's post documents for its own infer=False mode.

Make the import idempotent on source ids

Backfills crash halfway. Give every record a stable key from the source system, such as the session id or the old memory id, and keep a ledger keyed on (source_system, source_id) that records whether it was written, skipped by policy or failed, and the id the target assigned. A rerun reads the ledger and sends only what is missing. Supermemory's guide adds the reason this mapping outlives the migration: later corrections and deletions need an explicit target in the new system, and the source id is how you find it.

Do not rely on the target's duplicate detection as the idempotency mechanism. Mem0's post notes that a verbatim write of exactly the same sentence returns the existing memory, while a slightly different wording ("half-marathon" against "half marathon") becomes a second memory, which means a rerun of an extraction-based import can produce near-duplicates the target will not catch.

Treat import as a filter, not a copy

Two years of chat logs hold things you would not choose to store today: a card number pasted into a refund request, a password, a one-time code, a message about a relative's diagnosis. Import is the one moment you read every record anyway, so it is the cheapest place to drop them. Run deterministic filters first (card number patterns, credential formats, API key prefixes), then the target's extraction rules for the softer cases, such as "do not store health information about people other than the user".

Import is also a data protection checkpoint. The GDPR's Article 5 requires personal data to be "adequate, relevant and limited to what is necessary" for its purpose and kept "for no longer than is necessary", and a migration that copies everything forward because it was there fails both tests. Two practical rules follow: honour retention limits during the import (if your policy deletes chats after 18 months, do not import the 24-month-old ones), and re-apply every erasure request you have already processed, because a backup or a raw log export can still contain data a user asked you to delete. The full treatment of erasure across derived facts, embeddings and backups is in our guide to GDPR-compliant agent memory.

Keep identity and scope exact

Map every user, tenant, agent and session id from the old system to the new one before the first write, and import with the same user id where you can. A memory written under the wrong scope is worse than one not written, because it can surface for another user. Cognee's documentation lists user, agent, session and run ids, along with created and updated times, as the fields to preserve where the source has them.

One import loop that works against any memory layer

The backfill has the following shape, with the target's client hidden behind two calls so the same loop works against any memory layer.

from datetime import timezone

def import_user(user_id, target, ledger, policy):
    """Backfill one user's history, oldest first. Safe to rerun."""
    items = load_history(user_id)                 # extracted facts and/or raw sessions
    items.sort(key=lambda it: it.occurred_at.astimezone(timezone.utc))

    for it in items:
        key = (it.source_system, it.source_id)
        if ledger.is_done(key):
            continue                              # written on an earlier run

        clean = policy.scrub(it)                  # drop secrets, expired or erased data
        if clean is None:
            ledger.mark(key, "skipped_by_policy")
            continue

        meta = {"source_system": it.source_system, "source_id": it.source_id}
        if it.kind == "session":                  # raw chat: both roles, one session per call
            res = target.add_conversation(user_id, clean.messages,
                                          occurred_at=it.occurred_at, metadata=meta)
        else:                                     # already-extracted fact: load as written
            res = target.add_verbatim(user_id, clean.text,
                                      occurred_at=it.occurred_at, metadata=meta)

        ledger.mark(key, res.status, target_id=res.id)   # "pending" if extraction is async

Two details matter once this runs at volume. Extraction is often asynchronous: Mem0's default add returns an event with status PENDING, and Zep processes batches in the background, so the ledger needs a second pass that polls each pending job and resends the ones that did not succeed. And every vendor has rate limits and per-call caps (Zep's batch page lists up to 350 items per add_items call, 50,000 items per batch and 10,000 characters per episode), so pace the loop to them and budget for the model calls that extraction makes.

Getting data out: what Mem0, Zep, Letta and Cognee document

Every migration starts with an export, and most guides skip it. Four memory systems document the following ways out as of 18 November 2026; check your own vendor's docs for the equivalent before you plan anything else.

SystemDocumented way outWhat to watch
Mem0get_all with filters, paged; or create_memory_export with a schema you define, fetched later with get_memory_exportThe schema export is asynchronous and returns data shaped to your schema, so ask for id, content, metadata and created_at explicitly. Mem0's post notes that "superseded" links between facts do not carry over when you copy memories one by one.
ZepPaged list methods: graph.node.list, graph.edge.list, graph.episode.list, with page_size from 1 to 100 and a cursorNo dedicated export call; the docs name the list methods as the way to export a graph. Episodes come back newest first.
LettaAgent File (.af): GET /v1/agents/{agent_id}/export, or export_file in the SDKContains memory blocks, message history, tools and model settings. Archival memory passages are listed as planned rather than included, and secrets are set to null on export.
Cogneecognee.export(..., format="cogx") to a directoryA graph-only restore with index_vectors=False limits retrieval to keyword and graph search until vectors are rebuilt.

Three habits apply whatever the vendor. Export the raw conversations from your own application logs as well as the memories from the vendor, since raw history is the only thing you can re-extract from if the memories turn out to be poor. Run a small round trip (export ten users, import them, read them back) before the full export, because a text export can drop relationship types or validity dates, as Supermemory's guide notes. And never treat a vendor's statement that you own your data as proof that the export format holds everything you need.

When the source keeps fact history (a fact marked as replaced, or an edge with a validity window), decide whether the new system needs the history or only the current state. If only the current state, export current facts only and you avoid importing stale ones as live. If the history matters, import the old version and the new one in order so the target can link them, and test that it did. How revisions and supersession should be stored once they are in is covered in our post on agent memory versioning.

Cutting over without a gap

Dual write from day one. Before the backfill starts, every new message goes to both systems, and the old system keeps serving reads. The day dual writing starts is the backfill's upper bound, so no message falls between the two.

Backfill in the background. Run the import loop over everything before that day, per user, oldest first. The new system now has the past from the backfill and the present from dual writes.

Make deletions and corrections reach both. Dual writing usually breaks on this step. A user who asks to be forgotten, or corrects a fact, during the migration window has to have that change applied in both stores, and a deletion that lands before the backfill reaches that user's history has to be honoured by the backfill too, which is another job for the ledger. Supermemory's guide is right to add that if a rollback restores an older snapshot, it must not bring back data deleted after the snapshot was taken.

Compare answers on real questions. Take a sample of users (Mem0 suggests 30 to 50) and the questions your agent actually asks memory every session, such as "what is this customer's current plan?" or "any open complaints?", and run them against both systems. Read the answers side by side, then score them against the acceptance criteria you wrote first. Keep the answering model and prompt the same on both sides so you are comparing memory and not generation, and make sure the comparison path cannot trigger a real action such as sending an email.

Move reads in stages. Switch reads for one cohort, watch the metrics and support tickets for that cohort, then move the rest. A feature flag per user or per tenant is enough.

Keep the old store read-only for rollback. Stop writing to it only after reads have been on the new system long enough to trust (Mem0 suggests a few weeks), and keep it read-only, not deleted, until then. Then delete it on a date you have written down, since a forgotten copy of personal data is a retention problem in its own right.

Checks to pass before you move reads

These are written to pass or fail, so each one can sit in CI or a migration runbook. A wider test plan for memory, with metrics and pass bars per behaviour, is in how to test agent memory.

CheckHow to run itPass
Record countsCompare ledger counts (written, skipped by policy, failed) per user against source countsEvery source record is accounted for; failed is zero
Silent dropsCount images, files and system messages in the source and look for them in the targetKnown skips are in the ledger, not missing without trace
Original datesRead back the oldest and newest memory for 20 usersStored date equals source date, not import day
Relative timeImport a session containing "yesterday" with its real dateMemory resolves to the real date
SupersessionFor a user whose fact changed (address, plan, preference), ask for the current valueOnly the latest value comes back
DuplicatesSearch for the five most common facts per userOne memory each, not two wordings
ScopeAsk user A's questions while scoped to user BNothing from A
Filtered dataSearch the target for card number patterns, credential formats and erased usersNo hits
Deletion parityDelete a test user's fact mid-migrationGone from both stores and from the backfill
Answer parityReal questions for the sample cohort, both systems, same modelMeets the criteria you wrote before the import

A new embedding model means re-embedding every memory

Swapping the embedding model, whether as part of a vendor move or on its own, is a re-index, and it cannot be done in place. Vectors from different models live in different spaces; Zilliz's explanation puts it plainly that "there is no in-place transform that makes the old vectors valid", and that a mixed index returns neighbours from the wrong neighbourhood. Every memory has to be re-embedded from its text, which is one more reason to make sure the text, not only the vector, survives the export.

Qdrant's migration tutorial follows the same pattern as the cut-over above: create a new collection for the new model, dual write to both, backfill by re-embedding each stored record's text, then switch searches (ideally by repointing an alias) and change the query model at the same moment. Before switching, it recommends running the same labelled queries against both and comparing Recall@10, MRR and nDCG@10, and looking at the queries that regressed most rather than only the averages, because a new embedding model "is not automatically better on your data". It also warns that once the old collection stops receiving writes, rolling back loses everything written since, so keep dual writes on until you are sure.

If your memory layer is managed and the vendor changes its embedding model, ask how it re-indexes, and run the parity check on your own questions after the change.

Migrate only for a failure you can reproduce

A migration costs export work, extraction spend, a period of running two systems and engineering time on the cut-over, and only those future costs belong in the decision. The reason to move is a failure you can reproduce in the current system (a corrected preference that keeps coming back, a fact that never makes it across sessions, retrieval that misses a latency budget) and evidence that the new system fixes it on your data. If the pilot on one workflow does not show that, staying is the right answer. If it does, the method above keeps users from noticing the move. If the destination is Maximem Synap, it runs real import jobs from other memory providers with field mapping and readback verification.

Memory portability for end users, moving what ChatGPT or Claude knows about you to another assistant, is a related but different problem; our piece on AI memory portability covers it.

Frequently asked questions

How do I migrate agent memory to a new provider without losing context?

Dual write every new message to both systems from day one, backfill all earlier history in the background with original timestamps, oldest first per user, then compare answers on real questions for a sample of users before moving reads in stages. Keep the old store read-only until you are confident you will not need to roll back.

Should I re-extract memories from raw chats or import the extracted facts as they are?

Import already-extracted facts as written, because re-extracting a fact produces a summary of a summary and loses detail. Re-extract from raw chats when the new system's extraction is better than the old one's or when the old facts are poor. Do not load both for the same period, or you get duplicates in different words.

Why does import order matter for agent memory?

Memory systems decide whether a new fact replaces an old one by comparing it with what is already stored. Importing a user's history oldest first lets the later fact supersede the earlier one; importing out of order leaves both stored as if both were current.

What happens if I import chat history without timestamps?

The memory system dates every record at ingestion time, so "yesterday" resolves to the import day and date filters return the wrong results. Zep's documentation states that items without a reference time are dated at ingestion. Pass the original time with every record and check that the target uses it as the record's date, not only as metadata.

How do I export memories from Mem0, Zep or Letta?

Mem0 documents get_all with paging and a schema-based create_memory_export. Zep documents paged graph.node.list, graph.edge.list and graph.episode.list calls as the way to export a graph. Letta exports an agent as an Agent File through GET /v1/agents/{agent_id}/export, which does not yet include archival memory passages.

Do I need to re-embed everything if I change embedding models?

Yes. Vectors from different embedding models are not comparable, so every stored memory has to be re-embedded from its text into a new index, then searches switched over once retrieval quality on your own labelled queries is at least as good.

From the team at Maximem

Stop rebuilding agent memory from scratch

Maximem Synap is the context management layer we built after hitting every problem in this post ourselves. Persistent recall across sessions, entity resolution and conscious forgetting, in Python, TypeScript and REST.

Looking for more to read? See our directory of the best engineering blogs to follow.