PrepGenAICerts

Session

Agent SDK

Definition

A stateful container in the Claude Agent SDK that holds an agent's conversation history, accumulated tool results, and metadata across multiple turns. Sessions can be persisted to durable storage, resumed after a process restart, and forked into independent branches. Session lifecycle management — not the model or tools — is what makes long-running agentic tasks recoverable.

Example Usage

After each checkpoint in a multi-hour data migration, serialize the session to Redis with `session.dumps()` and store the key. On restart, call `Session.loads(redis_client.get(key))` to resume from the last committed step.

Why It Matters for the CCA-F Exam

Sessions appear in Domain 1 questions about long-running tasks, fault tolerance, and context management. The exam tests whether candidates know that session persistence is the architect's responsibility — the SDK provides the session object, but the engineer must call `session.dumps()` and write it to durable storage. A second scenario type asks what happens when a session grows so long it approaches the context window limit, testing knowledge of summarization and compression mitigations.

In Depth

A Session is the Agent SDK's unit of continuity. It wraps the messages array the model sees on each turn, accumulates tool call/result pairs as the agent works, and exposes lifecycle operations (persist, restore, fork) that the raw Messages API has no equivalent for. This page covers the Session object itself — for the SDK overview and hook system, see Claude Agent SDK.

Lifecycle: create → populate → persist → resume

from claude_agent_sdk import Agent, AgentDefinition, Session
import redis

r = redis.Redis()
defn = AgentDefinition(model="claude-sonnet-4-6", system="...", tools=["read_file"])
agent = Agent(definition=defn)

# 1. Create and run — agent populates the session with each turn
session = Session()
result = agent.run("Migrate table users — step 1 of 5", session=session)

# 2. Persist after each successful step (YOUR responsibility)
r.set("migration:session", session.dumps())  # serialize to bytes
print("Step 1 done, state saved.")

# --- process crashes here ---

# 3. Resume: load serialized state, continue from step 2
raw = r.get("migration:session")
session = Session.loads(raw)           # restore full message history
result = agent.run("Continue migration — step 2 of 5", session=session)

What the SDK returns vs. what you must persist

The SDK does not automatically write sessions to durable storage. session.dumps() gives you a bytes blob; you are responsible for writing it to disk, Redis, S3, or a database. If the process restarts before you persist, the session is gone and the agent starts cold.

fork_session vs. new session

`fork_session`New `Session()`
Starting stateFull copy of parent's message historyEmpty
Use caseParallel exploration (try two strategies without risking main thread)Independent task
Parent affectedNoN/A
# Fork for parallel A/B exploration
branch_a = fork_session(session)
branch_b = fork_session(session)
result_a = agent.run("Try strategy A", session=branch_a)
result_b = agent.run("Try strategy B", session=branch_b)
# session (parent) is unchanged; merge whichever result wins

Context window limits

Long-running sessions accumulate messages until they approach the model's context window limit. Mitigations include periodic Summarization Strategy (replace early messages with a summary) and Context Compression. The SDK does not compress sessions automatically.

How It's Tested & Common Confusions

Exam questions typically present a scenario — a multi-step task that must survive process restarts, or a system that must resume from a checkpoint — and ask which SDK construct enables it. The correct answer is session persistence via session.dumps() / Session.loads(). Distractors include prompt caching (reduces cost, does not provide resumability) and subagent delegation (isolation, not persistence). A second question type presents a session that is growing very long and asks how to stay within context limits; correct answers involve summarization or compression, not simply starting a new session (which loses history).

Frequently Asked Questions

Is a session the same as the conversation history (messages array)?

A session *contains* the messages array, but it is more than that. The SDK's Session object also tracks metadata, tool state, and provides lifecycle operations like `dumps()`, `loads()`, and `fork_session`. Think of the messages array as the raw data and the Session as the managed container with persistence methods.

What happens if I don't persist a session and the process restarts?

The session is lost. The Agent SDK does not automatically persist sessions to durable storage — that is the engineer's responsibility. In production systems, call `session.dumps()` and write the result to Redis, a database, or disk after each successful step so the workflow can resume from the last checkpoint rather than restart from the beginning.

When should I use fork_session instead of a new Session?

Use `fork_session` when you want to explore two strategies in parallel while keeping the parent session intact — for example, trying two different approaches to a sub-problem before committing to one. Use a new `Session()` for genuinely independent tasks that share no prior context.

PrepGenAICerts is an independent exam-prep site. It is not affiliated with, endorsed by, or sponsored by Anthropic, PBC. Claude and Anthropic are trademarks of Anthropic, PBC. Exam details are taken from publicly available Anthropic and Pearson documentation. About PrepGenAICerts.