← Blog

BLOG

Browser Run: What It Means and How to Execute One

A browser run is one execution of a real Chromium session. Learn how runs are created, driven over CDP, isolated, and metered in production.

10 min readRemote Browser
Ivory computer towers connected across terracotta platforms in a quiet desert landscape
The infrastructure behind your browserREMOTE BROWSER / ILLUSTRATION

A browser run is a single execution of a real browser session: Chromium starts, your code or agent drives it through navigation, clicks, and form fills, and then it terminates. The term shows up in two places. In CI and test tooling, a "run" is one pass of a suite. In agent infrastructure, a run is one browser instance bound to one task, with its own lifecycle, state, and cost. This guide covers the second meaning, because that is where most production failures live. If you are wiring an agent to a browser for the first time, start with Remote Browser for AI agents and come back here for the execution model.

The short version: a browser run is a unit of work, not a unit of code. Treat it like a job. Give it an identity, a timeout, a clean or persistent profile, and a way to observe it while it is alive. Everything else follows from those four decisions.

What Counts as a Browser Run

A run begins when a browser process is allocated and a CDP endpoint becomes reachable. It ends when the process is torn down, either because your code closed it or because a timeout or crash reclaimed it. Between those two points, several things are true:

  • The browser has a session ID you can use to reconnect, inspect, or kill it.
  • It has a profile — either ephemeral (wiped on teardown) or persistent (cookies, localStorage, and logins survive across runs).
  • It has a network identity — the egress IP and any proxy settings applied at creation.
  • It consumes wall-clock time, which is what hosted runtimes meter.

That last point matters more than people expect. A run that sits idle waiting on a queue still burns time. A run that retries a flaky step five times burns five times the time. Cost control in browser automation is mostly a scheduling problem, not a compute problem. See pricing for how metering is structured.

Run vs. Session vs. Context

These three words get used interchangeably and shouldn't be.

TermScopeLifetimeTypical owner
Browser runOne task executionMinutes to hoursYour orchestrator
Browser sessionOne browser processSpans one or more runs if reusedThe runtime provider
Browser contextOne isolated cookie/storage jarNested inside a sessionPlaywright or Puppeteer

A single session can host multiple contexts, and a single run usually maps to one context. If you need two agents to work on the same site without sharing cookies, give them separate contexts inside one session — cheaper than two sessions. If you need them to share a login, use one persistent profile and serialize access.

The Anatomy of a Browser Run

Every run has the same five phases. Skipping any of them is where flakiness comes from.

  1. Allocation. The runtime provisions a Chromium process and returns a CDP WebSocket URL. On a hosted runtime this is an API call; locally it is chromium.launch().
  2. Connection. Your client attaches over CDP. Playwright uses connectOverCDP, Puppeteer uses connect({ browserWSEndpoint }), Selenium uses a remote WebDriver URL.
  3. Setup. Navigate to the start URL, set viewport, apply auth state, install any init scripts.
  4. Execution. The agent or script performs its steps. This is where retries, waits, and error handling live.
  5. Teardown. Close the context, close the browser, release the session. Explicit teardown is not optional — orphaned runs are the most common cause of surprise bills.

Phase 1 and 2: Allocation and Connection

The connection step is where most integration bugs appear. The Chrome DevTools Protocol is a WebSocket-based protocol; the endpoint you get back is a ws:// or wss:// URL that speaks it. Playwright's connectOverCDP is the standard way to attach from Node or Python. The Playwright CDP documentation is the authoritative reference for the options, including headers for auth and slowMo for debugging.

Here is a minimal TypeScript run against a hosted Chromium endpoint:

import { chromium, Browser, BrowserContext, Page } from "playwright";

interface RunConfig {
  cdpUrl: string;          // wss://... from the runtime API
  startUrl: string;
  timeoutMs: number;
  persistentProfileId?: string;
}

