Note 10 / LLM / Backend / Postgres
Long-term memory for an LLM chat backend without losing the prompt cache: fold in blocks, claim before you write
A sliding window that drops one message per turn gave a 0 token cache hit. Moving the window in blocks and folding old turns into memory in the background brought it to 88 to 94 percent. The claim, retry and forgetting rules that keep that background job honest.
- By
- Trần Thế Anh, Software Engineer
- Published
- Work done
- October to November 2026, companion chat backend (NestJS, Postgres, BullMQ)
- Stack
- NestJS, BullMQ, Postgres with pgvector, OpenRouter (Qwen)
- Reading
- 6 min, 1,246 words
A chat product that talks to the same character for months cannot send the whole history on every turn. The obvious fix is a window of the last N messages, and the obvious way to implement it is to slide it one message at a time. That one choice can switch off prompt caching completely. This note explains why, how moving the window in blocks fixes it, and the rules around the background job that turns old messages into memory. The constants below come from one NestJS companion-chat backend; the cache measurement was taken on a second companion app. The snippets are rewritten illustrations.
Why a sliding window defeats the cache
Provider prompt caches match on a prefix: the cache hits when the start of this request is byte-identical to the start of a recent one. A window that drops the oldest message and appends a new one each turn changes the first message every time. The prefix, system prompt included, never matches the previous request.
That is what a measurement on the second app showed on 2 November 2026 (lesson BL-978 in my log): with a one-message slide, cached tokens were 0, even for the system prompt. Keeping the head of the window fixed and appending new turns gave 88 to 94 percent cached.
Move the window in blocks
The rule that came out:
- The prompt contains every turn after a marker,
memory_covered_until, up to a maximum (HISTORY_WINDOW = 20turns). - A turn is one reply from the character, which can be several short chat bubbles.
- While the window has room, new turns are only appended. The prefix is stable.
- When the window reaches the maximum, a background job folds the oldest turns into memory and moves the marker so that the newest
HISTORY_WINDOW_MIN = 12stay. The head moves once, by about eight turns, then stays still again for the next eight.
So the prefix changes about once every eight turns instead of every turn. Things that change on every turn (recalled memories, the current time, a note to the model) go after the last cache point, never in the system prompt.
One more rule: log cached_tokens and the cache-write count on every turn. Until you read them, you do not know whether you are caching.
An open point from my notes: Qwen models through OpenRouter may need an explicit cache_control: { type: "ephemeral" } on a content block. The endpoint metadata said implicit caching was unsupported, while the 2 November measurement showed hits without it. Those two contradict each other, and I did not resolve it. Measure the model you use.
What the fold produces
The fold job reads the oldest turns and writes three things: a short summary, a small set of facts about the user, and recall items, each of which is a sentence with an embedding. On each later turn the backend embeds the latest user message (with the two before it), picks the top six items by cosine similarity above a floor, and puts them after the cache point, capped at about 1,400 characters.
Recall has its own failure rule. The query embedding has a 1.5 second deadline, and an error returns an empty list with a warning in the log. Chat goes on without memory for that turn rather than failing.
Claim before you fold
Two folds for the same chat must not run at once. A user can also edit memory while one is running. The claim is a single guarded update:
UPDATE chats
SET memory_updating_since = $now
WHERE id = $chat
AND (memory_updating_since IS NULL
OR memory_updating_since < $now - interval '120 seconds')
RETURNING id;
No row back means someone else holds it. The 120 seconds lets a crashed worker’s claim expire. At save time the job opens a transaction, runs SELECT ... FOR UPDATE on the chat row, and checks that the claim is still its own (memory_updating_since = $claimedAt). If not, it drops its result.
The claim is also the tool for edits: when the user changes or deletes a memory entry, the edit drops any running fold’s claim (a dropRunningFold call in the same transaction). Otherwise the fold, which read the old text, would write it back over the edit.
Throw on bad output so the queue retries
The fold is a BullMQ job. These cases throw instead of saving: the model call failed, the answer was cut off by the token limit, the JSON did not parse, an item embedding failed, or the answer is empty where memory existed before. The last case is the important one. An empty result is a broken answer, not an instruction to forget everything. The previous memory stays, and the retry gets another chance. A failed job also sets a cooldown (600 seconds) before a new one is queued for that chat.
Do not store what the character made up
The fold reads the character’s lines as well as the user’s. A model that invented a story about its own past in an earlier turn will, if you let the summariser store it, treat it as fact from then on and repeat it. The prompt tells the fold to keep only things about the user and things both sides really said, and never the character’s invented life, scenes or dates. That came from a recorded bug (BL-1313).
For sensitive categories, a prompt alone is not enough: a Qwen model stored them despite instructions in production on 2 November 2026. So there is also a regex filter on the server that drops health, sexuality, religion, politics, addresses, documents, passwords, money, signs of a minor, and instruction-shaped sentences (“from now on …”) before anything is saved. Stored text also has < and > removed, and when it is put into a prompt it sits inside tags with a line saying it is data and not instructions.
Dates: absolute in, relative out
“Tomorrow” stored as the word tomorrow is wrong forever. The fold prompt asks for absolute dates when storing (“on 2026-11-26”), and the prompt builder turns them into relative phrases (“3 days ago”) when reading. Whether each backend does this fully is something I did not check again, so treat it as an item to verify in yours.
Forgetting on request
When a user deletes or rewrites an entry, recall items that mean the same thing also have to go, or the character mentions the deleted fact next turn. The rule used: delete stored items with cosine similarity 0.75 or higher to the old text. If embedding fails, or takes longer than 3 seconds inside the user’s request, fall back to keyword overlap: items that share at least half of the old text’s keywords. A newly written item with cosine 0.9 or more to an existing one rewrites it instead of adding a near-duplicate.
What I have not verified
I read the constants file of the NestJS backend and the notes that go with the memory service. I did not run them or repeat the cache measurements while writing this. The 88 to 94 percent figure and the Qwen behaviour are quoted from my own measurements and lessons log, on one model and one provider on one date, and they will not transfer unchanged to another model. The numbers like 20, 12 and 0.75 are what these apps use; the similarity floor for recall was noted as not yet calibrated on real chats.