Learning resourcesReviewed · Anthropic

Claude Agent SDK: Persist sessions to external storage

This documentation page shows developers who build agents with the Claude Agent SDK how to mirror session transcripts to their own object store, key-value store or database, so that another host can resume a session. The page documents a bundled InMemorySessionStore for development and testing. For persistent backends it offers S3, Redis and Postgres reference adapters that you copy and adapt. It also covers the SessionStore interface (append and load, plus four optional methods), a quick start, a conformance suite, and notes on how dual writes, best-effort mirroring, resume and retention behave.

Researched 14 Nov 2026

In short.

This documentation page is for developers who build agents with the Claude Agent SDK. It explains how to copy session transcripts to your own storage (an object store, key-value store or database) so that a different host can resume the same session. The page documents a bundled InMemorySessionStore for development and testing. For persistent backends it offers reference adapters that you copy and adapt. In practice, that means copying and adapting a reference adapter or writing your own SessionStore adapter. The page documents the adapter interface: append and load are required, and listSessions, listSessionSummaries, delete and listSubkeys are optional. It also gives a two-call quick start, reference S3, Redis and Postgres adapters, and a conformance suite. Several documented behaviours affect design. The local transcript is always written first, and a resume from the store deletes the local copy when the run ends. Mirror writes are best-effort. A rejected append call gets at most three attempts and a timed-out call is not retried. A batch that still fails produces a mirror_error message and is dropped while the query continues. Two options conflict with a store. The SDK never deletes from your store on its own: deleteSession can call your adapter's delete method, and retention is up to you, through the adapter, backend expiry, lifecycle rules or scheduled cleanup. Nothing was executed or tested for this report, and every statement comes from the single captured page. The page states no licence or cost.

Researched and written by an AI model and checked by a second AI model. How it works

