---
title: "Playwright on Kubernetes: Indexed Job Shards and Cost"
description: "Run Playwright on Kubernetes as plain Indexed Job shards started from CI: pods sized from measurement, spot-safe retries, merged blob reports and cost."
canonical: "https://currents.dev/posts/playwright-on-kubernetes-indexed-job-shards-and-cost"
updated: "2026-12-03"
---

# Playwright on Kubernetes: Indexed Job Shards and Cost

Published 2026-12-03 by Walter Galvão.

Canonical URL: https://currents.dev/posts/playwright-on-kubernetes-indexed-job-shards-and-cost

Run Playwright on Kubernetes as plain Indexed Job shards started from CI: pods sized from measurement, spot-safe retries, merged blob reports and cost.

---


> **TL;DR**
>
> This article covers how to run Playwright shards on Kubernetes as plain Indexed Jobs started from your existing CI pipeline, with no Testkube or other orchestrator on top. It explains the test image, how to size pods and workers, Chromium shared memory, a failure policy that tells a lost node apart from a failed test, merging blob reports, and when adding shards or using spot nodes stops paying off.
>
> Build the fan-out yourself from `--shard` and a Kubernetes Job, with no Testkube or other orchestrator on top. Most suites don't need a cluster: if your CI matrix already runs the shards fast enough, stay there.
>
> 1. Pin the official Playwright image to the specific Playwright version your project uses, and tag every image with the commit SHA.
> 2. Add 1 to a zero-based index before passing it to `--shard`, because Playwright's `--shard` option takes the form current/all and is 1-based.
> 3. Set `WORKERS` to the whole CPUs the pod requests, never higher, derive memory from the measured peak, and mount a memory-backed `emptyDir` at `/dev/shm`.
> 4. Leave flaky tests to Playwright's retries: with retries on, a failing test is retried until it passes or reaches the limit.
> 5. Save the test exit code, upload the blob report either way, and merge every blob in CI with `npx playwright merge-reports`.

Your Playwright suite has outgrown the CI runners. Pull requests queue behind each other, and the run that gates every merge now takes longer than the review. Sharding is the usual answer: Playwright splits the suite into shards, and each shard runs independently as a separate job. If your company already runs a Kubernetes cluster with spare nodes, running those shards as pods looks like the obvious move.

