Run an Agents API Session in Cloudflare Without Losing State

To resume an Agents API workload safely, make the OpenAI session ID—not a Worker instance or container process—the durable identity of the job. Store that ID with your application record, send every follow-up to the same session, and allow Cloudflare to replace the executor when necessary.
Do not treat process memory or the container filesystem as the source of truth. The Cloudflare reference integration maintains a container for each Codex session, reconnects it when follow-up input arrives, and shuts it down after idle periods, while OpenAI manages the session, orchestration, context compaction, and recovery.
Assign one owner to each kind of state

Separate state into three layers before deployment. A restarted executor can then resume the conversation without creating the false impression that its local processes and files are equally durable.
- OpenAI-managed state: the Agents API session, its identifier, and the conversation and orchestration state associated with it.
- Application state: the mapping between your user or job and the session ID, ownership data, idempotency records, and business status such as queued, awaiting approval, completed, or failed.
- Execution state: checked-out source, generated files, running processes, caches, and installed artifacts inside the container.
Persist at least your job ID, the OpenAI session ID, the owning principal, and the last accepted status or event marker. That record must be sufficient to locate the existing session after a Worker restart, without relying on a live container.
Do not confuse an Agents API session with the client-side memory abstraction in the Agents SDK. The Agents SDK session guidance says an SDK session is usually unnecessary when the same history is already retained through server-managed conversation state; it also describes MemorySession as process-local storage that disappears when the process exits. Use application storage for routing and business metadata, not as an automatic duplicate transcript.
Deploy the smallest complete executor
The reference topology consists of a Cloudflare Worker receiving signed OpenAI webhooks, a session-named Durable Object controlling the executor, and a container running codex exec-server against /workspace. The executor connects outbound to OpenAI, so it does not need a public interactive shell.
- Create the OpenAI agent and retain its agent ID in deployment configuration.
- Create separate application and executor API keys. Restrict the executor key to model reads and agent-environment connections; keep the application key used to retrieve session state in the Worker.
- Generate a separate secret for the executor cleanup endpoint. Store credentials as Worker secrets or runtime environment values, never in the Dockerfile or repository.
- Deploy the Worker and container, register the public webhook endpoint and signing secret, and subscribe to the created, action-required, in-progress, idle, and failed session events.
- Check the health endpoint and require both general and webhook configuration to be ready before accepting jobs.
The current Cloudflare deployment tutorial documents these components, credential scopes, webhook events, security boundaries, and lifecycle controls. Its reference configuration keeps a container available for 30 seconds by default, with a configurable timeout; prewarming and idle snapshots are enabled by default.
Create once, then reconnect to the session

For a new job, create a self-hosted Agents API session with /workspace as its workspace directory. Store the returned session ID atomically with your job record before accepting follow-up input, and apply an idempotency rule to creation requests so a timeout does not attach one logical job to two sessions.
Post new input to the stored session’s events endpoint and consume the event stream. If the browser or application loses that stream, reopen it and continue through the existing session instead of creating a replacement merely because the transport connection closed.
Later input must carry the same session ID. In Cloudflare’s reference lifecycle, the resulting action-required webhook makes the Worker retrieve the current OpenAI state, verify that the configured agent owns the session, and then reuse a matching container or restore the saved execution environment.
Separate idle recovery from file durability
An idle container stopping does not delete the OpenAI session. Activity extends the executor lifecycle deadline; when the session becomes idle, the reference Worker can snapshot the container and stop it after the deadline, retaining that snapshot for the next connection.
Snapshots are currently a private-beta, best-effort recovery mechanism, not durable backup. When snapshots are unavailable or disabled, the next executor receives a fresh /workspace; failed or deleted sessions and explicit cleanup also clear saved snapshots.
Put irreplaceable inputs and required outputs in durable storage. A snapshot may accelerate reconnection, but recovery must still work when it does not exist. Rebuild disposable dependencies from a pinned image and lockfiles instead of assuming that a warmed container is permanent infrastructure.
Restrict secrets, network access, and attachment
Agent-generated commands can read values exposed inside their container, including the executor credential. Keep the controller key, webhook signing secret, and cleanup secret in the Worker; expose only the restricted executor key to codex exec-server and rotate it independently.
Limit outbound access to OpenAI and explicitly approved dependencies where the workload permits. Inject destination-specific credentials only when tools require them. Leave the webhook reachable by OpenAI, verify its signature, and protect application and cleanup routes separately.
Keep one execution environment associated with each session and verify ownership during reconciliation. Possession of another session ID must not be enough to attach to its container, inspect its files, or invoke cleanup.
Prove recovery before production

A successful initial prompt covers only the happy path. Run failure drills against each state boundary:
- Write a marker file, let the executor pass its idle deadline, and send follow-up input to the same session. Repeat with snapshots disabled: conversation state should remain available even though the ephemeral file does not.
- Disconnect the event stream during work, reopen it without creating a new session, and confirm that the application still maps the result to the original job.
- Restart the Worker or executor and verify that recovery depends only on the durable job-to-session mapping.
- Deliver the same webhook or client request twice and confirm that idempotency controls prevent duplicate side effects.
- Simulate a failed session and a missing-session response; verify that the executor stops, its snapshot is cleared, and the application records a terminal state.
- Test explicit deletion of both resources. Deleting the OpenAI session does not send a container-cleanup webhook, so immediate executor cleanup requires a separate authenticated request.
The deployment is durable when conversation continuity follows the OpenAI session ID, business continuity follows the application record, and required file continuity follows durable storage. Those guarantees are independent; a container snapshot can improve recovery speed but cannot replace any of them.
Also read:
Subscribe to our newsletter
Get the latest Web3, AI, and crypto news delivered straight to your inbox.