Long Conversation Caching: How We Cut Repeated Context Costs by 80%
This article walks through a practical approach to reducing long-conversation costs through prefix cache reuse. It covers migrating legacy session storage to a project-scoped four-file layout, reverse-engineering the branch metadata contract, writing session artifacts atomically in a consistent order, stabilizing the request prefix to maximize cache hit rate, and tracking hit rate and per-turn cost as observability metrics. Readers will find migration logic, stabilization rules, and a production checklist for keeping context continuous, auditable, and portable.
1. Where the Problem Started: A Compatibility Gap from Session Storage Evolution
After the coding assistant evolved from early releases to 1.x, the way local session data is organized changed fundamentally. Early versions typically split a single conversation into two files: one holding the message body, and another holding metadata such as the title, token counts, and cost. Both were laid out flat in the same session directory. The new version switched to a project-isolated directory tree, where each session generates a set of four artifacts: a body file, branch metadata, a runtime metrics file, and a checkpoint directory for intermediate state.
The change spans three dimensions: naming moved from “device name + timestamp + sequence number” to “timestamp + model identifier”; the extension scheme moved from a single metadata file to several semantically separated files; and the file count grew from two to four. Copying old data directly into the new directory leaves the tool unable to recognize it, and both historical context and cost statistics reset to zero. The only viable path is to read the new version’s data layer implementation and reverse-engineer its actual data contract.
2. Reverse-Engineering the Data Contract: Branch Metadata as an Example
Branch metadata describes who a session branch belongs to, where it came from, and which tree it is attached to. It typically contains the following fields:
type BranchMeta struct {ID string `json:"id"`CreatedAt time.Time `json:"created_at"`UpdatedAt time.Time `json:"updated_at"`Scope string `json:"scope,omitempty"`WorkspaceRoot string `json:"workspace_root,omitempty"`TopicID string `json:"topic_id,omitempty"`TopicTitle string `json:"topic_title,omitempty"`}
Four pitfalls come up most often during this process:
- Time fields must be RFC3339 strings with a timezone; a missing timezone causes parse failures or lands on the wrong date.
- The ID must match the session identifier in the filename exactly, or the branch tree breaks.
- WorkspaceRoot should be an absolute path; a relative path resolves to the wrong location under different working directories.
- TopicID and TopicTitle must either both be present or both be omitted; writing only one causes title rendering anomalies.
3. Write Order and Consistency for the Four Artifacts
There are implicit dependencies among the four artifacts: the body file is the source of truth, branch metadata determines visibility, runtime metrics determine the statistical basis, and the checkpoint directory determines rollback capability. The recommended approach is to write to a temporary file first and then atomically rename, with the order body → metadata → metrics → checkpoint. If any step fails, roll back the files already written to avoid orphan sessions that have a body but no metadata.
Illustrative migration logic:
def migrate(old_session, project_dir):body = parse_jsonl(old_session.body_path)meta = {"id": old_session.id,"created_at": to_rfc3339(old_session.created),"updated_at": to_rfc3339(old_session.updated),"scope": "workspace","workspace_root": str(project_dir.resolve()),}write_atomic(project_dir / f"{old_session.id}.jsonl", body)write_atomic(project_dir / f"{old_session.id}.jsonl.meta", meta)write_atomic(project_dir / f"{old_session.id}.jsonl.telemetry.json", metrics)ensure_checkpoint_dir(project_dir / f"{old_session.id}.ckpt")
4. The Core of Cost Reduction: Prefix Cache Hit Rate
In long conversations, the main cost is not the new question but the historical context resubmitted every turn. Mainstream large model services generally offer implicit or explicit context caching: when the request prefix is byte-for-byte identical, the cached portion is billed at a lower price, and only the uncached portion is billed at the standard rate. So the key to cutting costs is not compressing context length, but keeping the prefix unchanged for as long as possible.
Actionable stabilization rules:
- Fix the order and wording of the system prompt and tool descriptions; never put timestamps or random IDs in the prefix.
- Append to conversation history only; never re-polish or reorder earlier messages.
- Place dynamic information (retrieval results, environment variables) uniformly at the end, after the stable prefix.
- Use deterministic key ordering and fixed separators during serialization, so equivalent content does not produce different bytes.
- On checkpoint restore, replay the original bytes; do not deserialize and re-serialize as a “formatting” step.
5. Observability: Turning Cache Effects into Measurable Metrics
No measurement, no optimization. The runtime metrics file should record at least: total input tokens, cache-hit tokens, uncached tokens, cache-write tokens, per-turn cost, cumulative cost, and conversation turns. From these, compute hit rate and unit context cost:
hit rate = cache-hit tokens / total input tokensper-turn cost = uncached tokens * standard price + hit tokens * discounted price + output tokens * output price
When the hit rate stays below expectations for a long time, check three things first: whether volatile fields have crept into the prefix; whether frequent model switching is invalidating the cache; and whether moving back and forth between branches is breaking prefix continuity.
6. Implementation Checklist
- Build a version adaptation layer that confines storage structure differences to one place and shields upper-layer business logic.
- Make the migration script idempotent and dry-run capable: validate first, then write.
- Route all session writes through atomic persistence and orphan cleanup.
- Include prefix templates in code review; treat any change as a high-risk change that affects cost.
- Set up a dashboard and alert thresholds for hit rate and per-turn cost.
With this approach, repeated billing for duplicated context in long conversations is sharply reduced, cutting overall cost by roughly 80% while keeping context continuous, auditable, and portable.
