Persist state across sessions
Keep an agent’s state and conversation history across restarts and requests. A session persists what the agent knows, so it can pick up where it left off even when your application restarts or runs across several machines.
What a session contains
Section titled “What a session contains”A session holds the stateful information agents and multi-agent systems need to function, including:
Single Agent Sessions:
- Conversation history (messages)
- Agent state (key-value storage)
- Other stateful information (like Conversation Manager)
Multi-Agent Sessions:
- Orchestrator state and configuration
- Individual agent states and result within the orchestrator
- Cross-agent shared state and context
- Execution flow and node transition history
Built-in session persistence captures and restores this information automatically, so an agent continues a conversation where it left off.
Beyond the built-in options, third-party session managers provide additional storage and memory capabilities.
Basic usage
Section titled “Basic usage”Single agent sessions
Section titled “Single agent sessions”Create an agent with a session manager and use it:
from strands import Agentfrom strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage
# Create a snapshot session manager with a unique session IDsession_manager = SnapshotSessionManager( session_id="test-session", storage=LocalFileStorage("./sessions/"),)
# Create an agent with the session manageragent = Agent(session_manager=session_manager)
# Use the agent - all messages and state are automatically persistedagent("Hello!") # This conversation is persistedSnapshotSessionManager is the recommended manager for new single-agent sessions.
FileSessionManager and S3SessionManager remain supported as the
compatibility path for Graph, Swarm, and existing
repository-format sessions.
SessionManager implements both Plugin (for agents) and MultiAgentPlugin (for orchestrators). The sessionManager constructor field is a convenience shorthand: you can also pass it directly in the plugins array:
const session = new SessionManager({ sessionId: 'test-session', storage: new LocalFileStorage('./sessions/'),})
const agent = new Agent({ sessionManager: session })
// Use the agent - all messages and state are automatically persistedawait agent.invoke('Hello!') // This conversation is persistedconst session = new SessionManager({ sessionId: 'test-session', storage: new LocalFileStorage('./sessions/'),})
// Equivalent to passing via sessionManager fieldconst agent = new Agent({ plugins: [session] })await agent.invoke('Hello!')cargo add tokio --features macros,rt-multi-threadAttach a
SessionManager
backed by
LocalFileStorage:
use std::sync::Arc;
use strands::storage::LocalFileStorage;use strands::{Agent, SessionManager};
#[tokio::main]async fn main() -> strands::Result<()> { let storage = Arc::new(LocalFileStorage::new("./sessions")); let session = SessionManager::builder() .session_id("support-chat") .storage(storage) .build()?; let mut agent = Agent::builder() .session_manager(session) .printer(false) .build()?;
agent.invoke("Remember that my order number is 4815.").await?; agent.shutdown().await}Strands persists the conversation and its state to the underlying storage backend.
Multi-agent sessions
Section titled “Multi-agent sessions”Multi-agent systems (Graph/Swarm) can also use session management to persist their state.
Pass an explicit storage backend to
SnapshotSessionManager:
from strands import Agentfrom strands.multiagent import GraphBuilderfrom strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage
researcher = Agent(name="researcher")writer = Agent(name="writer")
session_manager = SnapshotSessionManager( session_id="multi-agent-session", storage=LocalFileStorage("./sessions/"), multi_agent_save_latest_on="node",)
builder = GraphBuilder()builder.add_node(researcher, "researcher")builder.add_node(writer, "writer")builder.add_edge("researcher", "writer")builder.set_session_manager(session_manager)graph = builder.build()
result = graph("Research and write about AI")The default "node" strategy saves after every node and when the invocation ends. Use
"invocation" to reduce storage writes and save only when the invocation ends. See the
API reference for
MultiAgentSaveLatestStrategy and its accepted values.
const session = new SessionManager({ sessionId: 'graph-session', storage: new LocalFileStorage('./sessions/'),})
const researcher = new Agent({ id: 'researcher', systemPrompt: 'You are a research specialist.',})const writer = new Agent({ id: 'writer', systemPrompt: 'You are a writing specialist.',})
const graph = new Graph({ nodes: [researcher, writer], edges: [['researcher', 'writer']], sessionManager: session,})
// Orchestrator state is automatically persisted after each node completesconst result = await graph.invoke('Research and write about AI')Swarm works the same way:
const session = new SessionManager({ sessionId: 'swarm-session', storage: new LocalFileStorage('./sessions/'),})
const researcher = new Agent({ id: 'researcher', description: 'Researches a topic and gathers key facts.', systemPrompt: 'Research the answer, then hand off to the writer.',})
const writer = new Agent({ id: 'writer', description: 'Writes a polished final answer.', systemPrompt: 'Write the final answer. Do not hand off.',})
const swarm = new Swarm({ nodes: [researcher, writer], start: 'researcher', sessionManager: session,})
const result = await swarm.invoke('Explain quantum computing')Graph and Swarm are not available. Attach SessionManager to each single agent
that needs persistent state.
Multi-agent session managers only track the current state of the Graph/Swarm execution and do not persist individual agent conversation histories.
Reading the session ID
Section titled “Reading the session ID”An agent exposes its session identifier through agent.session_idagent.sessionIdagent.session_id()session_idsessionIdsession_id()
Snapshot-based session managers accept a Storage backend. See the storage guide for backend configuration, tradeoffs, and custom implementations.
from strands import Agentfrom strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage
session_manager = SnapshotSessionManager( session_id="user-123", storage=LocalFileStorage("./sessions/"),)agent = Agent(session_manager=session_manager)
print(agent.session_id) # "user-123"print(session_manager.session_id) # "user-123"
# Without a session manager, the id is a generated, non-persisted handleprint(Agent().session_id) # e.g. "a1b2c3d4"const session = new SessionManager({ sessionId: 'user-123', storage: new LocalFileStorage('./sessions/'),})const agent = new Agent({ sessionManager: session })
console.log(agent.sessionId) // "user-123"console.log(session.sessionId) // "user-123"
// Without a session manager, the id is a generated, non-persisted handleconsole.log(new Agent().sessionId) // e.g. "a1b2c3d4"use strands::storage::InMemoryStorage;use strands::{Agent, SessionManager};
fn main() -> strands::Result<()> { let session = SessionManager::builder() .session_id("user-123") .storage(InMemoryStorage::new()) .build()?; let agent = Agent::builder() .session_manager(session.clone()) .printer(false) .build()?;
assert_eq!(agent.session_id(), "user-123"); assert_eq!(session.session_id(), "user-123"); Ok(())}Storage backends
Section titled “Storage backends”Storage documents the persistence backends. The examples below show how each session manager receives one.
The recommended SnapshotSessionManager accepts any
Storage backend. Manager-level storage takes precedence
over agent-level storage. Without either, it uses
LocalFileStorage("./.strands/").
from strands import Agentfrom strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage, S3Storage
# File-based persistence (development, single-machine)session_manager = SnapshotSessionManager( session_id="user-123", storage=LocalFileStorage("./sessions/"),)
# S3-based persistence (production, distributed)session_manager = SnapshotSessionManager( session_id="user-123", storage=S3Storage(bucket="my-agent-sessions", prefix="production/"),)
agent = Agent(session_manager=session_manager)The repository-based managers cover Graph, Swarm, and existing repository-format
sessions. They configure storage directly rather than through a Storage
backend:
| Session Manager | Persistence | Best for |
|---|---|---|
FileSessionManager | Local disk | Development, single-machine |
S3SessionManager | Amazon S3 | Production, distributed |
from strands import Agentfrom strands.session import FileSessionManager, S3SessionManager
# File-based persistencesession_manager = FileSessionManager( session_id="user-123", storage_dir="/path/to/sessions",)
# S3-based persistencesession_manager = S3SessionManager( session_id="user-123", bucket="my-agent-sessions", prefix="production/",)
agent = Agent(session_manager=session_manager)Pass storage to SessionManager or to the agent. Manager-level storage takes precedence
over agent-level storage. If neither provides storage, initialization fails.
Use LocalFileStorage for durable local sessions and InMemoryStorage for
tests or short-lived processes. Manager-level storage takes precedence over
agent-level storage. Initialization fails if neither provides storage:
use strands::storage::{InMemoryStorage, LocalFileStorage};use strands::SessionManager;
fn main() -> strands::Result<()> { let local = SessionManager::builder() .session_id("durable-session") .storage(LocalFileStorage::new("./sessions")) .build()?; let temporary = SessionManager::builder() .session_id("test-session") .storage(InMemoryStorage::new()) .build()?;
let _ = (local, temporary); Ok(())}The SDK does not provide an S3 storage backend.
How session management works
Section titled “How session management works”Snapshot-based session managers
Section titled “Snapshot-based session managers”Snapshot-based session managers persist a complete point-in-time snapshot. For
single agents, they restore snapshot_latest during initialization and support
immutable checkpoints. Multi-agent managers restore the latest orchestrator
snapshot before the first invocation.
Single Agent Events
- Agent Initialization: When an agent is created with a session manager, it automatically restores any existing state and messages from the session.
- Message Addition: When a new message is added to the conversation, it’s automatically persisted to the session (
SnapshotSessionManagerdoes this undersave_latest_on="message"). - Agent Invocation: After each agent invocation, the agent state is synchronized with the session to capture any updates (
SnapshotSessionManagerdefault,save_latest_on="invocation"). - Message Redaction: When sensitive information needs to be redacted, the session manager replaces the original message with a redacted version while maintaining conversation flow.
SnapshotSessionManagerflushes the redacted content to the latest snapshot under every strategy. - Snapshot Trigger (
SnapshotSessionManager): Creates an immutable checkpoint when thesnapshot_triggercallback returnsTrue.
- Agent Initialization: Restores state from
snapshot_latestif it exists. - Message Addition (
saveLatestOn: 'message'): Saves after each message and again when the invocation ends. - Agent Invocation (
saveLatestOn: 'invocation', default): Saves when the invocation ends. - Snapshot Trigger: Creates an immutable checkpoint when
snapshotTriggerreturnstrue. - Message Redaction: Saves redacted content for the
messageandinvocationstrategies, but not fortrigger.
See Basic Usage for configuration examples.
- Agent initialization: restores
snapshot_latestwhen it exists. - Agent invocation: saves
snapshot_latestafter each invocation by default. - Message addition: saves after each message with
SaveLatestStrategy::Message. - Snapshot trigger: creates an immutable snapshot when its callback returns
true. - Message redaction: persists redacted content under message and invocation strategies.
Multi-Agent Events
- Before Multi-Agent Invocation: Restores orchestrator state from
snapshot_lateston the first invocation. - After Node Call (
multi_agent_save_latest_on="node", default): Saves after each node and again when the invocation ends. - After Multi-Agent Invocation (
multi_agent_save_latest_on="invocation"): Saves only when the full invocation ends.
- Before Multi-Agent Invocation: Restores orchestrator state from
snapshot_lateston the first invocation. - After Node Call (
multiAgentSaveLatestOn: 'node', default): Saves after each node and again when the invocation ends. - After Multi-Agent Invocation (
multiAgentSaveLatestOn: 'invocation'): Saves only when the full invocation ends.
const session = new SessionManager({ sessionId: 'my-session', storage: new LocalFileStorage('./sessions/'), // Save orchestrator state after each node completes (default) multiAgentSaveLatestOn: 'node', // Or save only after the full orchestrator invocation completes: // multiAgentSaveLatestOn: 'invocation',})Graph and Swarm session events are not available.
Immutable snapshots
Section titled “Immutable snapshots”A snapshot captures agent state at a point in time.
Snapshot-based managers persist snapshot_latest and append-only immutable
snapshots identified by UUID v7. You can restore the agent to any checkpoint.
Creating immutable snapshots
Section titled “Creating immutable snapshots”Use the snapshot-trigger callback to control when an immutable snapshot is created. The callback receives the current agent data and returns a boolean:
from strands import Agentfrom strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage
session_manager = SnapshotSessionManager( session_id="my-session", storage=LocalFileStorage("./sessions/"), snapshot_trigger=lambda *, agent_data, **_: len(agent_data.messages) % 4 == 0,)
agent = Agent(session_manager=session_manager)const session = new SessionManager({ sessionId: 'my-session', storage: new LocalFileStorage('./sessions/'), // Create an immutable snapshot after every 4 messages snapshotTrigger: ({ agentData }) => agentData.messages.length % 4 === 0,})
const agent = new Agent({ sessionManager: session })await agent.invoke('First message') // 2 messages, no snapshotawait agent.invoke('Second message') // 4 messages, immutable snapshot createduse strands::session::SnapshotTriggerCallback;use strands::storage::LocalFileStorage;use strands::SessionManager;
fn main() -> strands::Result<()> { let every_four_messages = SnapshotTriggerCallback::new(|params| { params.agent_data.messages().len() % 4 == 0 }); let session = SessionManager::builder() .session_id("support-chat") .storage(LocalFileStorage::new("./sessions")) .snapshot_trigger(every_four_messages) .build()?;
let _ = session; Ok(())}Listing and restoring snapshots
Section titled “Listing and restoring snapshots”Snapshot IDs are UUID v7, so they sort lexicographically in chronological
order. Use list_snapshot_idslistSnapshotIdslist_snapshot_idsrestore_snapshotrestoreSnapshotrestore_snapshot
import asyncio
from strands import Agentfrom strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage
session_manager = SnapshotSessionManager( session_id="my-session", storage=LocalFileStorage("./sessions/"),)agent = Agent(session_manager=session_manager)
async def restore() -> None: # Force an immutable checkpoint and read it back later snapshot_id = await session_manager.save_snapshot(agent, is_latest=False) snapshot_ids = await session_manager.list_snapshot_ids(agent) assert snapshot_id in snapshot_ids await session_manager.restore_snapshot(agent, snapshot_id=snapshot_id)
asyncio.run(restore())const storage = new LocalFileStorage('./sessions/')
const session = new SessionManager({ sessionId: 'my-session', storage,})const agent = new Agent({ sessionManager: session })await agent.initialize()
// List all immutable snapshot IDs (chronological order)const snapshotIds = await session.listSnapshotIds({ target: agent,})
// Restore agent to a specific checkpointawait session.restoreSnapshot({ target: agent, snapshotId: snapshotIds[0]!,})use strands::storage::LocalFileStorage;use strands::{Agent, SessionManager};
#[tokio::main]async fn main() -> strands::Result<()> { let session = SessionManager::builder() .session_id("support-chat") .storage(LocalFileStorage::new("./sessions")) .build()?; let mut agent = Agent::builder() .session_manager(session.clone()) .printer(false) .build()?; agent.initialize().await?;
session.save_snapshot(agent.local(), false).await?; let ids = session.list_snapshot_ids(agent.local(), None, None).await?; if let Some(snapshot_id) = ids.last() { session .restore_snapshot(agent.local_mut(), Some(snapshot_id)) .await?; } Ok(())}Deleting sessions
Section titled “Deleting sessions”To remove all snapshots for a session, call the session manager’s delete method. This removes the entire session root directory (filesystem) or all objects under the session prefix (S3):
import asyncio
from strands.session import SnapshotSessionManagerfrom strands.storage import LocalFileStorage
session_manager = SnapshotSessionManager( session_id="my-session", storage=LocalFileStorage("./sessions/"),)asyncio.run(session_manager.delete_session())const session = new SessionManager({ sessionId: 'my-session', storage: new LocalFileStorage('./sessions/'),})
// Remove all snapshots and manifests for this sessionawait session.deleteSession()use strands::storage::LocalFileStorage;use strands::SessionManager;
#[tokio::main]async fn main() -> strands::Result<()> { let session = SessionManager::builder() .session_id("support-chat") .storage(LocalFileStorage::new("./sessions")) .build()?; session.delete_session().await}Data models
Section titled “Data models”SnapshotSessionManager stores a single versioned Snapshot JSON blob whose data field carries the messages, agent state, conversation manager state, interrupt state, model state, and system prompt.
The record-based models below apply to FileSessionManager, S3SessionManager, and RepositorySessionManager, which persist each message individually:
Session
The Session model is the top-level container for session data:
- Purpose: Provides a namespace for organizing multiple agents and their interactions
- Key Fields:
session_id: Unique identifier for the sessionsession_type: Type of session (currently"AGENT"for both agent & multiagent in order to keep backward compatibility)created_at: ISO format timestamp of when the session was createdupdated_at: ISO format timestamp of when the session was last updated
SessionAgent
The SessionAgent model stores agent-specific data:
- Purpose: Maintains the state and configuration of a specific agent within a session
- Key Fields:
agent_id: Unique identifier for the agent within the sessionstate: Dictionary containing the agent’s state data (key-value pairs)conversation_manager_state: Dictionary containing the state of the conversation managercreated_at: ISO format timestamp of when the agent was createdupdated_at: ISO format timestamp of when the agent was last updated
SessionMessage
The SessionMessage model stores individual messages in the conversation:
- Purpose: Preserves the conversation history with support for message redaction
- Key Fields:
message: The original message content (role, content blocks)redact_message: Optional redacted version of the message (used when sensitive information is detected)message_id: Index of the message in the agent’s messages arraycreated_at: ISO format timestamp of when the message was createdupdated_at: ISO format timestamp of when the message was last updated
These data models work together to provide a complete representation of an agent’s state and conversation history. The session management system handles serialization and deserialization of these models, including special handling for binary data using base64 encoding.
Multi-Agent State
Multi-agent systems serialize their state as JSON objects containing:
- Orchestrator Configuration: Settings, parameters, and execution preferences
- Node State: Current execution state and node transition history
- Shared Context: Cross-agent shared state and variables
The session manager stores state as a Snapshot object written to JSON. Each
snapshot contains:
data.messages: The full conversation historydata.state: Agent key-value statedata.systemPrompt: The agent’s system promptschemaVersion: Schema version for forward compatibilitycreatedAt: ISO 8601 timestamp
There are two kinds of snapshots:
snapshot_latest.json: A single mutable file overwritten on each save. Used to resume the most recent state after a restart.- Immutable snapshots (
immutable_history/snapshot_<uuid7>.json): Append-only checkpoints created whensnapshotTriggerfires. Used for time-travel restore.
SessionManager stores the versioned Snapshot JSON shape. Its data includes
messages, agent state, system prompt, model state, and interrupt state. The
manager maintains snapshot_latest.json and optional immutable snapshots under
immutable_history/.
Third-party session managers
Section titled “Third-party session managers”The following third-party session managers extend Strands with additional storage and memory capabilities:
| Session Manager | Provider | Description | Documentation |
|---|---|---|---|
| AgentCoreMemorySessionManager | Amazon | Advanced memory with intelligent retrieval using Amazon Bedrock AgentCore Memory. Supports both short-term memory (STM) and long-term memory (LTM) with strategies for user preferences, facts, and session summaries. | View Documentation |
| Contribute Your Own | Community | Have you built a session manager? Share it with the community! | Learn How |
Custom session repositories
Section titled “Custom session repositories”For advanced use cases, you can implement your own session storage backend.
For new single-agent sessions, implement a custom Storage backend and pass it to SnapshotSessionManager: the manager owns the session layout, so the backend only moves bytes.
To customize a repository-based session, implement the SessionRepository interface:
from typing import Optionalfrom strands import Agentfrom strands.session.repository_session_manager import RepositorySessionManagerfrom strands.session.session_repository import SessionRepositoryfrom strands.types.session import Session, SessionAgent, SessionMessage
class CustomSessionRepository(SessionRepository): """Custom session repository implementation."""
def __init__(self): """Initialize with your custom storage backend.""" # Initialize your storage backend (e.g., database connection) self.db = YourDatabaseClient()
def create_session(self, session: Session) -> Session: """Create a new session.""" self.db.sessions.insert(asdict(session)) return session
def read_session(self, session_id: str) -> Optional[Session]: """Read a session by ID.""" data = self.db.sessions.find_one({"session_id": session_id}) if data: return Session.from_dict(data) return None
# Implement other required methods... # create_agent, read_agent, update_agent # create_message, read_message, update_message, list_messages
# Use your custom repository with RepositorySessionManagercustom_repo = CustomSessionRepository()session_manager = RepositorySessionManager( session_id="user-789", session_repository=custom_repo)
agent = Agent(session_manager=session_manager)The simplest approach is to pass any
Storage backend directly: the
SessionManager wraps it automatically. For full control,
implement the SnapshotStorage interface:
// Implement SnapshotStorage to plug in any backendclass MyStorage implements SnapshotStorage { async saveSnapshot({ location, snapshotId, snapshot, }: { location: SnapshotLocation snapshotId: string isLatest: boolean snapshot: Snapshot }) { // Store the snapshot JSON keyed by location + snapshotId }
async loadSnapshot({ location, snapshotId, }: { location: SnapshotLocation snapshotId?: string }) { // Return the snapshot, or null if not found return null }
async listSnapshotIds({ location, }: { location: SnapshotLocation limit?: number startAfter?: string }) { // Return immutable snapshot IDs sorted chronologically return [] }
async deleteSession({ sessionId }: { sessionId: string }) { // Remove all stored data for this session }
async loadManifest({ location, }: { location: SnapshotLocation }): Promise<SnapshotManifest> { return { schemaVersion: '1', updatedAt: new Date().toISOString(), } }
async saveManifest({ location, manifest, }: { location: SnapshotLocation manifest: SnapshotManifest }) { // Persist the manifest }}
const agent = new Agent({ sessionManager: new SessionManager({ sessionId: 'user-789', storage: { snapshot: new MyStorage() }, }),})Implement the Storage trait and pass the backend to SessionManager. The
manager owns the key layout, serialization, and snapshot lifecycle.
This lets you store session data in any backend while reusing the built-in session management logic.
Data layout
Section titled “Data layout”Both file and S3 backends use the same key structure:
SnapshotSessionManager layout for new single-agent sessions. The Storage
backend prepends a session/ namespace:
<root>/└── session/ └── <session_id>/ └── scopes/ └── agent/ └── <agent_id>/ └── snapshots/ ├── snapshot_latest.json └── immutable_history/ └── snapshot_<uuid7>.jsonRepository-based layout (FileSessionManager, S3SessionManager):
<root>/└── session_<session_id>/ ├── session.json ├── agents/ │ └── agent_<agent_id>/ │ ├── agent.json │ └── messages/ │ ├── message_0.json │ └── message_1.json └── multi_agents/ └── multi_agent_<orchestrator_id>/ └── multi_agent.jsonUsing the same session ID and storage location does not migrate
repository-based data to SnapshotSessionManager. Existing sessions can
continue using their current manager, or applications can migrate the required
state explicitly.
FileSessionManager creates a new storage directory with mode 0o700. It
leaves existing permissions unchanged and, on POSIX systems, emits a
UserWarning when the directory is accessible by group or others. It refuses
to read or write a session file that is itself a symlink, but still follows
symlinked directories.
<root>/└── <sessionId>/ └── scopes/ ├── agent/ │ └── <agentId>/ │ └── snapshots/ │ ├── snapshot_latest.json │ └── immutable_history/ │ └── snapshot_<uuid7>.json └── multiAgent/ └── <orchestratorId>/ └── snapshots/ └── snapshot_latest.json<root>/└── session/ └── <session_id>/ └── scopes/ └── agent/ └── <agent_id>/ └── snapshots/ ├── snapshot_latest.json └── immutable_history/ └── snapshot_<uuid7>.jsonSessions, agents, and concurrency
Section titled “Sessions, agents, and concurrency”Session management is designed around a single live writer per conversation:
the session ID plus the agent ID
(agent_ididid
One conversation per session
Section titled “One conversation per session”Give each conversation its own session ID. Several agents can share one session ID as long as their agent IDs differ: the session acts as a namespace, and each agent keeps its own messages and state inside it. A single agent instance processes one invocation at a time by default and rejects overlap, as described in Concurrent Invocations.
Create an agent per conversation
Section titled “Create an agent per conversation”Constructing an agent is cheap: it wires up tools, hooks, and plugins locally and makes no model call. Build one per request, invoke it, and let it go out of scope. The model provider is the part worth reusing: providers such as BedrockModel build their client in the constructor, so create the provider once per process and pass the same instance to every agent.
Common failure modes
Section titled “Common failure modes”The built-in session managers take no distributed lock, and the single-instance invocation guard is in-process, so neither can detect a second writer running elsewhere. Two patterns result:
- Two live agents addressing the same session ID and agent ID. The default
IDs
(
) make this easy to do by accident, including across separate executions that each build their own agent. Overlapping invocations overwrite each other’s turns, sequential ones merge two conversations into one history, and neither call errors.agent_id="default"id: 'agent'.id("agent") - Two callers creating the same session at the same time. Session creation is a check followed by a write, not an atomic operation, so simultaneous cold starts on a new session ID can both succeed, with the later write winning.
Session persistence best practices
Section titled “Session persistence best practices”When implementing session persistence in your applications, consider these best practices:
- Use Unique Session IDs: Generate unique session IDs for each user or conversation context to prevent data overlap.
- Session Cleanup: Implement a strategy for cleaning up old or inactive sessions. Consider adding TTL (Time To Live) for sessions in production environments.
- Understand Persistence Triggers: Remember that changes to agent state or messages are only persisted during specific lifecycle events.
- Concurrent Access: Built-in session managers provide no cross-process or distributed coordination. Use one live writer per conversation. See Sessions, Agents, and Concurrency.
- Secure Storage Directories: Treat the session storage directory as a trusted data store. Session state is trusted input, so do not load session files from untrusted sources, such as a cloned repository. Restrict filesystem permissions to the agent process. In shared or multi-tenant environments, do not allow untrusted users to create files or symlinks in the directory. A malicious link could load sensitive file contents into the conversation history.