Keeping Context Across Long Conversations: Session Compression and Memory Management in Practice
A practical guide to keeping long LLM conversations coherent after they hit context limits. It compares sliding windows, retrieval, structured summaries, and layered memory, then describes a hybrid design built on rolling summaries and pinned constraints. It also covers evaluation methods and common pitfalls.
The Core Problem: Session Management Lacks Engineering Rigor, Not Model Memory
When a long conversation reaches its limit and the user has to start a new one, the usual reaction is “the model forgot everything.” From an engineering perspective, this is rarely a single model limitation. It results from the combined effects of the context window, the session lifecycle, front-end message handling, and back-end context assembly.
No matter how large a context window is, it has a boundary. Suppose the window holds 10M tokens. Content beyond that boundary still has to be trimmed. The goal, then, is not “infinite context” but a “sustainable session.” Within a finite window, the system should keep the information most valuable to the current task, and a new session should be able to recover the task state quickly.
Common failure modes include:
- The front end only appends messages linearly and fails only when the limit is reached.
- Simple trimming drops early messages, which causes goals and constraints to be lost.
- Summaries keep only a natural-language overview and discard structured details such as file paths, interface signatures, and error codes.
- A new session starts without backfilling state, so the model has to begin from scratch.
Four General Approaches: From Forgetting to Layered Memory
1. Sliding Window and Gradual Forgetting
The most direct approach keeps only the most recent 20 to 30 turns and ignores older messages. Its advantages are simple implementation, low latency, and predictable cost, which make it suitable for short tasks and quick Q&A. Its drawback is that early constraints, user preferences, and confirmed decisions are easily lost, and the model may then answer the wrong question.
A better approach pins the system prompt and key constraints so they are never removed as the window slides. Messages that fall outside the window can be condensed into a rolling summary that preserves goals, constraints, decisions, and open questions. This keeps context length under control while reducing the chance that critical information breaks off.
2. Full Retention with On-Demand Retrieval
This approach persists all conversation messages, but each request sends only the recent window plus the relevant historical fragments that retrieval returns. Historical messages can be indexed by metadata such as time, entities, task stage, and code files. Its advantage is that long-tail information is preserved, which suits long-running tasks. Its drawbacks are that effectiveness depends heavily on retrieval quality, and latency and consistency become harder to manage.
In practice, the system must separate information that must stay resident from information that can be retrieved. The current goal, hard constraints, and recent decisions should always stay in context. Historical discussions, earlier versions of a plan, and background material can be recalled on demand. Retrieved results should carry timestamps and sources so that an old decision does not override a newer one.
3. Conversation Compression and Structured Summaries
Compression replaces a long history with a shorter representation before sending it to the model. Common forms include summaries, vector storage with on-demand recall, compression with a smaller model, and structured state extraction. For programming use cases, a natural-language summary is not enough. The summary should also preserve file paths, function signatures, interface constraints, error logs, lists of changes, and open questions.
Compression is lossy, so the output needs verification. Check whether key entities are preserved, whether constraints conflict, whether open questions were dropped, and whether code interfaces remain consistent. Summaries should be editable and versioned, and they should be injected together with the recent window when a new session starts.
4. Layered Memory
A more complete approach uses layers. Working memory holds the most recent N turns. Episodic memory stores summaries of each stage. Semantic memory stores long-term facts and preferences. Task state stores goals, constraints, decisions, and to-do items. Each layer has its own lifecycle and retrieval strategy. A long conversation then stops depending on a single window and instead depends on state recovery.
A Recommended Hybrid Architecture: Rolling Summaries, Pinned Key Information, and On-Demand Retrieval
For most web-based chat products and intelligent programming tools, a hybrid strategy works well:
- Define trigger conditions. Summarization runs when token usage reaches 70% to 80% of the limit, when the conversation reaches 20 to 30 turns, or when a task stage is completed.
- Generate a structured summary. Use a fixed template to extract the goal, constraints, confirmed decisions, open questions, key entities, and code context.
- Pin key information. The system prompt, hard constraints, and current task state are excluded from trimming.
- Initialize the new session. Inject the structured summary, the recent window, and the relevant retrieved fragments.
- Archive for traceability. Store summaries separately from the original messages, keep version numbers, and make it possible to trace back to the source.
A sample summary template looks like this:
[Task goal]...[Hard constraints]...[Confirmed decisions]...[Open questions]...[Key entities/files/interfaces]...[Recent changes]...[Suggested next steps]...[Compression ratio and confidence]...
Pseudocode:
function maybe_compact(session):if session.tokens < 0.75 * window_limit and session.turns < 25:return sessionsummary = summarize(messages = session.messages,template = STRUCTURED_TEMPLATE,max_words = 3000)pinned = extract_pinned_constraints(session)recent = session.recent_turns(8)retrieved = retrieve_relevant(session.archive, session.current_goal)new_session = create_session()new_session.inject(system_prompt)new_session.inject(pinned)new_session.inject(summary)new_session.inject(retrieved)new_session.inject(recent)return new_session
Evaluation and Rollout Recommendations
Evaluation should focus on recall of key information, adherence to constraints, answer consistency, compression ratio, time to first token, and cost. Combine manual spot checks with automated comparison. Check whether the goal has drifted, whether any constraint has been violated, and whether an open question has been wrongly treated as resolved.
Common pitfalls include:
- Over-compression that drops hard constraints.
- Summary drift, which leads later conversation to rest on a wrong premise.
- Retrieval noise that brings in unrelated old information.
- Full injection of history, which makes costs spiral.
- Private information that enters a summary without access controls.
In rollout, make thresholds configurable, keep summaries editable, allow key information to be pinned, and spot-check summary quality. With deliberate session engineering, a long conversation can move from “forgetting once the limit is reached” to a sustainable experience built on stage archiving, state recovery, and continuous evolution.