async function browserRun(cfg: RunConfig): Promise<void> {
  let browser: Browser | undefined;
  let context: BrowserContext | undefined;

  try {
    browser = await chromium.connectOverCDP(cfg.cdpUrl, {
      timeout: 30_000,
    });

    // Reuse the default context if the runtime pre-created one,
    // otherwise create an isolated context for this run.
    context =
      browser.contexts()[0] ??
      (await browser.newContext({
        viewport: { width: 1280, height: 800 },
        locale: "en-US",
      }));

    const page: Page = context.pages()[0] ?? (await context.newPage());
    page.setDefaultTimeout(cfg.timeoutMs);

    await page.goto(cfg.startUrl, { waitUntil: "domcontentloaded" });

    // --- agent or script steps go here ---
    await page.getByRole("button", { name: /sign in/i }).click();
    await page.waitForURL(/dashboard/);

    console.log("run complete:", await page.title());
  } catch (err) {
    console.error("run failed:", err);
    throw err;
  } finally {
    // Close the context you created; leave the browser to the runtime
    // if the runtime owns the session lifecycle.
    await context?.close().catch(() => {});
    await browser?.close().catch(() => {});
  }
}

Two details in that snippet are worth calling out. First, browser.contexts()[0] — hosted runtimes often hand you a browser that already has a default context, and creating a second one wastes memory. Second, the finally block closes the context before the browser. Closing the browser first can leave the context in a half-torn-down state that the runtime reports as an error.

Phase 3: Setup and State

Setup is where you decide whether the run is stateless or stateful.

  • Stateless runs start from a blank profile. Every run re-authenticates. This is correct for scraping, public-page research, and anything where you do not want cross-run contamination.
  • Stateful runs attach to a persistent profile. Logins, cookies, and localStorage carry over. This is correct for dashboards, internal tools, and multi-step workflows that span hours.

The trade-off is real. Persistent profiles are faster to start work in but harder to reason about: a corrupted cookie jar breaks every subsequent run, and two concurrent runs sharing a profile will race on storage. If you need concurrency plus persistence, shard by profile ID — one profile per tenant, per account, or per test user.

Phase 4: Execution and Retries

Retries belong inside the run, not around it. Wrapping the whole run in a retry loop means re-allocating a browser, re-authenticating, and re-navigating every time a single selector misses. That is expensive and slow. Instead, retry at the step level with bounded attempts, and only escalate to a full run retry when the browser itself is unhealthy.

A useful pattern is a three-tier retry policy:

  • Selector retry (3 attempts, 500ms backoff): handles transient DOM timing.
  • Step retry (2 attempts): re-runs a logical action like "submit the form" after a navigation failure.
  • Run retry (1 attempt): only for connection errors, browser crashes, or CDP disconnects.

Log which tier fired. If run retries dominate your metrics, the problem is infrastructure, not selectors.

Phase 5: Teardown

Explicit teardown does three things: releases the session so the runtime can reclaim it, flushes any recordings or logs, and stops the meter. If your code throws before teardown, the runtime's idle timeout is the backstop — but idle timeouts are usually measured in minutes, and those minutes are billable. Wrap every run in try/finally and close what you opened.

Running Browsers at Scale

Once you have more than a handful of runs, three concerns dominate: isolation, observability, and cost.

Isolation

Each run should be isolated at the process level, not just the context level. Context isolation protects cookies; process isolation protects against crashes, memory leaks, and one run's runaway JavaScript starving another. Hosted runtimes handle this for you by giving each session its own Chromium process. If you self-host, run one browser per container and cap memory.

Observability

You cannot debug a run you cannot see. Two things make runs debuggable:

  • A live viewer. Being able to watch the browser in real time turns a 40-minute log-reading session into a 40-second diagnosis. Remote Browser exposes this per session; see remote control browser for how the viewer fits into the control model.
  • Recordings and traces. Playwright traces, HAR files, and console logs should be captured per run and keyed by run ID. When a run fails in production, you want the artifact, not a reproduction attempt.