Playwright gives you two pieces for it. The [Docker image](https://playwright.dev/docs/docker) carries the browsers and their system dependencies, and `--shard` selects one part of the suite. Everything between those pieces and a green build is yours to work out: how many pods, how many workers in each, how much memory, what happens when a node disappears, and how the results come back together.

Get those wrong and the cluster costs you money and trust. Chromium pods get OOMKilled halfway through a shard. A reclaimed spot node turns into a red build that nobody can reproduce. Shards finish minutes apart, and the build waits on the slowest one.

The fix is one Indexed Job that your existing CI pipeline starts, with pods sized from measurement, a failure policy that retries a lost node but not a failed test, and one merged report.

## When Kubernetes is worth it

Most suites don't need a cluster. If your [CI matrix already runs the shards](/posts/playwright-ci-at-scale-github-gitlab) fast enough, stay there. In GitHub Actions, [`fail-fast` defaults to `true`](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstrategyfail-fast), which cancels all in-progress and queued jobs in the matrix if any job in the matrix fails. Every shard is already its own job, and you have no cluster to operate.

Kubernetes pays off in two situations. In the first, your CI provider's concurrency limit caps how many shards run at once, so extra shards only wait in a queue. In the second, setup on the runners is the bottleneck: each GitHub-hosted runner, except single-CPU runners, is a new VM, and Playwright's CI docs don't recommend caching browser binaries, since restoring the cache takes about as long as downloading them. A prebuilt image on a cluster with spare capacity removes both limits.

Don't wait for a Playwright grid to deploy into the cluster. A user asked for a way to deploy Playwright workers with a load balancer in a Kubernetes cluster ([#26507](https://github.com/microsoft/playwright/issues/26507)). The request was closed as not planned. You build the fan-out yourself from `--shard` and a Kubernetes Job, with no Testkube or other orchestrator on top. You need a cluster, `kubectl` access from CI, a container registry and an object storage bucket for reports.

<AntiPattern title="Tests as a Deployment" id="anti-pattern-tests-as-a-deployment">

A Deployment with three replicas looks like three-way parallelism. Nothing tells a replica which part of the suite belongs to it, so every pod runs the whole suite. A Deployment also exists to keep its pods running: when the test command exits, Kubernetes restarts the container and the finished run starts over.

<AntiPattern.Fix>

Run the suite as a Job, which runs its pods to completion and stops, and give each pod one shard. An Indexed Job does both in one object.

</AntiPattern.Fix>

</AntiPattern>

## Building the test image

Every shard pod pulls the same image, so a version mismatch in the image breaks every shard at once. Start from the official Playwright image. It includes the browsers and their system dependencies but not the Playwright package, so your Dockerfile still runs `npm ci`.

<AntiPattern title="A frozen image tag" id="anti-pattern-a-frozen-image-tag">

The Dockerfile names a tag once, and `@playwright/test` in `package.json` moves on without it. The [Docker docs](https://playwright.dev/docs/docker) spell out the result: when the image's Playwright version doesn't match the project's, Playwright can't locate the browser executables. When the versions differ, Playwright can't locate the browser executables, so no test gets a browser.

```
# Anti-pattern: the tag stays put while package.json upgrades @playwright/test, so the browsers don't match
FROM mcr.microsoft.com/playwright:v1.49.0-noble
WORKDIR /app
COPY . .
RUN npm ci
CMD ["npx", "playwright", "test"]
```

A moving tag only reverses which side drifts.

<AntiPattern.Fix>

Pin the image to the specific Playwright version your project uses, and pass that version in at build time so [a Playwright upgrade](/posts/playwright-update-in-ci-pinning-browsers-and-rollback#matching-the-docker-image-tag) never needs a Dockerfile edit. Install dependencies in an earlier layer than the tests, so Docker doesn't need to rebuild those layers when a project file has changed.

```
ARG PLAYWRIGHT_VERSION
FROM mcr.microsoft.com/playwright:v${PLAYWRIGHT_VERSION}-noble

# tini is installed for the pod's command to wrap as its init process; the AWS CLI uploads blob reports (x86_64 nodes)
RUN apt-get update && apt-get install -y --no-install-recommends tini unzip curl && rm -rf /var/lib/apt/lists/*
RUN curl -sSL https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o /tmp/awscli.zip && unzip -q /tmp/awscli.zip -d /tmp && /tmp/aws/install && rm -rf /tmp/aws /tmp/awscli.zip

# A fixed UID for pods that run as non-root
RUN useradd --uid 10001 --create-home e2e

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN chown e2e:e2e /app

CMD ["npx", "playwright", "test"]
```

Put this in `.dockerignore` to keep local reports and dependencies out of the build context, so a report from someone's laptop never ships in the image:

```plaintext
node_modules
playwright-report
blob-report
test-results
```

Tag every image with the commit SHA, so every shard pod in a run executes the same build. Then run one shard locally before you touch the cluster:

```bash
PW_VERSION=$(node -p "require('./package-lock.json').packages['node_modules/@playwright/test'].version")
IMAGE=registry.example.com/e2e:$(git rev-parse HEAD)
docker build --build-arg PLAYWRIGHT_VERSION="$PW_VERSION" -t "$IMAGE" .
docker run --rm --ipc=host --init "$IMAGE" npx playwright test --shard=1/4
```

Using `--ipc=host` is recommended when using Chromium. Without it, Chromium can run out of memory and crash. A pod has neither, and the shared memory section below covers what replaces them. If shard 1 of 4 passes here and fails in a pod, check the pod spec before the tests.

</AntiPattern.Fix>

</AntiPattern>

## Configuring Playwright for shard pods

Three Playwright defaults work against shard pods, and the config is where you turn them off.

The first is how shards split. Playwright can only shard tests that can run in parallel, so by default it shards whole test files. Turn on `fullyParallel` and sharding gets test-level granularity: each shard tries to balance the number of individual tests it runs, which the [sharding docs](https://playwright.dev/docs/test-sharding) call the preferred mode for even load.

The second is the worker count. `--workers` defaults to 50% of logical CPU cores, and the `workers` option takes a number or a percentage of cores. Pass a number in from the Job instead, so the worker count matches the CPU request in the manifest rather than whatever core count the container detects.

The third is time. Failing tests aren't retried by default, and a run has no upper bound. The CI docs say to always set a global timeout, because a run that gets killed mid-run produces no test report. The CI docs say to keep any job-level timeout comfortably above `globalTimeout`, so that Playwright always stops first.

One more change: use the blob reporter in CI. A blob report holds every test that ran, its result and its attachments such as traces and screenshot diffs, and blob reports can be merged and converted to any other Playwright report later.

```ts
import { defineConfig, devices } from '@playwright/test';

const isCI = !!process.env.CI;

export default defineConfig({
  testDir: './tests',
  // Shard by test, not by file
  fullyParallel: true,
  // The Job passes WORKERS to match the pod's CPU request
  workers: isCI ? Number(process.env.WORKERS ?? 1) : undefined,
  retries: isCI ? 2 : 0,
  reporter: isCI ? 'blob' : 'html',
  // Must end the run before the Job's own deadline does
  globalTimeout: isCI ? 30 * 60 * 1000 : undefined,
  use: {
    trace: 'on-first-retry',
  },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});
```

The config keys off `process.env.CI`. The Job sets `CI` itself, so the CI-only settings apply. The 30-minute timeout and two retries are example values: set the timeout above your slowest shard's normal run.

## The Indexed Job manifest

One Indexed Job replaces a loop that creates a separate Job per shard. `completions` is the shard count, and Kubernetes gives each pod a completion index. `parallelism` caps how many of those pods run at once, so you can set it below `completions` when the cluster can't fit every shard together.

<AntiPattern title="Zero-based shard numbers" id="anti-pattern-zero-based-shard-numbers">

Kubernetes numbers completion indexes from 0. Playwright's `--shard` option takes the form current/all and is 1-based, as in `3/5`. Passing the index straight through looks harmless:

```bash
# Anti-pattern: indexes run 0 to 7, so pod 0 asks for shard 0/8 and no pod asks for 8/8
npx playwright test --shard=$JOB_COMPLETION_INDEX/$SHARD_TOTAL --reporter=blob
```

Playwright rejects a `--shard` value whose current part isn't a positive number, so a shard number of zero stops the run with an error.

<AntiPattern.Fix>

Add 1 to the index. The [CI docs](https://playwright.dev/docs/ci) show the same fix for CircleCI, adding 1 to its zero-based `CIRCLE_NODE_INDEX` before passing it to `--shard`. The manifest reads the index from the pod's `job-completion-index` annotation through a `fieldRef`, and takes the shard total from one variable.

```yaml
# k8s/e2e-job.yaml: CI fills in the ${...} values with envsubst
apiVersion: batch/v1
kind: Job
metadata:
  name: ${JOB_NAME}
  namespace: e2e
spec:
  completionMode: Indexed
  completions: ${SHARD_TOTAL}
  parallelism: ${SHARD_TOTAL}
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: playwright
          image: ${IMAGE}
          env:
            - name: JOB_COMPLETION_INDEX
              valueFrom:
                fieldRef:
                  fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']
            - name: SHARD_TOTAL
              value: "${SHARD_TOTAL}"
            - name: CI
              value: "true"
          command:
            - sh
            - -c
            - npx playwright test --shard=$((JOB_COMPLETION_INDEX + 1))/$SHARD_TOTAL --reporter=blob
```

CI renders this template with `envsubst`, so `SHARD_TOTAL` sets both `completions` and the total in `--shard`, and the two can't disagree. `restartPolicy: Never` leaves a failed pod in place with its logs instead of restarting its container, and `ttlSecondsAfterFinished` deletes the Job and its pods an hour after it finishes.

</AntiPattern.Fix>

</AntiPattern>

## Sizing pods and workers

Every worker is an independent OS process that starts its own browser. Size the pod from what one worker uses, measured on your suite.

### Measure one worker

Run one shard with `WORKERS` set to 1 and sample its working set while it runs. `kubectl top` reports current usage, so poll it and keep the highest value:

```bash
while sleep 5; do kubectl -n e2e top pod -l job-name="$JOB_NAME" --containers --no-headers; done
```

Set the memory request to that peak times the worker count, plus headroom, and the memory limit above the request. With that gap, an OOMKill is rare, and when one happens it points at a real change in the suite instead of a guess.

<AntiPattern title="More workers than CPUs" id="anti-pattern-more-workers-than-cpus">

The pod runs more workers than the CPUs it requests, or leaves the worker count at its default, half of the number of logical CPU cores. The browsers fight for CPU, tests time out, and the pod hits its memory limit. In its CircleCI section, the [CI docs](https://playwright.dev/docs/ci) warn that setting more workers than the detected core count causes unnecessary timeouts and failures.

<AntiPattern.Fix>

Set `WORKERS` to the whole CPUs the pod requests, never higher, and derive memory from the measured peak. It's the same rule that [sizes workers to plain Docker container limits](/posts/run-playwright-tests-in-docker-base-images-and-workers#sizing-workers-to-container-limits), applied to the pod's request. These container fields are example values for two workers; replace the memory with your own measurement:

```yaml
# Added to the playwright container in k8s/e2e-job.yaml (example values for two workers)
env:
  - name: WORKERS
    value: "2"
resources:
  requests:
    cpu: "2"
    memory: 3Gi
  limits:
    cpu: "2"
    memory: 4Gi
```

</AntiPattern.Fix>

</AntiPattern>

### More pods, not bigger pods

The CI docs recommend 1 worker in CI for stability and reproducibility, so each test gets the full system resources. For wider parallelization, the CI docs recommend [sharding tests across multiple CI jobs](/posts/optimizing-test-runtime-playwright-sharding-vs-workers#playwright-sharding-vs-workers). Go bigger only when per-pod startup dominates the run, which the shard-count section below shows how to measure.

A pod is an isolated slice of a node with its own request, unlike a CI runner whose memory every worker shares. Choose `parallelism` from the free CPU and memory your nodes have, so the pods you ask for can all be scheduled.

## Chromium shared memory and sandbox

The local `docker run` used the two flags the Docker guide recommends: `--init` and, with Chromium, `--ipc=host`.

<AntiPattern title="Trusting the Docker flags" id="anti-pattern-trusting-the-docker-flags">

The Docker guide recommends `--ipc=host` with Chromium, because without it Chromium can run out of memory and crash. The smoke test ran with it, so the image looks ready. A pod has no `docker run` command line to put the flag on, and the container keeps its own small `/dev/shm`, so Chromium can run out of memory and crash in the cluster only.

<AntiPattern.Fix>

Mount a memory-backed `emptyDir` at `/dev/shm`, and add its size to the memory limit from the previous section, since its contents live in memory. The pod template below also wraps the command in `tini` and runs as a non-root user:

```yaml
# Pod template fields in k8s/e2e-job.yaml
spec:
  template:
    spec:
      securityContext:
        runAsNonRoot: true
        runAsUser: 10001
      volumes:
        - name: dshm
          emptyDir:
            medium: Memory
            sizeLimit: 1Gi
      containers:
        - name: playwright
          volumeMounts:
            - name: dshm
              mountPath: /dev/shm
          command:
            - /usr/bin/tini
            - "--"
            - sh
            - -c
            - npx playwright test --shard=$((JOB_COMPLETION_INDEX + 1))/$SHARD_TOTAL --reporter=blob
```

</AntiPattern.Fix>

</AntiPattern>

### Init process

The Docker guide also recommends `--init`, so the process with PID 1 gets no special treatment, a common cause of zombie processes. Docker's [`--init` flag](https://docs.docker.com/reference/cli/docker/container/run/#init) runs an init process as PID 1 in the container. Docker's default init process is the `docker-init` binary, which is backed by tini. The pod's command starts with `tini`, the init that backs Docker's default `docker-init`.

### Root and the sandbox

By default the image runs the browsers as root, which disables the Chromium sandbox. For a pod that only runs your own tests against your own app, root is a defensible choice. If your cluster requires non-root, the `securityContext` above runs the container as UID 10001, which the Dockerfile creates as the `e2e` user and gives `/app` to.

Test any custom seccomp profile on a single pod before you roll it out to nodes. One reporter loaded Playwright's own seccomp profile onto Kubernetes nodes, and Chrome stopped starting from v1.39.0 on ([#30738](https://github.com/microsoft/playwright/issues/30738)). The reporter later found that Chromium started working again in Kubernetes once the profile allowed pkey_mprotect, and the issue was closed as completed.

## Retry and failure policy

A shard pod fails for one of two reasons, and they need opposite responses: a test failed, or the node under the pod went away.

Flaky tests belong to Playwright's [retries](https://playwright.dev/docs/test-retries). With retries on, a failing test is retried until it passes or reaches the limit. When a test fails, Playwright discards the whole worker process and its browser and carries on in a new one, all inside the same pod.

<AntiPattern title="BackoffLimit as the retry" id="anti-pattern-backofflimit-as-the-retry">

Setting `backoffLimit` and nothing else makes Kubernetes the retry mechanism, and it retries the whole shard pod. One real failure reruns every passing test in that shard twice and still fails, and a spot reclaim spends the same retry budget as a genuine bug.

```yaml
# Anti-pattern: one real test failure reruns the whole shard twice, and spot reclaims share the same budget
spec:
  backoffLimit: 2
  template:
    spec:
      restartPolicy: Never
```

<AntiPattern.Fix>

Leave test retries to Playwright, and tell Kubernetes which pod failures to retry with a `podFailurePolicy`. The rules below ignore disruptions such as a spot reclaim or a node drain, so Kubernetes replaces the pod without counting it, and fail the shard's index without a rerun when the test command exits non-zero:

```yaml
# Job spec fields in k8s/e2e-job.yaml
spec:
  # Any other pod failure gets one more try
  backoffLimitPerIndex: 1
  activeDeadlineSeconds: 2700
  podFailurePolicy:
    rules:
      # Spot reclaim, node drain or node-pressure eviction: replace the pod, don't count it
      - action: Ignore
        onPodConditions:
          - type: DisruptionTarget
      # Failed tests or an OOMKill: fail this shard's index, no rerun
      - action: FailIndex
        onExitCodes:
          containerName: playwright
          operator: NotIn
          values: [0]
```

`FailIndex` with a per-index limit, in place of the Job-wide `backoffLimit`, fails one shard without stopping the others, so they still finish and upload their reports.

</AntiPattern.Fix>

</AntiPattern>

### OOMKill or eviction

An OOMKilled container exits non-zero, so the policy fails that shard instead of rerunning it: fix the pod's size, not the retry count. Eviction under node pressure marks the pod as disrupted, so it gets a replacement. Set `activeDeadlineSeconds` above Playwright's global timeout, with room for startup and one replacement pod, so Playwright's timeout ends the run first and the shard still has a report to upload.

## Triggering the Job from CI

Keep the existing pipeline as the entry point. On every pull request, it builds and pushes the image, applies the Job under a name built from the [run ID](https://docs.github.com/en/actions/reference/workflows-and-actions/contexts#github-context) and the run attempt, so separate runs and reruns get their own Job, and waits for the result:

```yaml
name: e2e
on: pull_request

jobs:
  e2e:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    env:
      IMAGE: registry.example.com/e2e:${{ github.sha }}
      JOB_NAME: e2e-${{ github.run_id }}-${{ github.run_attempt }}
      RUN_ID: ${{ github.run_id }}-${{ github.run_attempt }}
      SHARD_TOTAL: "8"
      KUBECONFIG: ${{ github.workspace }}/kubeconfig
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - uses: docker/login-action@v3
        with:
          registry: registry.example.com
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
      - name: Build and push the test image
        run: |
          PW_VERSION=$(node -p "require('./package-lock.json').packages['node_modules/@playwright/test'].version")
          docker build --build-arg PLAYWRIGHT_VERSION="$PW_VERSION" -t "$IMAGE" .
          docker push "$IMAGE"
      - uses: azure/setup-kubectl@v4
      - name: Write kubeconfig
        run: |
          echo "${{ secrets.KUBECONFIG_B64 }}" | base64 -d > "$KUBECONFIG"
      - name: Start the shard Job
        run: |
          envsubst '${IMAGE} ${JOB_NAME} ${RUN_ID} ${SHARD_TOTAL}' < k8s/e2e-job.yaml | kubectl apply -f -
      - name: Wait for the Job
        timeout-minutes: 50
        run: |
          while true; do
            if kubectl -n e2e wait --for=condition=complete "job/$JOB_NAME" --timeout=0s >/dev/null 2>&1; then exit 0; fi
            if kubectl -n e2e wait --for=condition=failed "job/$JOB_NAME" --timeout=0s >/dev/null 2>&1; then exit 1; fi
            sleep 15
          done
      - uses: aws-actions/configure-aws-credentials@v4
        if: always()
        with:
          role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
          aws-region: us-east-1
      - name: Merge blob reports
        if: always()
        run: bash scripts/merge-blobs.sh
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: playwright-report
          path: playwright-report/
```

`kubectl wait` with a zero timeout checks a condition once, so the loop polls for both outcomes and fails the step when the Job fails. The pull request status then matches the tests. Watching `kubectl get jobs -w` in a log shows progress, but it never fails the step.

A self-hosted runner inside the cluster is another way to connect CI and Kubernetes. It brings back the per-runner setup you moved to Kubernetes to avoid, so we'd keep the runner hosted and the work in the Job. Nightly full runs can reuse the same Job template from a CronJob, with no CI involved.

## Merging blob reports

Every pod uploads its `blob-report` directory to object storage under a prefix for the run. Object storage spares you a `ReadWriteMany` volume that pods on every node would have to mount, and the bucket outlives the pods that `ttlSecondsAfterFinished` deletes.

<AntiPattern title="Uploading only on success" id="anti-pattern-uploading-only-on-success">

Chaining the upload after the test command with `&&` looks tidy:

```bash
# Anti-pattern: && skips the upload whenever a test fails, so failing shards vanish from the merged report
npx playwright test --shard=$SHARD/$SHARD_TOTAL --reporter=blob && aws s3 cp blob-report/ "s3://e2e-blob-reports/$RUN_ID/shard-$SHARD/" --recursive
```

The shards you most need to see are the ones that never upload.

<AntiPattern.Fix>

Save the test exit code, upload either way, then exit with the saved code. These container fields replace the command in the Job, and CI's `envsubst` fills in `$RUN_ID`:

```yaml
# Fields of the playwright container in k8s/e2e-job.yaml
envFrom:
  - secretRef:
      name: e2e-blob-storage
command:
  - /usr/bin/tini
  - "--"
  - sh
  - -c
  - |
    SHARD=$((JOB_COMPLETION_INDEX + 1))
    npx playwright test --shard=$SHARD/$SHARD_TOTAL --reporter=blob
    status=$?
    aws s3 rm "s3://e2e-blob-reports/$RUN_ID/shard-$SHARD/" --recursive
    aws s3 cp blob-report/ "s3://e2e-blob-reports/$RUN_ID/shard-$SHARD/" --recursive
    exit $status
```

The `e2e-blob-storage` Secret holds the bucket credentials as environment variables, so they never appear on a command line or in the manifest. Clearing the shard's prefix first means a pod that replaces a disrupted one doesn't leave a second blob for the same shard.

On the CI side, put every blob in one directory. Blob report names contain the shard number, so they don't clash:

```bash
#!/usr/bin/env bash
# scripts/merge-blobs.sh: needs RUN_ID and SHARD_TOTAL from the workflow
set -uo pipefail
aws s3 cp "s3://e2e-blob-reports/$RUN_ID/" downloaded/ --recursive
mkdir -p all-blob-reports
find downloaded -name '*.zip' -exec cp -t all-blob-reports/ {} +
npx playwright merge-reports --reporter html ./all-blob-reports
found=$(find all-blob-reports -name '*.zip' | wc -l)
if [ "$found" -ne "$SHARD_TOTAL" ]; then
  echo "Expected $SHARD_TOTAL blob reports, found $found: a shard died without reporting"
  exit 1
fi
```

The script merges first and counts after, so you still get a report for the shards that did finish. `npx playwright merge-reports` reads all blob reports from the passed directory and merges them into a single report, and the count check after it exits non-zero when a blob is missing.

</AntiPattern.Fix>

</AntiPattern>

## Where more shards stop helping

Sharding splits your tests into smaller parts called shards, to speed up test runtime. Startup doesn't. Every pod pays in full for pulling the browser image and, when no node has room, for waiting on the autoscaler, however small its share of the suite. Baking `npm ci` into the image keeps dependency install out of that bill.

Measure the two parts from pod timestamps. The gap between a pod's creation and its container start is overhead, and the gap from start to finish is test time:

```bash
kubectl -n e2e get pods -l job-name="$JOB_NAME" -o jsonpath='{range .items[*]}{.metadata.name}{" created="}{.metadata.creationTimestamp}{" started="}{.status.containerStatuses[0].state.terminated.startedAt}{" finished="}{.status.containerStatuses[0].state.terminated.finishedAt}{"\n"}{end}'
```

<AntiPattern title="A shard for every slow build" id="anti-pattern-a-shard-for-every-slow-build">

When the build feels slow, `completions` goes up. Past the point where startup dominates, each extra shard adds pod-minutes and its own startup without making the build faster.

<AntiPattern.Fix>

Stop adding shards when the overhead approaches the per-shard test time. Use that measurement in place of a fixed files-per-shard rule of thumb. To cut the overhead itself, keep the image warm on nodes or keep capacity provisioned ahead of the run.

</AntiPattern.Fix>

</AntiPattern>

### Uneven files

Without `fullyParallel`, the number of tests per file can greatly influence [shard distribution](https://playwright.dev/docs/test-sharding). When test files are not evenly sized, some shards may run significantly more tests, while others may run fewer or even none. Test-level granularity from `fullyParallel` evens out the test counts.

## Spot nodes versus runner minutes

Cluster time isn't free just because the cluster already exists. Compare like with like: a shard's pod-minutes are its startup plus test time, weighted by the CPU and memory it requests and priced at your node rate. Put that next to the CI runner minutes the same shards would bill.

Then add the costs a per-pod figure leaves out: nodes the autoscaler keeps idle, the time pods wait for scale-up, and your share of the cluster's fixed cost. A cluster that exists only for this suite carries all of that fixed cost itself.

Spot instances can cost up to 90% less than traditionally allocated resources. However, spot instances can be terminated at any time, which can cause the loss of the test results. Run shards on spot only once disruptions are ignored rather than counted as failures, or every reclaim becomes a red build. [Currents Orchestration](https://docs.currents.dev/guides/ci-optimization/ci-tests-on-spot-instances) can reassign the tests of an instance about to be terminated to another machine. With the `--pwc-reset-signal` flag set, `pwc-p run` listens for `SIGUSR1` or `SIGUSR2`, and it is your responsibility to capture the eviction notice and send the signal to the `pwc-p run` process before the eviction.

## Balancing the slowest test files

With `fullyParallel: true`, each shard attempts to balance the number of individual tests it runs. A shard that draws a run of slow end-to-end flows still finishes last, and the build waits for it.

Without `fullyParallel`, Playwright splits tests at the file level, so to balance the shards, keep your test files small and evenly sized. Tests skipped statically, with `test.skip()` or `test.fixme()`, aren't counted when balancing shards, because they don't run.

[Currents Balanced Sharding](https://docs.currents.dev/guides/ci-optimization/balanced-sharding) keeps the same `--shard=i/N` pods and Job manifest: each shard fetches recent spec-file durations, every shard gets the same durations so they agree on a split without talking to each other, and every shard needs the same CI Build ID, which you set once in the pipeline and pass to each pod through the Job's `env` (without one, each pod becomes a separate run).

Once the shards end together, the startup measurement from earlier gives you a shard count you can defend. Keep adding pods while one more pod saves more test time than it costs in startup. When it stops doing that, you have your number, and every pod past it only adds pod-minutes.

## Frequently asked questions


### How do I run Playwright tests on Kubernetes?

Split the suite with `--shard`, and run each shard as a separate job. Playwright's `--shard` option takes the form current/all and is 1-based, as in `3/5`. The CI docs therefore add 1 to CircleCI's zero-based `CIRCLE_NODE_INDEX` before passing it to `--shard`, as [Zero-based shard numbers](#anti-pattern-zero-based-shard-numbers) shows.


### Is Kubernetes worth it for Playwright tests?

Most suites don't need a cluster: if your CI matrix already runs the shards fast enough, stay there.


### Is there a Playwright grid for Kubernetes?

Not as a planned feature: a user asked for a way to deploy Playwright workers with a load balancer in a Kubernetes cluster, and the request was closed as not planned.


### How many Playwright workers should each Kubernetes pod run?

Set `WORKERS` to the whole CPUs the pod requests, never higher, and derive memory from the measured peak. The CI docs warn that setting more workers than the detected core count causes unnecessary timeouts and failures, as [the more workers than CPUs anti-pattern](#anti-pattern-more-workers-than-cpus) shows.


### Why does Chromium crash in a Kubernetes pod but not in Docker?

Using `--ipc=host` is recommended when using Chromium. Without it, Chromium can run out of memory and crash.


### Should Kubernetes retry failed Playwright shards?

Leave test retries to Playwright. With retries on, a failing test is retried until it passes or reaches the limit. When a test fails, Playwright discards the whole worker process and its browser and carries on in a new one, as [Retry and failure policy](#retry-and-failure-policy) explains.


### How do I merge Playwright reports from Kubernetes pods?

Every pod uploads its `blob-report` directory to object storage under a prefix for the run, and CI puts every blob in one directory. `npx playwright merge-reports` reads all blob reports from the passed directory and merges them into a single report, as [Merging blob reports](#merging-blob-reports) shows.


### How many shards should I use for Playwright on Kubernetes?

Stop adding shards when the overhead approaches the per-shard test time.




---

## About the author

**Walter Galvão**, Software Engineer. Walter Galvão is a software engineer at Currents. He writes about Playwright in practice: debugging flaky tests, structuring suites for CI, and the engineering workflows that keep large test suites reliable.

LinkedIn: https://www.linkedin.com/in/waltergalvao/
