Session Persistence
Save conversation history across app launches, devices, or users. Pick from file storage for local use or S3 for cross-device sync.
Overview
By default, an agent's conversation history lives in memory and is lost when the agent is deallocated. A SessionManager persists messages after each exchange, so conversations survive app restarts and can be restored on any device.
File Storage
Best for single-device use. Messages are written atomically to disk after each turn:
import StrandsAgents
let sessionsDir = FileManager.default.urls(
for: .applicationSupportDirectory, in: .userDomainMask
)[0].appendingPathComponent("Sessions")
let repo = FileSessionRepository(directory: sessionsDir)
let manager = RepositorySessionManager(sessionId: "user-123", repository: repo)
let agent = Agent(
model: provider,
sessionManager: manager
)
// First run: history saved automatically
_ = try await agent.run("My name is Alex.")
// Restart app, recreate agent with the same sessionId
let restoredManager = RepositorySessionManager(sessionId: "user-123", repository: repo)
let restoredAgent = Agent(model: provider, sessionManager: restoredManager)
let result = try await restoredAgent.run("What's my name?")
print(result.output) // "Your name is Alex."
S3 Storage
Best for multi-device or multi-user apps. Sessions are stored in an S3 bucket with a per-user prefix:
import StrandsAgents
let repo = S3SessionRepository(
bucket: "my-app-sessions",
prefix: "users/\(userId)/"
)
let manager = RepositorySessionManager(sessionId: "conversation-1", repository: repo)
let agent = Agent(model: provider, sessionManager: manager)
Session IDs
The session ID is an arbitrary string that identifies a conversation. Use whatever makes sense for your data model:
"user-\(userId)"for one persistent conversation per user"chat-\(UUID())"for a new conversation per session"support-ticket-\(ticketId)"for a conversation tied to a support ticket
Storage Guarantees
| Feature | File | S3 |
|---|---|---|
| Atomic writes | ✓ | ✓ |
| Version tracking | ✓ | ✓ |
| Broken history repair | ✓ | ✓ |
| Cross-device sync | -- | ✓ |
| Offline access | ✓ | -- |
Combine S3 storage with a sliding window conversation manager to keep token usage bounded while retaining an unlimited persistent history in S3.