Cost

Cost is a function of concurrent runs × duration. Two levers:

  1. Shorten runs. Most agent runs spend a large fraction of their time waiting. Parallelize independent steps, cache navigation results, and set aggressive per-step timeouts.
  2. Right-size concurrency. Queue runs instead of launching them all at once. A queue with a concurrency cap is cheaper and more predictable than unbounded fan-out.

Current rates and concurrency limits are on the pricing page; do not hard-code them into your planning.

Local vs. Hosted Browser Runs

The execution model is identical whether Chromium runs on your laptop or on a provider's infrastructure. What changes is who owns the operational surface.

ConcernLocal ChromiumHosted browser run
ProvisioningYou install and patch ChromeRuntime handles it
IsolationShared with your desktopPer-session process
ScalingLimited by your machineBounded by plan concurrency
Network identityYour IPConfigurable proxy settings
DebuggingDevTools on your screenLive viewer + recordings
Cost modelYour time and hardwareMetered per browser-hour
Best forDevelopment, one-off scriptsAgents, CI, production workloads

The honest recommendation: develop locally, run in production on a hosted runtime. Local Chromium is faster to iterate against and gives you full DevTools. Hosted runs give you isolation, reproducibility, and a network identity you control. The migration is mostly a change to the connection step — the rest of your Playwright code is unchanged. The remote browser online guide walks through that switch.

Common Failure Modes

These are the failures that show up repeatedly in production browser runs.

  • Orphaned sessions. The script crashed before teardown. Fix: try/finally, plus a runtime-side idle timeout as a backstop.
  • CDP disconnects mid-run. Usually a network blip or a browser crash. Fix: listen for the disconnected event and fail the run fast rather than letting subsequent calls hang.
  • Selector drift. The site changed. Fix: prefer role- and text-based locators over CSS paths, and assert on page state after each navigation.
  • Profile contention. Two runs sharing a profile. Fix: shard profiles by identity and serialize access with a lock.
  • Silent timeouts. A step waits forever because the default timeout is unset. Fix: set page.setDefaultTimeout() and per-action overrides.
  • Auth expiry mid-run. Long runs outlive session cookies. Fix: detect the login redirect and re-authenticate inside the run rather than failing.

Each of these is cheap to prevent and expensive to debug after the fact. Build the guards into your run wrapper once and reuse it everywhere.

A Production Checklist for Browser Runs

Before you ship a run to production, confirm:

  • [ ] The run has a unique ID that appears in logs, traces, and the runtime's session list.
  • [ ] Connection uses connectOverCDP with an explicit timeout.
  • [ ] The run creates or reuses exactly one context and closes it in finally.
  • [ ] Default timeouts are set at the page level and overridden per step where needed.
  • [ ] Retries are tiered (selector → step → run) and logged by tier.
  • [ ] The profile strategy is explicit: ephemeral or persistent, and sharded if concurrent.
  • [ ] A live viewer or recording is available for post-mortem debugging.
  • [ ] Idle timeout is configured so orphaned runs are reclaimed.
  • [ ] Concurrency is capped and queued, not unbounded.
  • [ ] Cost per run is measured, not estimated.

If you can check all ten, your runs are observable, bounded, and reproducible. That is the whole game.

Where to Go Next

If you are still deciding on a runtime, read remote web browser for the architectural comparison. If you are ready to wire up a run, the documentation covers session creation, CDP endpoints, persistent profiles, and the live viewer. And if you want to understand how runs fit into a larger agent loop — planning, tool calls, verification — start with the Remote Browser for AI agents guide and treat the run as the atomic unit your agent schedules.

A browser run is a small thing: one process, one task, one teardown. But every reliability property you care about — isolation, debuggability, cost predictability — is decided at that boundary. Get the run right and the rest of the system has a solid foundation.