playwright icon indicating copy to clipboard operation
playwright copied to clipboard

[Feature] Exponential backoff on retries

Open 403-html opened this issue 2 years ago • 12 comments

Context:

Currently, Playwright implements a linear retry mechanism for tests, as outlined in its documentation. This approach is invaluable for handling flakiness in tests due to transient issues. However, the existing retry mechanism operates on a linear timeout basis, which can sometimes be inefficient and put unnecessary load on servers, especially in cases of persistent transient issues.

Feature Request:

I propose the implementation of an Exponential Backoff Timeout mechanism for all retries within Playwright (expect/action/global?). Exponential backoff is a standard algorithm that gradually increases the timeout between retries, which can significantly improve the efficiency of handling retry attempts under fluctuating network conditions or server states.

Key Benefits:

  • Reduced Server Load: By spacing out retry attempts more effectively, this approach can help in reducing the load on servers, especially when many tests are running simultaneously and failing due to common transient issues.

  • Improved Test Performance: Exponential backoff can minimize the time wasted in rapid, successive retries, leading to overall faster test completion times in scenarios with intermittent failures.

  • Better Resource Management: This approach can lead to more efficient use of CI/CD pipeline resources, as it avoids rapid, successive retries that may not be necessary if the issue is temporarily persisting.

Example usage

import { defineConfig } from '@playwright/test';

export default defineConfig({
  retries: 2,
  retryStrategy: 'exponentialBackoff',
  exponentialBackoffConfig: {
    initialDelay: 1000, // Initial delay in milliseconds
    growthFactor: 4,    // The factor by which the delay increases after each retry (from example it'd be 1000ms, 2000ms, 4000ms, 8000ms of waiting)
    maxDelay: 30000     // Maximum delay in milliseconds between retries, so even if growth hits it, it'll be maximum used, so tests aren't rolling forever
  }
});

403-html avatar Jan 04 '24 11:01 403-html

Looks similar https://github.com/microsoft/playwright/issues/23354.

mxschmitt avatar Jan 04 '24 18:01 mxschmitt

I mean that's tailing the flaky tests, so adding config when flaky tests should be runned (in his example - at the end of whole run), but here it's more about timing of the retry config, as now we have available only linear retries timeouts.

403-html avatar Jan 04 '24 18:01 403-html

+1

zargham-k avatar Mar 05 '24 16:03 zargham-k

Definitely a supporter of adding this feature!

natesuri-sg avatar Mar 14 '24 15:03 natesuri-sg

+1

darlenew avatar Mar 22 '24 21:03 darlenew

+1

olekach avatar Jun 06 '24 11:06 olekach

+1

artem-zherdiev-ingio avatar Aug 06 '24 13:08 artem-zherdiev-ingio

+1

nils-e avatar Aug 23 '24 05:08 nils-e

I would be happy with just a timeout between retries.

cesarvarela avatar Sep 03 '24 02:09 cesarvarela

I would be happy with just a timeout between retries.

In theory you could use some global (on fixture level) use of testInfo.retry property, to detect and make delay between them. But it's not direct solution. Probably new issue or PR could be a good idea.

403-html avatar Sep 03 '24 03:09 403-html

I would be happy with just a timeout between retries.

In theory you could use some global (on fixture level) use of testInfo.retry property, to detect and make delay between them. But it's not direct solution. Probably new issue or PR could be a good idea.

I ended up doing just that, the only downside is that your test durations will no longer be accurate since the delay is part of the failing test itself.

const ONE_MINUTE = 60_000;
const MAXIMUM_DELAY = 5 * ONE_MINUTE;

const waitMs = (delay: number) => new Promise<void>((resolve) => setTimeout(resolve, delay));

const test = baseTest.extend({});

test.afterEach(async ({}, testInfo) => {
  const testFailedWithRetriesEnabled =
    testInfo.status !== testInfo.expectedStatus && testInfo.project.retries > 0;
  const isLastRetry = testInfo.retry === testInfo.project.retries;

  if (!testFailedWithRetriesEnabled || isLastRetry) {
    return;
  }

  let delay = (testInfo.retry + 1) * ONE_MINUTE;
  if (delay > MAXIMUM_DELAY) {
    delay = MAXIMUM_DELAY;
  }

  testInfo.setTimeout(testInfo.timeout + delay);
  console.info(`Exponential backoff: waiting ${delay}ms before the next test retry`);
  await waitMs(delay);
});

