In Cloudflare Browser Run, what does keep_alive change, and how does a Worker reuse a session with sessions() and connect() instead of launching per request?
answer
- an idle timer, not a lifetime
- 60 seconds default, 600000 ms max
- list, attach, fall back to launch
- disconnect, never close a shared browser
- one browser context per request
basics
~20 sA Browser Run browser closes after 60 idle seconds; keep_alive raises that idle timeout to at most 10 minutes. To reuse one, find it with sessions(), attach with connect(), work in a new browser context, then disconnect.
solid answer
~40 sEach `puppeteer.launch()` starts a new browser: it pays the cold start and counts against the concurrent-browser limit and the new-browser rate (3 per second on Workers Paid, one every 20 seconds on Free). `keep_alive`, in milliseconds up to `600000`, is an **inactivity** timeout, so a session that gets a command inside the window lives on. To reuse, call `puppeteer.sessions(env.MYBROWSER)`, attach with `puppeteer.connect(env.MYBROWSER, sessionId)`, and fall back to `launch()` when no session answers. As of 2026-10-10 a session accepts several concurrent connections, so each request opens its own `browser.createBrowserContext()` to keep cookies and storage apart, closes the context, then calls `browser.disconnect()`; `browser.close()` would end the browser for every other client. In `@cloudflare/playwright`, `acquire()` and `connect()` do the same, and `browser.close()` on a connected browser only disconnects.
code
typescript · 33 linesimport puppeteer, { type Browser } from "@cloudflare/puppeteer";
interface Env {
MYBROWSER: Fetcher;
}
async function getBrowser(env: Env): Promise<Browser> {
for (const { sessionId } of await puppeteer.sessions(env.MYBROWSER)) {
try {
return await puppeteer.connect(env.MYBROWSER, sessionId);
} catch {
// the session closed after it was listed; try the next one
}
}
return puppeteer.launch(env.MYBROWSER, { keep_alive: 120000 });
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const target = new URL(request.url).searchParams.get("url") ?? "https://example.com";
const browser = await getBrowser(env);
const context = await browser.createBrowserContext();
try {
const page = await context.newPage();
await page.goto(new URL(target).toString());
const png = await page.screenshot();
return new Response(png, { headers: { "content-type": "image/png" } });
} finally {
await context.close();
await browser.disconnect(); // leave the shared browser running
}
},
};go deeper
Recall the numbers: a browser idles out after 60 seconds, and keep_alive extends that to at most 10 minutes, set in milliseconds.
Walk through sessions(), connect(), the launch() fallback and disconnect(), and say why each request gets its own browser context.
Show the failure handling: sessions that vanish between listing and attaching, crashes from too many heavy tabs, and the difference between close() in the Puppeteer and Playwright forks.
Weigh a long keep_alive, which bills idle time, against launch cost and the new-browser rate, and decide where per-customer isolation needs a context or a separate browser.
## Launch versus reuse By default every Browser Sessions request (Puppeteer, Playwright or raw Chrome DevTools Protocol) **launches** a new browser. That costs a cold start of the browser on every request and spends two separately limited resources: - **concurrent browsers**: 3 per account on Workers Free, 200 by default on Workers Paid; - **new browser instances**: one every 20 seconds on Free, 3 per second on Paid. **Reusing** a session means leaving a browser running after one request and attaching the next request to it. For a Worker that screenshots thousands of customer pages a day for link previews, reuse turns thousands of launches into a handful. ## keep_alive is an idle timer A Browser Run session closes after **60 seconds without a command**. The `keep_alive` launch option, in milliseconds, raises that to at most 10 minutes: ```js const browser = await puppeteer.launch(env.MYBROWSER, { keep_alive: 600000 }); ``` It is not a maximum lifetime. A session that receives a command inside its window keeps running for as long as traffic keeps it busy, so a steady stream of preview requests can hold one browser for hours. Idle time inside the window is still browser time, so a long `keep_alive` on a quiet Worker is paid for. ## Finding and attaching to a session The Puppeteer fork adds session methods to the library. A reuse-first request does this: 1. `puppeteer.sessions(env.MYBROWSER)` lists running sessions with their `sessionId`; 2. `puppeteer.connect(env.MYBROWSER, sessionId)` attaches to one, opening a new CDP connection; 3. if the session has closed since it was listed, or is already as busy as you allow, try the next one; 4. only when none answers, `puppeteer.launch()` a new browser. `browser.sessionId()` returns the ID of the browser you hold. The Playwright fork offers `acquire()` to start a session and return its ID, and `connect()` to attach to it. A Durable Object that keeps one browser and extends its life with alarms is another pattern; the Durable Objects material covers alarms. ## Isolation inside a shared browser Since 2026-09-29 several Workers can hold connections to the same session at once. They share one browser process, so each request should work inside its own **browser context** (`browser.createBrowserContext()` in Puppeteer, `browser.newContext()` in Playwright). A context keeps its own cookies, local storage and cache, so one customer's page cannot see another's state. Tabs and contexts inside a session count against neither the concurrent-browser nor the new-browser limit, but they share memory. Too many heavy pages in one browser can crash Chromium, which closes the session for every client. ## Closing versus disconnecting | Call | Puppeteer fork | Playwright fork | |---|---|---| | `browser.close()` | ends the browser for every client | ends it if the browser came from `launch()`; only disconnects if it came from `connect()` | | `browser.disconnect()` | drops this client's connection, browser keeps running | not needed: `close()` on a connected browser disconnects | | `context.close()` | closes this request's pages and storage | the same | A request on a shared Puppeteer session therefore ends with `context.close()` then `browser.disconnect()`. ## Sizing a shared browser How many requests one browser should carry has no fixed answer, because every tab shares that browser's memory. Cloudflare's guidance is to test the workload: - light pages, such as most link-preview targets, can run tens of tabs in one browser; - heavy pages with large JavaScript bundles, media or very large DOMs may manage only a few; - Cloudflare's reuse example caps each browser at a small number of open contexts, asking the browser for its current contexts over CDP (`Target.getBrowserContexts`) before taking on more, and moves on to another session when the cap is reached. A cap like that turns a crash risk into an extra launch, which is the cheaper failure. Watching close reasons in `puppeteer.history()` tells you which way to adjust: many `Chromium crashed` closures mean too many pages per browser, while a steady stream of new launches with idle sessions available means the cap is too low or the reuse loop is not finding them. ## Sessions still end Reuse code must expect a session to vanish between listing and attaching. Sessions close on idle timeout, when Chromium crashes, when the connection drops (for example because the Worker hit its CPU limit), and when Browser Run recycles them for a release. Wrap `connect()` in `try/catch` and fall back to `launch()`.
- Why might a reuse loop that connects to whichever session sessions() lists first still launch too many browsers?Attaching only helps if the attempt succeeds and the session can take more work. A listed session may close before `connect()` completes, and a busy one may already hold as many contexts as its memory allows. Cloudflare's example checks each candidate's open contexts against a cap, tries the other sessions, and launches only when none has room.
- When would you still launch a fresh browser instead of reusing a session?When a job needs process-level isolation rather than a separate context, a different browser configuration, or when a browser has become unstable. For screenshot and PDF work on public pages, a shared session with a context per request is usually enough.
- How long can a reused Browser Run session live?There is no fixed maximum lifetime. A session lives while it receives commands inside its idle window (60 seconds by default, up to 10 minutes with `keep_alive`), and it ends on `browser.close()`, an idle timeout, a Chromium crash, a dropped connection, or when Browser Run recycles it for a release.
A shared browser session is like a hotel kept open between guests: each request checks into its own room (a browser context) with its own key and belongings, and leaves by checking out (disconnect). Only closing the hotel (browser.close() in the Puppeteer fork) turns every other guest out.
- keep_alive sets a hard ten-minute lifetime for the browser
- In the Puppeteer fork, browser.close() on a shared session ends only your connection
- Every tab opened in a session counts as another concurrent browser
- Requests sharing one browser need no separate browser context
- A session returned by sessions() is guaranteed to accept connect()
Assumes Browser Run as of 2026-10-10: since 2026-09-29 one session accepts several concurrent connections (@cloudflare/puppeteer 1.1.0 or @cloudflare/playwright 1.3.0 and later); before that a session took one connection at a time.