[Feature] Exponential backoff on retries
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
}
});
Looks similar https://github.com/microsoft/playwright/issues/23354.
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.
+1
Definitely a supporter of adding this feature!
+1
+1
+1
+1
I would be happy with just a timeout between retries.
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 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 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)
});
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 (falseby default, so zero overhead when unused)_backoff— an auto fixture that readsbackoffOptionsand applies backoff; no-op when disabledtestInfo.setTimeout()is used to grow the timeout per retry (instead oftest.setTimeout()in abeforeEach, which requires importingtest)- Each retry is annotated so it's visible in the HTML report
Note:
test.describe.configure({ retries: N })must still be declared statically alongsidetest.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.