hugo-dlb avatar Dec 02 '24 14:12 hugo-dlb

@hugo-dlb looks good, I'd prefer still native solution

also you can make it a bit shorter

const ONE_MINUTE = 60_000;
const MAXIMUM_DELAY = 5 * ONE_MINUTE;

test.afterEach(async ({page}, testInfo) => {
  if (testInfo.status === testInfo.expectedStatus || testInfo.retry === testInfo.project.retries) {
    return; 
  }

  const delay = Math.min((testInfo.retry + 1) * ONE_MINUTE, MAXIMUM_DELAY);
  testInfo.setTimeout(testInfo.timeout + delay);
  console.info(`Exponential backoff: waiting ${delay}ms before the next test retry`);
  await page.waitForTimeout(delay); // you can use Playwright's built-in wait function (also it'll be logged)
});

403-html avatar Dec 02 '24 15:12 403-html

Workaround: exponential backoff as a Playwright fixture

We ran into the same need — retrying flaky API tests with exponential backoff and a growing timeout per attempt. Here's the pattern we settled on.

How it works

  • backoffOptions — an option fixture (false by default, so zero overhead when unused)
  • _backoff — an auto fixture that reads backoffOptions and applies backoff; no-op when disabled
  • testInfo.setTimeout() is used to grow the timeout per retry (instead of test.setTimeout() in a beforeEach, which requires importing test)
  • Each retry is annotated so it's visible in the HTML report

Note: test.describe.configure({ retries: N }) must still be declared statically alongside test.use({ backoffOptions: {} }) — retries are a collection-time concept and cannot be set from inside a fixture.

backoff.ts

import type { TestInfo } from '@playwright/test'

export interface ExponentialBackoffOptions {
    /** Base delay for retry 1 in ms; doubles each retry. @default 1_000 */
    baseDelayMs?: number
    /** Jitter as a fraction of baseDelay (±). Set 0 to disable. @default 0.25 */
    jitterFactor?: number
    /** Test timeout on attempt 0 (ms). @default 20_000 */
    baseTimeoutMs?: number
    /** Additional ms added to the timeout per retry. @default 10_000 */
    timeoutIncrementMs?: number
}

export async function applyExponentialBackoff(
    options: ExponentialBackoffOptions,
    testInfo: TestInfo,
): Promise<void> {
    const {
        baseDelayMs = 1_000,
        jitterFactor = 0.25,
        baseTimeoutMs = 20_000,
        timeoutIncrementMs = 10_000,
    } = options

    const retryAttempt = testInfo.retry
    const timeout = baseTimeoutMs + retryAttempt * timeoutIncrementMs
    testInfo.setTimeout(timeout)

    if (retryAttempt === 0)
        return

    const base = baseDelayMs * 2 ** (retryAttempt - 1)
    const jitter = base * jitterFactor * (Math.random() * 2 - 1)
    const delay = Math.round(base + jitter)

    testInfo.annotations.push({
        type: 'backoff',
        description: `Retry ${retryAttempt}: waited ${delay}ms before attempt (timeout: ${timeout / 1_000}s)`,
    })

    await new Promise<void>(resolve => setTimeout(resolve, delay))
}

Wiring into the fixture system

import { test as base } from '@playwright/test'
import type { ExponentialBackoffOptions } from './backoff'
import { applyExponentialBackoff } from './backoff'

// option fixture — overridable via test.use()
export interface DefaultOptions {
    backoffOptions: ExponentialBackoffOptions | false
}

// auto fixture — runs for every test, exits immediately when disabled
export interface Fixtures {
    _backoff: void
}

export const test = base.extend<DefaultOptions & Fixtures>({
    backoffOptions: [false, { option: true }],

    _backoff: [async ({ backoffOptions }, use, testInfo) => {
        if (backoffOptions !== false)
            await applyExponentialBackoff(backoffOptions, testInfo)
        await use()
    }, { auto: true }],
})

Usage

test.describe('My flaky API suite', () => {
    test.describe.configure({ retries: 3 })
    test.use({ backoffOptions: { baseTimeoutMs: 60_000, timeoutIncrementMs: 30_000 } })

    test('some test', async ({ request }) => {
        // ...
    })
})

Retry 1 waits ~1 s, retry 2 ~2 s, retry 3 ~4 s (±25 % jitter each). The timeout grows from 60 s → 90 s → 120 s → 150 s across attempts.

flynnhou avatar Mar 24 '26 18:03 flynnhou