Playwright in Production: 10 Best Practices for Reliability and Scale

Ten practices for running Playwright reliably in production — remote browsers, cleanup, timeouts, request blocking, retries, concurrency limits and logging.

Spectrae team · · 10 min read

Getting Playwright to work locally takes an afternoon. Getting it to work in production — reliably, at scale, for weeks without babysitting — is a different problem entirely.

The script that ran perfectly on your laptop will fail in ways you didn't anticipate. Memory leaks accumulate over hours. Timeouts that never triggered locally fire constantly in the cloud. One bad page hangs the whole worker queue. Browsers crash and take your process with them.

These failures aren't Playwright bugs. They're the natural result of moving automation code into a harsher environment without adapting it. Here are the ten practices that separate production-grade Playwright from scripts that work most of the time.


1. Use remote browsers, not local ones

Running Chrome inside your application server is a liability. A single browser instance can use hundreds of megabytes of RAM, and heavy pages push that higher. When the machine runs out of memory, the OOM killer doesn't care which process is your API server.

Remote browsers solve this by moving the browser process out of your application entirely. Your code connects over WebSocket. The browser runs on separate infrastructure. If it crashes or runs out of memory, your application doesn't.

// Don't do this in production
const browser = await chromium.launch({ headless: true });

// Do this instead
const browser = await chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
  headers: { Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}` },
});

Beyond stability, each connection gets a fresh browser, so cookies and state don't leak between jobs. You stop sizing machines for browsers. And you eliminate a whole class of Linux dependency problems — libgbm, libnss, font packages — that plague Dockerized Chromium.


2. Always close browsers, contexts, and pages

Resource leaks are the most common production failure for Playwright workloads. It's easy to open a page, extract data, and move on — forgetting to close the page. Do that a thousand times and the remote browser is sitting on a thousand zombie pages eating memory.

The rule is simple: every open gets a matching close, in a finally block.

async function scrape(browser, url) {
  let context;
  let page;

  try {
    context = await browser.newContext();
    page = await context.newPage();
    await page.goto(url);
    return await page.textContent('.data');
  } finally {
    // These run even if goto() or textContent() throws
    await page?.close().catch(() => {});
    await context?.close().catch(() => {});
  }
}

The .catch(() => {}) on close calls is intentional. If the browser has already disconnected, the close call will throw. You don't want a cleanup error masking the original exception.

Close in order: page first, then context, then browser. Closing the browser first while pages are open can cause the remote server to log errors and potentially not clean up properly.


3. Handle timeouts explicitly — don't rely on defaults

Playwright's default timeout is 30 seconds for most operations. That's 30 seconds your worker is stuck waiting on a page that's never going to load. In a queue-based system, that's 30 seconds of throughput lost per bad URL.

Set explicit timeouts everywhere and make them as tight as real-world data supports.

// Set global defaults in your browser context
const context = await browser.newContext();
context.setDefaultTimeout(15000);     // 15s for all operations
context.setDefaultNavigationTimeout(20000); // 20s for navigations

// Override per-operation where needed
await page.goto(url, {
  waitUntil: 'domcontentloaded',
  timeout: 20000,
});

await page.waitForSelector('.data', { timeout: 10000 });
await page.click('#submit', { timeout: 5000 });

The waitUntil: 'domcontentloaded' option deserves special attention. It fires when HTML is parsed — much faster than 'load' (which waits for all resources) or 'networkidle' (which waits for no network activity for 500ms). For scraping, domcontentloaded is almost always sufficient and can shave several seconds off each request.


4. Use request interception to block unnecessary resources

Every image, font, and stylesheet your browser loads is time and bandwidth you're paying for — and usually don't need. For scraping, you want HTML and JSON. Everything else is overhead.

Request interception lets you abort resource types before they're fetched:

await page.route('**/*', (route) => {
  const blocked = ['image', 'media', 'font', 'stylesheet'];

  if (blocked.includes(route.request().resourceType())) {
    route.abort();
  } else {
    route.continue();
  }
});

Pages with heavy media assets can load noticeably faster with this in place. For a high-volume scraper running thousands of requests per day, the cumulative savings are significant.

One caveat: Playwright disables the HTTP cache while routing is enabled. If you're making repeated requests to the same domain, weigh the cache loss against the asset savings.

You can also use interception to block analytics and tracking scripts — gtm.js, analytics.js, pixel trackers — which reduces noise and speeds up networkidle waits if you're stuck using them.


5. Implement retry logic for transient failures

Some failures aren't bugs. The target server returned a 503. A network packet got dropped. The page loaded but the element wasn't there yet due to a race condition. These things happen.

Retry logic handles them gracefully without treating every failure as fatal.

async function withRetry(fn, retries = 3, delayMs = 1000) {
  let lastError;

  for (let attempt = 1; attempt <= retries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      lastError = err;

      // Don't retry on permanent errors
      if (err.message.includes('net::ERR_NAME_NOT_RESOLVED')) {
        throw err; // DNS failure — no point retrying
      }

      if (attempt < retries) {
        const wait = delayMs * attempt; // linear backoff: 1s, 2s, ...
        console.log(`Attempt ${attempt} failed: ${err.message}. Retrying in ${wait}ms`);
        await new Promise(resolve => setTimeout(resolve, wait));
      }
    }
  }

  throw lastError;
}

// Usage
const data = await withRetry(() => scrapePage(browser, url));

Keep retries low — 2 or 3 is enough for transient failures. More than that and you're masking real problems. Add backoff between attempts to avoid hammering a server that's already struggling.

Don't retry on errors that won't resolve with time: DNS failures, 404s, authentication errors. Check the error message and bail early when it makes sense.


6. Monitor browser memory usage

Browsers leak memory over long sessions. Playwright doesn't expose direct memory metrics, but you can infer health from session duration and track memory from outside the browser.

For long-running processes, the simplest approach is periodic recycling. Two details matter: concurrent callers must share one launch, and an old browser should only close once the jobs still using it have finished.

class BrowserPool {
  constructor(createBrowser, maxUses = 500) {
    this.createBrowser = createBrowser;
    this.maxUses = maxUses; // recycle after this many jobs
    this.current = null;    // { browser: Promise<Browser>, uses, active }
  }

  // Run fn(browser) on a pooled browser, recycling it after maxUses jobs.
  async run(fn) {
    if (!this.current || this.current.uses >= this.maxUses) {
      this.retire(this.current);
      // Store the promise, not the browser, so concurrent callers share one launch.
      this.current = { browser: this.createBrowser(), uses: 0, active: 0, retired: false };
    }
    const slot = this.current;
    slot.uses++;
    slot.active++;
    try {
      return await fn(await slot.browser);
    } finally {
      slot.active--;
      if (slot.retired && slot.active === 0) await this.close(slot);
    }
  }

  retire(slot) {
    if (!slot) return;
    slot.retired = true;
    if (slot.active === 0) void this.close(slot); // otherwise the last job closes it
  }

  async close(slot) {
    const browser = await slot.browser.catch(() => null);
    await browser?.close().catch(() => {});
  }
}

// Usage
const pool = new BrowserPool(() => chromium.launch());
const data = await pool.run((browser) => scrape(browser, url));

With remote browsers, this is less critical — the provider handles memory at the container level. But local browser pools need explicit recycling to stay healthy over hours of operation.


7. Parallelize with limits — avoid OOM

Parallel Playwright sessions are fast. Unbounded parallel sessions are a crash waiting to happen. Each open context and page holds memory on the browser. Stack 50 of them and you'll OOM.

Use a concurrency limiter. The p-limit package is the standard choice:

import pLimit from 'p-limit'; // p-limit is ESM-only in current versions

const limit = pLimit(10); // max 10 concurrent scrapes

async function scrapeAll(browser, urls) {
  const tasks = urls.map(url =>
    limit(() => scrapeUrl(browser, url))
  );

  return Promise.allSettled(tasks);
}

Pick your concurrency ceiling based on what you're running:

Environment Starting point
Local dev (8GB RAM) 5–10
Small cloud VM (2 vCPU, 4GB) 3–5
Remote browser API Your plan's concurrent-session limit

Treat these as starting points and measure. With remote browsers, the ceiling is the provider's concurrent-session limit for your account and the target site's tolerance, not your local memory, so you can't OOM your application server. Set your limiter to match the provider's limit so you don't open connections that will just be rejected.


8. Use wait strategies correctly

The wrong wait strategy is one of the top causes of flaky production scrapers. There are three common approaches and they're not interchangeable.

page.waitForLoadState() waits for a global page lifecycle event. Use it after navigation to confirm the page reached a known state. Playwright's own docs discourage networkidle for this reason — it's slow and unreliable on pages with polling or websocket activity.

page.waitForSelector() waits for a specific element to appear in the DOM. Use it when you need to confirm content has loaded before interacting.

Auto-waiting via locators is the modern Playwright approach. When you use page.locator('.selector').click(), Playwright automatically waits for the element to be visible, stable, and clickable before acting.

// Fragile — assumes the page is ready at an arbitrary moment
await page.waitForTimeout(3000); // never do this

// Better — waits for specific state
await page.waitForLoadState('domcontentloaded');

// Better still — waits for the exact thing you need
await page.waitForSelector('.results-list', { timeout: 10000 });

// Best — auto-waiting built in
const firstResult = page.locator('.results-list .item').first();
await firstResult.click(); // waits automatically

Avoid waitForTimeout entirely in production. It's a fixed sleep that either waits too long (wasting time) or not long enough (causing intermittent failures). Replace every instance of it with a condition-based wait.


9. Log everything with structured logs and session IDs

When something fails at 3am on request number 47,293, you need to know what happened. Unstructured logs — console.log('error') — tell you nothing useful.

Structured logs with session IDs let you trace every step of a failed request.

const crypto = require('crypto');

function createLogger(sessionId) {
  return {
    info: (event, data = {}) => {
      console.log(JSON.stringify({
        level: 'info',
        sessionId,
        event,
        timestamp: new Date().toISOString(),
        ...data,
      }));
    },
    error: (event, err, data = {}) => {
      console.error(JSON.stringify({
        level: 'error',
        sessionId,
        event,
        error: err.message,
        stack: err.stack,
        timestamp: new Date().toISOString(),
        ...data,
      }));
    },
  };
}

async function scrapeWithLogging(browser, url) {
  const sessionId = crypto.randomUUID();
  const log = createLogger(sessionId);

  log.info('scrape.start', { url });

  let context;
  let page;

  try {
    context = await browser.newContext();
    page = await context.newPage();

    await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20000 });
    log.info('scrape.navigated', { url, title: await page.title() });

    const data = await page.textContent('.content');
    log.info('scrape.complete', { url, dataLength: data.length });

    return data;
  } catch (err) {
    log.error('scrape.failed', err, { url });
    throw err;
  } finally {
    await page?.close().catch(() => {});
    await context?.close().catch(() => {});
  }
}

With JSON logs and a session ID, you can grep for a specific session and see the full timeline of what happened. Feed the logs into any observability platform — Datadog, Grafana, CloudWatch — and you have production visibility.


10. Separate browser concerns from application logic

The worst production scraper codebases mix navigation, data extraction, business logic, and error handling in the same function. That function becomes impossible to test, debug, or modify without breaking something.

Separate the concerns into layers:

// Layer 1: Browser management (how to get a browser)
async function getBrowser() {
  return chromium.connect('wss://browser.spectrae.dev/standard/playwright', {
    headers: { Authorization: `Bearer ${process.env.SPECTRAE_API_KEY}` },
  });
}

// Layer 2: Page interaction (how to extract data from a URL)
async function extractProductData(page, url) {
  await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 20000 });

  return {
    title: await page.textContent('h1'),
    price: await page.textContent('.price'),
    inStock: await page.isVisible('.in-stock'),
  };
}

// Layer 3: Session management (how to run a scrape safely)
async function scrapeProduct(browser, url) {
  let context;
  let page;

  try {
    context = await browser.newContext();
    page = await context.newPage();
    return await extractProductData(page, url);
  } finally {
    await page?.close().catch(() => {});
    await context?.close().catch(() => {});
  }
}

// Layer 4: Application logic (what to do with the data)
async function updateProductCatalog(urls) {
  const browser = await getBrowser();

  try {
    const products = await Promise.allSettled(
      urls.map(url => scrapeProduct(browser, url))
    );
    await saveToDatabase(products);
  } finally {
    await browser.close().catch(() => {});
  }
}

Each layer is independently testable. You can mock the browser layer in unit tests. You can swap the data extraction logic without touching session management. Debugging is simpler because failures in each layer are clearly scoped.


How Spectrae handles three of these for you

Practices 1, 6, and part of 7 — remote browsers, memory management, and enforcing a concurrency ceiling — are infrastructure problems that Spectrae handles at the platform level.

You don't provision servers. You don't tune container memory limits. You don't set up a browser pool with recycling logic. You connect over WebSocket, Spectrae starts an isolated Chromium or Camoufox session, and cleans it up when you disconnect.

Pricing is per second: $0.003/min for the standard browser and $0.05/min for the stealth browser. No idle costs and no plan to buy.

The remaining practices — cleanup, timeouts, request interception, retry logic, wait strategies, logging, and clean architecture — are things your code needs to handle. But with the infrastructure layer gone, you can focus on them without managing browsers at the same time.

Get an API key with $1 of free credit, or read the docs.