[KongchangAI]
· 2 min read· 1,288 words

Vercel Sandbox Launches Session Lifecycle Webhooks: Expiry Warnings, Stop Reasons, and Usage Metrics

Vercel Sandbox Launches Session Lifecycle Webhooks: Expiry Warnings, Stop Reasons, and Usage Metrics

Vercel Sandbox adds session lifecycle webhooks, letting Agents manage sandbox timeouts and resources via events instead of polling.

Vercel Sandbox introduces three session lifecycle webhook events—started, expiring, and stopped—so backends can receive accurate signals instead of polling. The expiring event fires 1 minute before timeout (customizable via expiryNotificationLeadTime) and rolls over after each extension; the stopped event includes stop reason, session duration, active CPU time, and network transfer. Agents can also subscribe via Vercel MCP and call extend_session_timeout, or consume events in Workflow SDK without polling. Idempotent handling keyed by session ID is required.

Vercel Sandbox has recently rounded out its session lifecycle event notification capabilities: when a sandbox session becomes ready, approaches its timeout, or is stopped, the platform pushes events to team webhooks. This isn't a flashy feature launch, but it solves the hardest part of "state synchronization" between AI Agents and long-running task sandboxes—previously, backends could only guess session state by polling; now they can passively receive accurate signals.

Vercel Sandbox session lifecycle webhook announcement

Three Events Covering the Full Session Lifecycle

Vercel Sandbox provides three subscribable events: sandbox.session.started, sandbox.session.expiring, and sandbox.session.stopped. The subscription entry point is in the team's webhook settings, and each event carries sandbox and session details, allowing backends to precisely locate affected sessions.

The value of this design lies in replacing "state queries" with "event-driven" notifications. For sandboxes running code execution, browser automation, or long-running inference tasks, whether a session is still alive and when it will be reclaimed directly determines whether the upper-layer application should continue waiting, extend, or clean up resources.

Expiring Warnings: A One-Minute Window to Extend

The most noteworthy event is sandbox.session.expiring. Vercel sends a reminder 1 minute before a session times out, and this lead time can be customized via expiryNotificationLeadTime. More subtly: each time a session is extended, the platform sends another warning 1 minute before the new timeout, creating rolling warnings.

This means an Agent can reassess "does this task still need to continue?" at each warning, rather than setting a single timeout value at startup that may be too long or too short. For on-demand billed sandbox resources, this dynamic renewal balances both task success rate and cost control.

Rolling expiry notification means that each time a session's timeout is extended, the platform triggers sandbox.session.expiring again before the new expiration time, rather than firing only once at session creation. This mechanism requires handlers to treat expiring events not as a one-time terminal signal, but as periodic reminders that "the current deadline is approaching." In implementation, the backend should always use the event's sandbox.expiresAt (or equivalent field) as the decision basis: only execute renewal logic when the new expiresAt is later than the locally recorded previous value; otherwise, the event is a duplicate delivery of an old warning. The difference between rolling warnings and a fixed single warning determines whether an Agent can dynamically decide how long to extend based on task progress, rather than gambling on a timeout value at startup.

Stopped Events: With Stop Reasons and Usage Details

sandbox.session.stopped has the highest information density. The event includes a stop reason with values requested, snapshot, timeout, exited, or error, along with session duration, active CPU time, and network transfer volume.

These fields let backends distinguish "normal completion" from "abnormal interruption": stopping due to timeout usually means the task was not completed and needs retry or extension strategy; error may require alerting. Active CPU time and network transfer volume provide raw data for usage accounting and performance analysis.

The TypeScript example in the article directly demonstrates destructuring these fields in a verified webhook handler:

if (event.type === 'sandbox.session.stopped') {
  const { id, stopReason, activeCpuDurationMs, networkTransfer } =
    event.payload.session;
  console.log({ id, stopReason, activeCpuDurationMs, networkTransfer });
}

Idempotent Handling Is Mandatory

Vercel explicitly warns that events may be delivered more than once, so handlers must be idempotent keyed by session ID; for expiring events, combine with sandbox.expiresAt to avoid treating an old warning as a new one. This is a classic webhook system pitfall, and calling it out directly in the docs can save considerable production debugging time.

