Designing Agent Session Memory: Append-Only Logs, Checkpoints, and Recovery
This article explains how to design persistent session memory for AI agents using an append-only event log, checkpoints, and recovery. It covers the physical log layout, event schema design, batching and compression, checkpoint strategies, replay-based state reconstruction, delegation and subtask memory, engineering practices such as privacy and testing, and common pitfalls.
1. Why Agents Need Memory
Agents often perform many steps in real development scenarios. Consider an agent modifying a large codebase: it may first read files, then plan changes, modify three files, and run tests. If the process exits unexpectedly during this workflow, whether the restarted agent can continue from the previous progress depends entirely on whether the runtime framework has saved memory.
An agent without persistent memory typically faces three problems:
- Progress loss: When the user asks, “Where did we stop?” the agent cannot answer and must re-inspect the entire codebase from the beginning.
- Broken references: In a multi-turn conversation, when the user says, “Adjust that function from earlier again,” the agent cannot determine which previous modification “earlier” refers to.
- Untraceable execution: When an incorrect result appears, developers cannot reconstruct what operations the agent performed and what inputs informed its decisions, so troubleshooting relies on guesswork.
Memory is therefore infrastructure for an agent framework, not an optional enhancement. The approach discussed in this article can be summarized as:
Memory = append-only event log + recording + checkpoints + recovery
The log is the single source of truth. Recording writes events into the log. Checkpoints force data to disk at critical moments. Recovery rebuilds conversation and execution state from the log.
2. The Physical Form of Memory: One Log File per Session
Treating memory as a concrete file helps reduce system complexity. Each session corresponds to a directory on disk, and that directory contains a compressed event log. A typical logical layout looks like this:
sessions/<escaped-workspace-path>/<session-id>/session.jsonl.gz # compressed event log
Several path design points deserve attention:
- Isolate by workspace: Sessions from different projects should not interfere with one another. Workspace paths contain characters such as slashes and colons, which cannot be used directly as directory names. They need to be escaped, for example by replacing path separators with double hyphens.
- Use unique session IDs: A timestamp plus a random suffix can ensure uniqueness within the same workspace.
- Keep the log decompressible and inspectable: After decompression, the compressed file is plain text with one JSON object per line. This saves disk space and also makes manual inspection easier.
The decompressed format is commonly called JSON Lines. Each line is a complete, independent JSON object, which supports streaming reads and makes it easier to determine which lines were fully written after a crash.
3. Recording: An Append-Only Event Stream
3.1 Append-Only Semantics
Append-only is the most important constraint for this log, and it applies at three levels:
- Written lines are never modified: Events use continuously increasing sequence numbers. Any event already persisted must not be rewritten or deleted.
- The session header is immutable: The first line records session identity information, such as session ID, creation time, workspace path, and delegation depth. Once a session is created, this information is fixed.
- State changes only through appends: Every state change appears as a new event rather than as an overwrite of old data.
The reason is straightforward. The log is the only record of “what happened.” If history can be modified, the recovered state cannot be guaranteed to match the actual execution process. For debugging and auditing, an immutable history is also more valuable.
3.2 Event Structure Example
Event field design should serve two goals: replayability and traceability. The following is a generic example. Field names are illustrative only; actual projects should define fields according to their own needs:
{"seq": 0, "type": "session_header", "sessionId": "s-20261125-01", "createdAt": "2026-11-25T01:30:00Z", "workspace": "/path/to/workspace", "delegationDepth": 0}{"seq": 1, "type": "user_message", "payload": {"text": "Fix the null pointer issue in the login API"}}{"seq": 2, "type": "tool_call", "payload": {"name": "read_file", "args": {"path": "src/auth.py"}}}{"seq": 3, "type": "tool_result", "payload": {"status": "ok", "bytes": 4096}}{"seq": 4, "type": "assistant_message", "payload": {"text": "The null pointer occurs when the token is empty; a null check should be added."}}
When designing events, consider the following:
seqshould increase monotonically, making it easier to detect missing and out-of-order events.typeshould use a finite set of enum values so recovery can dispatch handling by type.payloadshould preserve the original information, but sensitive content such as keys and tokens should not be written. When necessary, record only redacted summaries.
3.3 Batching and Compression
Model output is usually streaming, and a single response may be split into dozens of small fragments. If every fragment is written as a separate line, the log grows quickly, and excessive write operations reduce performance. A common approach is to batch consecutive events of the same kind:
- When multiple consecutive
assistant_deltafragments appear, merge them in memory into oneassistant_messageevent. - Merging can be triggered by a type switch, a byte threshold, or an end marker.
- The merged event still consumes a new
seqand retains metadata such as the original fragment count for traceability.
For compression, text logs contain high redundancy, and common compression algorithms usually reduce size significantly. There is a technical detail between compression and append writes: most compressed formats require a complete data stream to decompress correctly. Therefore, choose a compression method that supports segmented appends, or use a periodic “sealing” strategy so that every compression segment is complete and readable.
4. Checkpoints: Forcing Data to Disk at Key Points
4.1 Why Checkpoints Are Needed
An append-only log already prevents most data loss, but the operating system write cache means that data may not actually reach disk when a write function returns. If power is lost or the process is forcibly killed during that window, the most recent events may be lost. Checkpoints solve exactly this problem: at certain critical moments, force data to be durable before continuing with subsequent actions.
4.2 Correct Persistence Practices
When implementing checkpoints, pay attention to the following:
- Call the system synchronization interface: After writing, call
fsyncor an equivalent interface to ensure data moves from cache to persistent storage. - Persist first, then perform side effects: For example, record “about to modify file X” first, confirm it is durable, and only then modify the file. Even if a crash occurs during the modification, recovery can still know the intent.
- Synchronize directory entries: When creating a new file, also synchronize its containing directory; otherwise the file itself may disappear after a crash.
- Avoid partial writes: When a snapshot file needs to be replaced as a whole, write to a temporary file first and then replace the original through an atomic rename.
4.3 Checkpoint Strategies
Checkpoints do not need to be performed for every event, because that would incur excessive performance overhead. Common strategies include:
- Per turn: Persist after each completed user interaction, suitable for conversational scenarios.
- Per side effect: Persist before operations with side effects such as file writes, external requests, or command execution. This is key to ensuring recoverability.
- Per time interval: Set a fixed interval as a fallback.
- Per delegation boundary: Persist when a subtask starts and ends, making it easier for the parent task to reschedule after a subtask failure.
Strategies can be combined. The general principle is: any operation that cannot be safely repeated must have a checkpoint before it.
5. Recovery: Rebuilding State from the Log
5.1 Recovery Flow
The goal of recovery is to restore an interrupted session to the last fully committed state and then let the agent continue. The standard flow is:
- Open the log file and read it line by line.
- Discard trailing incomplete lines, meaning lines without a newline or lines that cannot be parsed, and treat them as uncommitted writes.
- Validate whether
seqis continuous. If a gap is found, report an error rather than silently skipping it. - Replay events in order to rebuild conversation history, tool call results, and the list of unfinished operations.
- Find the last checkpoint, then use subsequent events to determine which side effects have already been executed and which need to be redone or confirmed.
- Set the
seqcounter to the maximum value in the log plus one, then continue appending.
5.2 Reference Implementation
The following example code shows the core logic of recording and recovery. It omits compression and concurrency control to make the main flow easier to understand:
import jsonimport osimport timeclass SessionLog:def __init__(self, path: str, session_id: str):self.path = pathself.seq = 0if os.path.exists(path):self.seq = self._load_last_seq()else:self._append_raw({"seq": 0,"type": "session_header","sessionId": session_id,"createdAt": time.time(),"delegationDepth": 0,})self.seq = 0def _append_raw(self, obj: dict) -> None:line = json.dumps(obj, ensure_ascii=False) + "\n"with open(self.path, "a", encoding="utf-8") as f:f.write(line)f.flush()os.fsync(f.fileno())def append(self, event_type: str, payload: dict) -> int:self.seq += 1self._append_raw({"seq": self.seq, "type": event_type, "payload": payload})return self.seqdef checkpoint(self, state: dict) -> int:# A checkpoint is also an event; writing it forces it to diskreturn self.append("checkpoint", state)def _load_last_seq(self) -> int:events = list(restore(self.path))return events[-1]["seq"] if events else 0def restore(path: str):expected = 0with open(path, encoding="utf-8") as f:for raw in f:if not raw.endswith("\n"):break # Incomplete write at the end; treat as uncommittedtry:event = json.loads(raw)except json.JSONDecodeError:breakif event["seq"] != expected:raise ValueError(f"Non-contiguous seq: expected {expected}, got {event['seq']}")expected += 1yield event
This code reflects three principles: every write is persisted, recovery tolerates a truncated tail but not gaps in the middle, and checkpoints use the same mechanism as ordinary events so they can be handled uniformly.
5.3 Rebuilding State After Recovery
Event replay is not just about reconstructing a message list. A more complete approach is to maintain a state object and update it item by item by event type, for example:
user_messageandassistant_messageupdate conversation history;tool_callrecords an unfinished operation, andtool_resultmarks it as completed;checkpointacts as a snapshot anchor, allowing recovery to start from the snapshot and reduce replay volume;- If a call is recorded but its result is missing, mark that operation as pending confirmation and let the user decide whether to retry or skip it.
6. Memory for Delegation and Subtasks
Complex tasks are often delegated to sub-agents. In this case, each subtask should ideally have its own independent session log and record the delegation depth in its session header. The top-level session has depth 0, and each subtask layer increments it by one. This has several benefits:
- The parent task can trace subtask execution through the child session ID.
- The depth field helps limit recursion levels and prevent infinite delegation.
- If a subtask fails, the parent task only needs to replay the child session’s last checkpoint rather than re-executing every step.
The parent-child relationship should also be recorded in the parent session event stream, for example with “delegated to a child session” and “child session returned a result” events, keeping the main trail clear.
7. Engineering Practices
7.1 Permissions and Privacy
Session logs store user input, code snippets, and tool output, which may contain sensitive information. Recommended measures include:
- Configure the log directory so that only the current user can read and write it, while other users cannot access it.
- Redact secrets and tokens with known formats before writing.
- Do not write the full contents of environment variables into logs.
- Clearly tell users where logs are stored and provide a command to delete sessions.
7.2 Retention and Cleanup
Long-running projects accumulate many session files. Retention policies can be based on time or count, such as keeping sessions from the last 30 days or keeping at most 50 sessions per workspace. Cleanup is irreversible, so list candidate files first and delete only after confirmation.
7.3 Testing Methods
Reliability needs to be verified through tests, not inference. Cover at least the following scenarios:
- Crash injection: Forcefully terminate the process at different stages of writing and check whether recovered state is consistent.
- Truncation test: Artificially truncate the end of the log and confirm that recovery logic correctly discards incomplete lines.
- Sequence gap test: Delete a line in the middle and confirm that recovery logic reports an error rather than silently skipping it.
- Concurrent write test: When multiple processes open the same session at the same time, there should be a mutex or lock mechanism to avoid sequence conflicts.
8. Common Pitfalls
- Pitfall 1: A log is a backup. A log records the process, while a backup records the result. Both are needed, and neither can replace the other.
- Pitfall 2: Calling fsync for every event is the safest approach. It is indeed reliable, but the performance cost is high. Choose checkpoint locations based on the risk of side effects.
- Pitfall 3: Compressed files can be appended directly. Many compression formats do not support arbitrary-position appends, so segmented or sealing strategies are required.
- Pitfall 4: Recovery means resending the message list to the model. Tool call side effects, unfinished operations, and subtask states must be handled separately; otherwise the agent may repeat dangerous actions.
The core of memory design is to separate “what happened” from “what the current state is.” The former is handled by an append-only log, while the latter is derived from the log through checkpoints and recovery. This division gives the system a reliable basis for handling crashes, restarts, and troubleshooting.
