Help improve this page
To contribute to this user guide, choose the Edit this page on GitHub link that is located in the right pane of every page.
Store agent session state
An agent’s model call is stateless, so the agent itself carries everything that connects one turn to the next: the conversation so far, intermediate results, and files it’s working on. Where that state lives decides whether an agent survives a pod restart, whether more than one replica can serve it, and whether one agent can read another’s sessions.
Agent state has three lifetimes, and each one needs a different kind of storage:
| Lifetime | Where it goes | Why |
|---|---|---|
|
Between turns |
Key-value cache outside the pod |
Any replica serves the next turn, and a restart keeps the session. |
|
Between tiers |
A workspace volume |
The execution tier has no network, so files are its only channel. |
|
After the session |
Amazon S3, per-agent prefix |
Checkpoints, results, and the record of the agent’s actions. |
The following diagrams show each path.
Open source and AWS services paths
The following table compares how each path provides session state.
| Aspect | Open source | AWS services |
|---|---|---|
|
Cache |
Valkey in the cluster |
Amazon ElastiCache Serverless |
|
Authentication |
A password stored in a Kubernetes Secret, which |
IAM. Each agent signs a short-lived token with its own role, and no password is stored. |
|
Connection |
Plaintext inside the cluster |
TLS only |
|
Who operates the cache |
You operate its upgrades, capacity, and failover |
The managed service, which scales with load |
|
Durable state |
A versioned Amazon S3 bucket with one prefix per agent |
A versioned Amazon S3 bucket with one prefix per agent |
|
Separation between agents |
One shared cache with one credential. See Isolate agents that share a cache. |
One shared cache with one credential. See Isolate agents that share a cache. |
Cache between turns
State kept in the pod disappears when the pod restarts, and it ties a session to one replica. A key-value cache outside the pod fixes both. A restarted or replaced pod continues the session, and any replica behind a Service can serve the next turn. The second point matters more for agents than for web applications, because agent protocols such as MCP have no cookie to pin a session to one replica (see Give an agent tools with MCP).
You need the cache when an agent runs more than one replica, or when a restarted pod must continue a task in progress. An agent that runs as one long-lived sandbox, the default runtime, is capped at one replica, so multiple replicas apply to agents that run as a Deployment. The reference agent saves its conversation to Amazon S3, not to the cache (see Save the conversation between turns). The cache holds the working state that changes within a task.
The cache can run in the cluster or as a managed service:
-
Valkey in the cluster keeps the cache next to the agents and under your control. You operate its upgrades, capacity, and failover, and it authenticates with a password stored in a Kubernetes Secret.
-
Amazon ElastiCache Serverless removes the cache tier from your operations and scales with load. It authenticates with IAM, so each agent signs a short-lived token with its own credentials and no password is stored.
Either cache works on both paths, and you can mix components from both paths.
Isolate agents that share a cache
A cache is usually shared by every agent in the cluster, and a shared cache with one credential lets any agent read and overwrite any other agent’s keys. A prompt injection can make an agent do exactly that, so isolation has to be enforced by the cache, not by the agent’s code. A key prefix that only the application applies isn’t a boundary, because a compromised agent can choose any key.
The sample deploys a shared cache with one credential, which is acceptable for a single agent. Before several agents share it, separate them in one of these ways:
-
A cache user per agent, limited to the agent’s key prefix. Valkey ACLs and ElastiCache access strings both restrict a user to a key pattern, such as
~agent:research:*, and to non-administrative commands. The cache returnsNOPERMfor another agent’s keys. With IAM authentication, each agent’s role must permitelasticache:Connecton its own user only, or the agent can present another agent’s user. -
A separate cache per agent, or per group of agents that may share state. This costs more and gives the strongest separation.
Whichever you choose, require authentication, because a cache that answers an unauthenticated PING with PONG is open to every pod that network policy lets reach it. In ElastiCache, also turn off the default user that every user group must contain. Keep key names non-sensitive, because a key-pattern restriction protects values but leaves key names enumerable. The default users-per-user-group quota supports dozens of agents, and you can request an increase for more.
Workspace volume between tiers
When an agent is split into reasoning and execution tiers (Isolate agent workloads on Amazon EKS), they exchange data only through a volume. The reasoning tier writes files to the volume and runs commands in the execution tier over the sandbox’s control channel. The execution tier writes results back to the volume.
Because the execution tier has no network, only some storage types work there:
| Storage | In a network-isolated sandbox | Use it for |
|---|---|---|
|
Amazon EBS |
Yes |
A per-session workspace. The CSI driver attaches it from outside the guest, so the pod needs no network. |
|
Amazon EFS |
No |
Shared read-write workspaces for pods with a network, such as the reasoning tier, because the mount needs one. |
|
Amazon S3 |
Not directly |
Durable data. The reasoning tier copies objects onto the volume and results back to Amazon S3. |
For the full storage matrix for sandboxed pods, see Storage with Nitro Sandboxes.
Durable state in Amazon S3
Use Amazon S3 when state must outlive the pod: checkpoints the agent resumes from, the record of its actions, and files returned by the execution tier. This is the same on both paths, and it’s off in the base setup in the reference sample (enable_checkpoints = false). S3 and the cache are separate layers. An agent typically accesses S3 once per session and the cache once per turn.
Configure the bucket as follows:
-
One prefix per agent, enforced in IAM. Each agent’s role permits only its own prefix, so a request for another agent’s prefix returns
AccessDenied. Verify the scoping describes how to verify this. -
Versioning. An agent can overwrite its checkpoint with a bad one. Versioning lets you restore the previous checkpoint.
-
A data perimeter in the bucket policy. Restrict access to principals and networks in your organization.
Save the conversation between turns
An agent that is constructed per request starts each turn with no history unless the conversation is saved. The reference agent uses session managers from the Strands Agents SDK:
-
S3SessionManager(when a bucket is configured). Writes the conversation under the agent’s prefix after every turn and reloads it when the session continues, on any replica or after a restart. -
FileSessionManager(on a sandbox with a workspace volume and no bucket). Keeps the conversation on the volume, so it survives suspend and resume.
Key saved sessions on the verified caller identity and the session ID together. The caller chooses the session ID, so a store keyed on the ID alone lets one caller load another’s conversation by guessing it. The reference agent keys on a digest of both.
The egress policy permits the bucket’s virtual-hosted endpoint, bucket.s3.region-code.amazonaws.com, not the Regional endpoint s3.region-code.amazonaws.com. The Regional endpoint serves every bucket. The agent’s IAM role limits only requests signed with the agent’s credentials. It does not limit anonymous requests or presigned URLs signed by someone else. For those requests, the egress rule is what keeps the pod away from other buckets.
Beyond session state
Session state is one of four memory capabilities, and most agents with more than one turn need it. Semantic recall and consolidation across sessions are separate components. See Choose an agent’s memory components before you add either.
Session state in the reference sample
The base setup turns off both the cache and durable storage. enable_session_state turns on the cache, shared by all agents through one credential. enable_checkpoints turns on the versioned bucket and gives each agent a grant scoped to its own prefix.
-
Open source path. The cache is Valkey in the cluster.
enable_platform_secrets, which is on by default, generates the cache password and the stack’s other passwords outside Git. Set it tofalseonly if you create those Secrets yourself. -
AWS services path. The cache is ElastiCache Serverless.
enable_platform_secrets doesn’t manage credentials for third-party APIs, which Call third-party APIs from agents without giving them credentials covers.
Prerequisites
-
The base setup from Set up an Amazon EKS cluster for agent workloads, applied, and the in-cluster components from Set up EKS Capabilities and in-cluster components for agents, synced.
-
Permissions to run
terraform applyfor the bucket and, on the AWS services path, the ElastiCache Serverless cache. -
PAVED_PATHset toopen-sourceoraws-services, such as withexport PAVED_PATH=open-source. -
A shell with
kubectlaccess to the cluster, on the bastion or your workstation, and an agent deployed as in Deploy an agent on Amazon EKS. The commands use the reference agentresearchin namespaceagents.
Step 1: Turn on session state
This step turns on the cache, the bucket, or both. With enable_session_state, each agent gets the endpoint in SESSION_STATE_ENDPOINT and a network policy rule permitting it. With enable_checkpoints, Terraform creates a versioned bucket whose policy limits access to principals in your account or organization, and gives each agent a prefix-scoped IAM grant, an egress rule for the bucket’s endpoint, and CHECKPOINT_BUCKET and CHECKPOINT_PREFIX in its environment. Outside these templates, create the same cache and bucket, scope each agent’s credentials, and pass the endpoint and bucket to the agent as environment variables.
The bootstrap script applies the rendered root Application, refreshes and syncs it, and waits for the Applications to converge. With --roll-agents, it then recreates each agent pod whose Sandbox changed, and prints a line for each agent, such as agents/research: recreating (env SESSION_STATE_ENDPOINT added), or current for an agent that didn’t change.
Every Application reports Synced and Healthy. If one stays Progressing after its objects are ready, run the bootstrap script again, because Argo CD can keep the health it computed while they were starting. See Turn on a component later.
A Sandbox doesn’t replace its running pod when its spec changes, so without --roll-agents a sandboxed agent keeps running without the cache endpoint. The --roll-agents on the sync recreates the pod. To confirm that the agent’s Sandbox has SESSION_STATE_ENDPOINT, run the following:
./scripts/run-stack.sh --root terraform/$PAVED_PATH -- bash -c "kubectl -n agents get sandbox research -o yaml | grep -A1 SESSION_STATE_ENDPOINT"
An agent with runtime: deployment rolls automatically.
After the restart, the Agent resource has put the state settings in the agent’s environment. On the AWS services path with both components on, they look like the following:
env: - name: SESSION_STATE_ENDPOINT # the cache; on the open source path, the Valkey Service in agent-memory value: my-agents-agent-session-abc123.serverless.usw2.cache.amazonaws.com:6379 - name: CHECKPOINT_BUCKET value: my-agents-agent-checkpoints-111122223333 - name: CHECKPOINT_PREFIX # set by the stack, never by the model value: agents/research/
CHECKPOINT_PREFIX is configuration rather than a tool argument, so the model never sees it as something it can choose. A write outside the prefix also fails, because the agent’s IAM role allows only that prefix.
The reference agent saves its conversation with a Strands Agents SDK session manager. The following excerpt shows the choice it makes on each turn:
import hashlib, os from strands.session import FileSessionManager, S3SessionManager def session_manager(user_id: str, session_id: str): # Key on the verified caller as well as the session ID, so one caller can't load another's conversation. key = hashlib.sha256(f"{user_id}\0{session_id}".encode()).hexdigest()[:40] bucket = os.environ.get("CHECKPOINT_BUCKET") if bucket: prefix = os.environ["CHECKPOINT_PREFIX"].rstrip("/") + "/sessions" return S3SessionManager(session_id=key, bucket=bucket, prefix=prefix, region_name=os.environ.get("AWS_REGION")) if os.environ.get("AGENT_WORKSPACE_PERSISTENT") == "true": # No bucket: keep the conversation on the workspace volume, which survives suspend and resume. return FileSessionManager(session_id=key, storage_dir="/workspace/.sessions") return None # no durable state: each turn stands alone
The session manager saves the agent’s messages after each turn and loads them when an agent is built with the same key, so another replica or a restarted pod continues the conversation.
Step 2: Verify the cache refuses an unauthenticated caller
This step confirms that the cache requires a credential. Run the check from the agent’s pod. A check from your workstation can report an open cache as closed. The command names the pod research, as on the default runtime. For an agent with runtime: deployment, use deploy/research instead.
The check passes when it returns an authentication error, such as -NOAUTH Authentication required. That confirms the agent can reach the cache through network policy and that the cache requires a credential. A PONG reply means the cache is open. Right after the apply that creates the cache, the connection can time out while the cache starts. Run the check again before you look at network policy.
An agent that uses the cache must then authenticate. The reference agent doesn’t use the cache itself, so write this part into your agent.
The state and session phases of the sample’s exercise.sh also run an authenticated round trip, and confirm that a saved conversation continues in a new process and that another caller cannot read it.
./scripts/exercise.sh --path $PAVED_PATH state session
Clean up
To remove the session cache and durable checkpoints, first prepare the checkpoint bucket, because the apply that turns checkpoints off deletes it. Copy out any conversations you want to keep. Then either empty the bucket, including every object version, or set checkpoint_bucket_force_destroy = true and apply once while checkpoints are still on. Terraform deletes the bucket with the setting from its last apply, so the setting has no effect if you set it in the same apply that deletes the bucket.
Then turn both off as described in Turn on a component later. Set enable_session_state and enable_checkpoints to false, apply with scripts/apply.sh, and run the bootstrap script with --sync --prune.
Next steps
-
Give each agent its own identity with EKS Pod Identity for the per-agent IAM scoping the S3 prefix depends on.
-
Choose an agent’s memory components for semantic recall and consolidation.