Agents Can Subscribe Too: Two Paths via MCP and Workflow

Beyond traditional backend webhooks, Agents can also subscribe to the same events through Vercel MCP. An Agent that created a sandbox can listen for sandbox.session.expiring and then call extend_session_timeout to keep the session alive—this effectively hands the "renewal decision" to the party executing the task, rather than an external scheduler.

The other path is integration with the Workflow SDK. The official example uses defineHook<SandboxSessionEvent>() to define a hook that consumes events in a loop within a workflow: when expiring is received and the Agent is still working, extend by 10 minutes; when stopped is received, exit the loop. This way the workflow can continuously renew the sandbox while the Agent keeps working, without polling.

export const sandboxEvents = defineHook<SandboxSessionEvent>();

export async function agentTask(taskId: string, sandboxName: string) {
  'use workflow';
  const sandboxHook = sandboxEvents.create({ token: sandboxName });
  for await (const { type } of sandboxHook) {
    if (type === 'sandbox.session.expiring' && (await isAgentWorking(taskId))) {
      await extendSession(sandboxName, ms('10m'));
    }
    if (type === 'sandbox.session.stopped') break;
  }
}

Vercel MCP (Model Context Protocol) is Vercel's MCP service endpoint that lets AI Agents access platform capabilities via standardized tool calls. MCP itself is an open protocol that defines the discovery and invocation interface between models and external tools/data sources: the server declares available tools (such as extend_session_timeout), and the client (Agent runtime) can call them on demand during reasoning. The difference from backend webhooks is the actor—webhooks are passively received by team servers, while MCP makes the Agent executing the task itself the event consumer and decision-maker. Note that MCP subscriptions typically rely on the Agent runtime maintaining a connection or periodically pulling, and event delivery semantics are not fully identical to webhooks; design renewal logic to handle both duplication and loss possibilities separately.

Significance for Agent Infrastructure

Sandbox lifecycle management has long been a hidden pain point in Agent engineering: set timeouts too short and tasks get interrupted; set them too long and idle resources are wasted; and polling introduces latency and extra calls. By turning all three nodes—started, expiring, stopped—into events and opening up customizable warning lead time, Vercel effectively extracts the question "is the session still alive?" from application-layer logic and hands it to the platform's event stream.

Combined with the MCP and Workflow SDK integration paths, it's clear Vercel's intent isn't just to provide a webhook, but to make sandboxes an orchestratable node in Agent workflows. For teams building long-running Agents, this event mechanism is worth prioritizing in evaluation.

Workflow SDK and defineHook are Vercel's tools for writing durable, resumable workflows. Traditional long-running tasks lose in-memory state after process restarts or function timeouts; Workflow uses durable execution to record progress at each step, allowing functions to be suspended and resumed without rerunning from scratch. defineHook<T>() defines a suspension point that can be awakened by external events: the workflow pauses here and waits for an event matching the token to arrive, then continues from the breakpoint. In the example, for await (const { type } of sandboxHook) is the syntax for continuously consuming the event stream. Understanding this is key—durable execution is what makes "waiting for sandbox events without polling" feasible in serverless environments; ordinary functions cannot remain suspended for long periods waiting for webhook callbacks.

One-line Summary

Vercel Sandbox adds session lifecycle webhooks, letting Agents manage sandbox timeouts and resources via events instead of polling.

Paragraph Summary

Vercel Sandbox has completed its session lifecycle event notification capabilities with three webhook events—sandbox.session.started, sandbox.session.expiring, and sandbox.session.stopped—shifting backends from polling session state to passively receiving accurate signals. The expiring event fires 1 minute before timeout by default, supports custom lead time via expiryNotificationLeadTime, and rolls over with each session extension; the stopped event carries stop reasons (requested/snapshot/timeout/exited/error) plus session duration, active CPU time, and network transfer, helping distinguish normal completion from abnormal interruption. Beyond traditional backend webhooks, Agents can subscribe via Vercel MCP and call extend_session_timeout for self-service renewal, or use Workflow SDK's defineHook to consume events in a workflow without polling. The article also stresses idempotent handling keyed by session ID and using sandbox.expiresAt to judge whether expiring events are old or new.

Share:

Related articles