Scope covered: the complete selected documentation page at [https://code.claude.com/docs/en/agent-sdk/session-storage.md], captured as a single page on 14 November 2026. Excluded: every linked page and repository. That includes the sessions guide, the hosting guide, the TypeScript and Python references, the authentication and settings pages, and the example adapter source code on GitHub. No licence, pricing, changelog or release notice was captured. Nothing was executed or tested. All behaviour described here is as documented on the page, not observed, including retries, resume, deletion of the local copy, and the conformance-suite contracts and usage instructions.

The overview

What this resource is

This is a single documentation page titled Persist sessions to external storage, published at [https://code.claude.com/docs/en/agent-sdk/session-storage.md]. Its stated purpose is to mirror Agent SDK session transcripts to your own object store, key-value store or database so that other hosts can resume your sessions. The page is a feature guide and interface reference for the Claude Agent SDK. It shows the SDK as the TypeScript package @anthropic-ai/claude-agent-sdk and the Python package claude_agent_sdk.

By default the SDK writes session transcripts as JSONL files under ~/.claude/projects/ on the local filesystem. The page introduces a SessionStore adapter as the extension point that copies those transcripts to a backend of your choice. It is a guide to a feature, not a tool you install on its own.

The captured page shows no author, version number or publication date. Some behaviour is tied to named SDK versions (see the freshness section), but the captured text gives no version for the page as a whole.

Overall assessment

Judged on this page alone, it is a thorough and practical guide to one narrow job: making Agent SDK sessions resumable across machines. It gives the full interface in both TypeScript and Python, a quick start that looks runnable, a table of when each method is called, links to reference adapters for three storage types, and a long section of behaviour notes. Many of those notes cover issues that usually only show up in production: retry limits, duplicate delivery, what happens to local files on resume, and which options conflict.

The main catch is effort. The page documents a bundled InMemorySessionStore for development and testing, plus reference adapters to copy and adapt for persistent backends. The page says the S3, Redis and Postgres reference adapters are not published as packages. You copy one from the SDK repositories and adapt it. You are also responsible for correctness: de-duplication, retention, keeping summaries up to date, and watching for mirror failures.

This assessment comes from reading the documentation only. Nothing was run, so statements about how the SDK behaves are the page's claims, not verified results.

Who it is for

The page is for developers who run Claude Agent SDK agents somewhere other than a single local machine. It gives three reasons to use a store. The first is multi-host deployment: serverless functions, autoscaled workers and CI runners don't share a filesystem. The second is durability, because local containers are ephemeral. The third is compliance and audit: keeping transcripts in storage you already govern, with your own retention, encryption and access controls.

It suits beginners who already use the SDK's query() function and want to understand sessions, and experienced backend engineers who will build an adapter. Writing an adapter assumes you are comfortable with async code and with your chosen backend (S3, Redis, Postgres or similar). That includes concurrency control for the optional summary sidecar.

It is not aimed at people who only use Claude Code interactively and never need to resume sessions on another host. For continuing, resuming and forking sessions without a custom store, the page points to a separate guide at [https://code.claude.com/docs/en/agent-sdk/sessions.md]. That linked page was not captured.

What it enables

Two methods are required. append writes batches of transcript entries, and load reads a session back, returning null if the session is unknown. Four methods are optional. listSessions is required for continue: true, which throws without it. listSessions({ sessionStore }) can work without it if listSessionSummaries is implemented, and throws if neither is implemented. listSessionSummaries reads metadata for all sessions in one call; without it, listing falls back to listSessions plus one load per session. delete backs deleteSession; if it is undefined, deletion does nothing, which the page says suits append-only backends. listSubkeys finds subagent transcripts during resume.

The page says the following TypeScript functions work against the store when one is attached: query(), startup(), listSessions(), getSessionInfo(), getSessionMessages(), renameSession(), tagSession(), deleteSession(), forkSession(), listSubagents() and getSubagentMessages(). In Python, you set session_store in ClaudeAgentOptions to run query() against a store. The other operations have store-backed functions such as list_sessions_from_store(), get_session_messages_from_store(), fork_session_via_store() and delete_session_via_store(). startup() has no Python equivalent.

Both SDKs ship a conformance suite that checks an adapter against the behaviour the SDK expects. Tests for optional methods are skipped automatically when those methods are not implemented. The page also describes how to maintain per-session summary metadata. You call the exported foldSessionSummary helper (fold_session_summary in Python) inside append when you implement listSessionSummaries.

Using it

Requirements and prerequisites

You need the Claude Agent SDK in TypeScript or Python, and a backend you can write to. A real adapter also needs that backend's client library. The page says each reference adapter takes a client instance that you configure beforehand, so you control credentials, TLS, region and connection pooling.

Resume depends on the working directory. projectKey encodes the working directory, so you must resume or continue from a working directory that matches the original run's. In TypeScript only, you can set CLAUDE_CODE_PROJECT_DIR_NAME alongside CLAUDE_CONFIG_DIR in a query's env option. The SDK then keys that query's entries and lookups by that name instead. The page says this requires Agent SDK v0.3.234 or later. Standalone helpers such as listSessions and deleteSession take no env option, so you must also set both variables in the host process environment.

Pointing CLAUDE_CONFIG_DIR at a new temp directory affects authentication. The page says that if you sign in with a claude.ai login, or with an apiKeyHelper in your user settings.json, the run then fails with Not logged in. It lists three fixes. You can set CLAUDE_CODE_OAUTH_TOKEN to a long-lived token from claude setup-token, set ANTHROPIC_API_KEY, or copy your config files into the temp directory. The long-lived token can only make model requests, so claude.ai connectors are not available in that run.

To run the Python conformance suite with pytest, install pytest first, because it is not an SDK dependency. The page names no Python or Node.js version requirement beyond the SDK versions listed under freshness, so other runtime requirements are unknown.

How it works

The SDK writes every batch twice. The Claude Code subprocess writes each batch of transcript entries to local disk first, and the SDK then forwards the same batch to your store's append(). The store is a mirror of the local transcript, not a replacement for it. Entries are JSON-safe objects, one per line in the local JSONL file. Treat them as opaque: store them in order and return them from load in the same order. load must return entries that are deep-equal to what was appended, so a backend that reorders object keys is fine.

Each transcript is addressed by a SessionKey with a projectKey, a sessionId and an optional subpath. With no subpath, the key means the main transcript. A subpath such as subagents/agent-<id> means a subagent transcript or sidecar file. The page says to treat the subpath as an opaque key suffix.

Resume is triggered by resume, by continue: true in TypeScript, or by continue_conversation=True in Python. In each case the SDK calls load before it starts the subprocess. If the store returns a transcript, the SDK writes it into a temporary config directory and runs the subprocess with CLAUDE_CONFIG_DIR pointing there. It deletes that directory when the run ends, and the local transcript from the run goes with it, so the store then holds the only durable copy. If the store has nothing for the session, the outcome depends on the option. resume passes the ID through to the subprocess, which resumes the local transcript. continue: true in TypeScript starts a fresh session, and continue_conversation=True in Python continues from the newest local session.

Mirror writes are best-effort. If append() rejects, the SDK retries the batch up to two more times with a short backoff, for at most three attempts in total. A call that times out is not retried, because the original call may still land. If the batch still fails, the SDK logs the error, emits a system message with subtype mirror_error, drops the batch and continues the query. Retries can deliver the same entries twice, so your append() should de-duplicate by entry.uuid and keep every entry that has no uuid.

Setup steps the page describes

Quick start: create an InMemorySessionStore and run query() with it. In TypeScript you pass it as options.sessionStore, and in Python as ClaudeAgentOptions(session_store=...). Capture the session ID from the result message. Then call query() again with the same store instance and resume set to that ID. The page says the second call prints a summary of the files found by the first, which shows the agent resumed with full context. The in-memory store lives in process memory, so this shows the flow but not durability across hosts.

For a real backend, implement append and load against your storage, then add any optional methods you need. Alternatively, copy the reference adapter closest to your backend from the SDK repositories, install that backend's client, and adapt it. The page describes how each storage type works. The object-store adapter (S3) writes one part file per append(), and load() lists the parts, sorts them and joins them. The key-value adapter (Redis) keeps one list per transcript plus a sorted index of sessions. The relational or document-store adapter (Postgres) stores one row or document per entry, ordered by a key assigned on insert.

To validate an adapter in TypeScript, copy shared/conformance.ts from the example directory into your tests. In Python, install pytest and call run_session_store_conformance with a zero-argument factory that builds your store. The page says every store the factory returns must start with empty storage, because the tests reuse the same session keys. It suggests a fresh in-memory fake, a unique key prefix or a new test database.

If you don't want a fresh session to leave a local transcript, set CLAUDE_CONFIG_DIR to a private temp directory in options.env. In TypeScript, also copy process.env into env, because the env option replaces the subprocess environment.

Worked example from the page

The page's multi-host example builds an S3SessionStore, copied from examples/session-stores/s3, with a bucket name (my-claude-sessions), a prefix (transcripts) and an S3Client set to us-east-1. It passes the store as sessionStore to query() with the prompt Hello!. Later, possibly on a different host, it calls query() again with the same store, resume set to a previous session ID, and the prompt Continue where we left off. The bucket, prefix and region are example placeholders, not requirements.

The Python quick start shows the same pattern with InMemorySessionStore and ResultMessage, and it wraps the first query in try/except. The page explains that a single-shot query() raises an error after it yields an error result. If the failure was an error result, the session ID has already been captured. Connection or process failures produce no result message, so in that case the session ID may be missing.

Neither example was run for this report. Both are summarised from the page and have not been verified.

Assessment & evidence

Limitations and cautions

Conflicting options: the SDK throws at startup if you combine a store with either of two options. One is persistSession: false in TypeScript; the Python SDK has no equivalent. The other is file checkpointing (enableFileCheckpointing in TypeScript, enable_file_checkpointing in Python), which writes file backups straight to local disk without mirroring them to the store.

Risk of data loss: mirroring is best-effort. A rejected append call gets at most three attempts in total, and a call that times out is not retried. A batch that still fails produces a mirror_error message and is dropped, and the query continues. On a run resumed from the store the local copy is deleted, so a dropped batch has no surviving copy once the run ends. Watch for mirror_error messages.

Concurrency: append calls running at the same time for the same session can race on the summary sidecar. The page says to serialise the read, fold and write steps with a transaction, a compare-and-swap or a per-session lock. Deleting the main key must also delete all subkeys and remove the summary entry.

Working directory: because projectKey encodes the working directory, you must resume from a matching one.

Gaps in Python: on resume from a store, the Python SDK copies only credentials and .claude.json into the temporary directory. An app that authenticates through apiKeyHelper in user settings.json therefore fails with Not logged in. An apiKeyHelper in managed or project settings still works. startup() has no Python equivalent, and standalone functions such as list_sessions() read local files, not the store.

Behaviour worth knowing: getSessionMessages returns the chain left after auto-compaction, so a store holding 503 raw entries may return only 18 messages. Use store.load(key) for the full raw history. forkSession is not a byte copy: it rewrites sessionId fields and remaps message UUIDs, so copying at the adapter level would produce wrong results. listSubagents needs listSubkeys, and without listSubkeys resume restores only the main transcript. If listSessions is undefined, continue: true throws.

Security: the page does give specific security-related guidance. It suggests keeping transcripts in storage you already govern, with your own retention rules, encryption and access controls. It says to set CLAUDE_CONFIG_DIR to a new, private temp directory if you don't want a fresh session to leave a transcript on local disk. It explains how credentials and authentication carry into temporary config directories, and which sign-in methods fail with Not logged in. It also says the reference adapters take a client you configure beforehand, so you control credentials and TLS. What the page does not provide is any security guarantee for the store or the mirror, or a way to validate an adapter's security. It describes the conformance suite as checking the behavioural contract of the adapter methods, not security.

Unknowns: the page gives no performance, scale or latency figures and no size limits for entries or transcripts. None of these were assessed.

Reasoning behind this assessment

The page is concrete rather than promotional. It gives exact method signatures in two languages and exact conditions for when each method is called. It names specific failures (mirror_error, Not logged in, startup errors for conflicting options) and states which copy of the transcript survives a run. That level of detail supports a confident description of what the feature is meant to do.

The assessment is limited because only this page was captured. Linked pages were not read: the sessions guide, the TypeScript and Python references, the hosting guide and the example repositories. Adapter source code, edge-case behaviour and version history were therefore not assessed. Nothing was executed either, so the page's statements about behaviour are reported as documented, not observed. These include the retry counts, the deletion of the temporary config directory, and the conformance-suite contracts and usage instructions.

The recommendation to use this feature is conditional. It fits well when sessions must outlive a host or move between hosts. It adds operational work, and the page's own notes show why. Writes are best-effort. The SDK never deletes from the store on its own, so retention depends on you: deleteSession calling your adapter's delete method, backend expiry, lifecycle rules or scheduled cleanup. When a run resumed from a transcript the store returned comes to an end, the store holds the only durable copy, because the local copy is deleted. If the store has nothing for the session, a resume falls back to the local transcript instead, and that local transcript survives the run.

Alternatives and related options

The page itself names the default behaviour as the alternative. With no store, transcripts stay as local JSONL files under the config directory, and the sessions guide covers continuing, resuming and forking sessions without a custom store. That is simpler and needs no adapter. However, local transcripts are not automatically available to another host by default; this page documents a shared SessionStore as one way to make them available.

Within the feature, the choice is between the three documented reference patterns: an object store with one part file per append, a key-value store with one list per transcript, or a relational or document database with one row per entry. The page does not rank them. The right fit depends on your existing infrastructure, your ordering and concurrency needs, and how you want to handle retention.

The page also links to a hosting guide for multi-host deployment patterns at [https://code.claude.com/docs/en/agent-sdk/hosting.md], which was not captured. Other approaches, such as syncing the local config directory yourself with file-level tools, are not discussed on this page, so they are not assessed here.

Evidence base

The only evidence is the selected documentation page at [https://code.claude.com/docs/en/agent-sdk/session-storage.md], captured on 14 November 2026. The capture is complete for that single page. Linked pages and repositories are outside the scope.

The page contains code blocks for the TypeScript and Python interfaces, two quick-start programs, an S3 wiring example and a pytest conformance example. It also has tables of when each method is called and of the reference adapters, plus behaviour notes. It contains no benchmarks, test results or user reports, and none are claimed here. Nothing was executed, so the page's statements about SDK behaviour have not been independently verified.

Access & freshness

Costs

The page states no price for the SDK feature or the documentation, so the cost is unknown from this evidence. The design suggests two likely cost categories: charges from whatever backend hosts your store (object storage, a key-value store or a database), and model usage when the agent runs. The page says nothing about billing for either, the amounts are unknown, and no estimate is offered here.

Request volume and storage depend on your setup. Every batch is written locally and also sent to your store's append(), and a rejected append call can be tried up to three times in total. Request volume and storage size therefore depend on your backend and on how long and how often your sessions run. The SDK performs no automatic store retention. Deletion can be implemented by the adapter or through backend expiry, lifecycle rules or scheduled cleanup.

Rights and licence

The captured page states no licence for the documentation, the SDK or the example adapters, so reuse terms are unknown from this evidence. The page tells you to copy the reference adapters into your own project but gives no licence terms for doing so. Check the licence terms of the linked SDK repositories, [https://github.com/anthropics/claude-agent-sdk-typescript] and [https://github.com/anthropics/claude-agent-sdk-python], before copying code. Those repositories were not captured.

On data handling, the page's compliance and audit use case says you can keep transcripts in storage you already govern, with your own retention rules, encryption and access controls. Treat transcripts as potentially sensitive. That is a precaution added here, not something the page says. The page describes several kinds of stored content: main conversation transcripts, subagent transcripts and sidecar files stored under a subpath, and metadata entries that appear in the raw history load returns. Summary entries also carry opaque state owned by the SDK, which the page says to store unchanged. Entries are typed only as JSON-safe objects with a type field, and the page does not give a complete entry schema.

Freshness and version notes

The page was captured on 14 November 2026 and has no explicit last-updated date. It mentions three SDK versions. Keying by CLAUDE_CODE_PROJECT_DIR_NAME requires Agent SDK v0.3.234 or later. From v0.3.232, the TypeScript SDK strips the additionalMarketplaces alias from copied settings; earlier versions did not. Before v0.3.222, the TypeScript SDK copied only credentials and .claude.json when resuming from a store.

Because these notes name specific SDK versions, older SDK releases may behave differently from what the page describes. The page does not say which SDK version is current or whether the feature is stable, in preview or changing. The documentation is hosted online and may change after capture, so check it against the SDK version you actually install.

Suggested next steps

If you only need to resume sessions on one machine, use the default local behaviour and skip the adapter. If you need resume across hosts, start with the quick start and InMemorySessionStore in a scratch project to learn how append, load and resume fit together. Then copy the reference adapter closest to your backend, install its client, and run the conformance suite against it before you rely on it.

Before going to production, settle these points: how you will de-duplicate by entry.uuid; which of listSessions, listSessionSummaries, delete and listSubkeys you need; how you will serialise summary updates; how you will alert on mirror_error; which working directory or CLAUDE_CODE_PROJECT_DIR_NAME convention every host will use; how you will authenticate if you use a temporary CLAUDE_CONFIG_DIR; and what retention policy applies to stored transcripts.

Check the licence terms of the SDK repositories and example adapters before copying code, and confirm that your SDK version meets the version notes above. Pricing for the SDK and for model usage is not on this page, so check it separately.

Evidence for this report

selected-page.txtselected · checked 2026-11-14