Skip to content
Myr

Add `retryOnTimeout` and `shouldRetry` options (#767)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by GitHub · parent 081c924 · Browse files · 9 files+779 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+779 added−37 removed

  • tests:+537 added−10 removed
  • other:+242 added−27 removed

9 files+779 added−37 removed

modified:source/core/Ky.ts+62 added-21 removed
1import {HTTPError} from '../errors/HTTPError.js';2import {NonError} from '../errors/NonError.js';3import type {4 Input,5 InternalOptions,6 NormalizedOptions,
147 unmodified lines
154 return searchParams;155 }156157 public request: Request;157 readonly #abortController?: AbortController;158 #abortController?: AbortController;159 #retryCount = 0;160 // eslint-disable-next-line @typescript-eslint/prefer-readonly -- False positive: #input is reassigned on line 202161 #input: Input;162 readonly #options: InternalOptions;163 #originalRequest?: Request;164 readonly #userProvidedAbortSignal?: AbortSignal;165 #cachedNormalizedOptions?: NormalizedOptions;166167 // eslint-disable-next-line complexity168 constructor(input: Input, options: Options = {}) {
36 unmodified lines
205 this.#input = this.#options.prefixUrl + this.#input;206 }207208 if (supportsAbortController && supportsAbortSignal) {207 const originalSignal = this.#options.signal ?? (this.#input as Request).signal;209 this.#userProvidedAbortSignal = this.#options.signal ?? (this.#input as Request).signal;210 this.#abortController = new globalThis.AbortController();209 this.#options.signal = originalSignal ? AbortSignal.any([originalSignal, this.#abortController.signal]) : this.#abortController.signal;211 this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal;212 }213214 if (supportsRequestStreams) {215 // @ts-expect-error - Types are outdated.
48 unmodified lines
264 }265 }266 }267268 #calculateDelay(): number {269 const retryDelay = this.#options.retry.delay(this.#retryCount);270271 let jitteredDelay = retryDelay;272 if (this.#options.retry.jitter === true) {273 jitteredDelay = Math.random() * retryDelay;274 } else if (typeof this.#options.retry.jitter === 'function') {275 jitteredDelay = this.#options.retry.jitter(retryDelay);276277 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {278 jitteredDelay = retryDelay;279 }280 }281282 return Math.min(this.#options.retry.backoffLimit, jitteredDelay);283 }284266 #calculateRetryDelay(error: unknown) {285 async #calculateRetryDelay(error: unknown) {286 this.#retryCount++;287269 if (this.#retryCount > this.#options.retry.limit || isTimeoutError(error)) {288 if (this.#retryCount > this.#options.retry.limit) {289 throw error;290 }291292 // Wrap non-Error throws to ensure consistent error handling293 const errorObject = error instanceof Error ? error : new NonError(error);294295 // User-provided shouldRetry function takes precedence over all other checks296 if (this.#options.retry.shouldRetry !== undefined) {297 const result = await this.#options.retry.shouldRetry({error: errorObject, retryCount: this.#retryCount});298299 // Strict boolean checking - only exact true/false are handled specially300 if (result === false) {301 throw error;302 }303304 if (result === true) {305 // Force retry - skip all other validation and return delay306 return this.#calculateDelay();307 }308309 // If undefined or any other value, fall through to default behavior310 }311312 // Default timeout behavior313 if (isTimeoutError(error) && !this.#options.retry.retryOnTimeout) {314 throw error;315 }316317 if (isHTTPError(error)) {318 if (!this.#options.retry.statusCodes.includes(error.response.status)) {319 throw error;320 }
11 unmodified lines
332 after -= Date.now();333 }334335 const max = this.#options.retry.maxRetryAfter ?? after;336 // Don't apply jitter when server provides explicit retry timing337 return after < max ? after : max;338 }339340 if (error.response.status === 413) {341 throw error;342 }343 }344300 const retryDelay = this.#options.retry.delay(this.#retryCount);301302 let jitteredDelay = retryDelay;303 if (this.#options.retry.jitter === true) {304 jitteredDelay = Math.random() * retryDelay;305 } else if (typeof this.#options.retry.jitter === 'function') {306 jitteredDelay = this.#options.retry.jitter(retryDelay);307308 if (!Number.isFinite(jitteredDelay) || jitteredDelay < 0) {309 jitteredDelay = retryDelay;310 }311 }312313 return Math.min(this.#options.retry.backoffLimit, jitteredDelay);345 return this.#calculateDelay();346 }347348 #decorateResponse(response: Response): Response {349 if (this.#options.parseJson) {
6 unmodified lines
356 async #retry<T extends (...arguments_: any) => Promise<any>>(function_: T): Promise<ReturnType<T> | void> {357 try {358 return await function_();359 } catch (error) {328 const ms = Math.min(this.#calculateRetryDelay(error), maxSafeTimeout);360 const ms = Math.min(await this.#calculateRetryDelay(error), maxSafeTimeout);361 if (this.#retryCount < 1) {362 throw error;363 }364333 await delay(ms, {signal: this.#options.signal});365 // Only use user-provided signal for delay, not our internal abortController366 await delay(ms, this.#userProvidedAbortSignal ? {signal: this.#userProvidedAbortSignal} : {});367368 for (const hook of this.#options.hooks.beforeRetry) {369 // eslint-disable-next-line no-await-in-loop370 const hookResult = await hook({
13 unmodified lines
384 }385 }386387 async #fetch(): Promise<Response> {388 // Reset abortController if it was aborted (happens on timeout retry)389 if (this.#abortController?.signal.aborted) {390 this.#abortController = new globalThis.AbortController();391 this.#options.signal = this.#userProvidedAbortSignal ? AbortSignal.any([this.#userProvidedAbortSignal, this.#abortController.signal]) : this.#abortController.signal;392 // Recreate request with new signal393 this.request = new globalThis.Request(this.request, {signal: this.#options.signal});394 }395396 for (const hook of this.#options.hooks.beforeRequest) {397 // eslint-disable-next-line no-await-in-loop398 const result = await hook(399 this.request,
36 unmodified lines
added:source/errors/NonError.ts+28 added
modified:source/types/options.ts+2 added-2 removed
295 unmodified lines
296'fetch' | 'prefixUrl' | 'timeout'297> & {298 headers: Required<Headers>;299 hooks: Required<Hooks>;300 retry: Required<RetryOptions>;300 retry: Required<Omit<RetryOptions, 'shouldRetry'>> & Pick<RetryOptions, 'shouldRetry'>;301 prefixUrl: string;302};303304/**
10 unmodified lines
315 onDownloadProgress: Options['onDownloadProgress'];316 onUploadProgress: Options['onUploadProgress'];317}318319export type {RetryOptions} from './retry.js';319export type {RetryOptions, ShouldRetryState} from './retry.js';
modified:source/types/retry.ts+77 added
modified:source/utils/normalize.ts+5 added-2 removed
modified:source/index.ts+4 added
39 unmodified lines
40 Input,41 Options,42 NormalizedOptions,43 RetryOptions,44 ShouldRetryState,45 SearchParamsOption,46 Progress,47} from './types/options.js';48
14 unmodified lines
63export type {KyResponse} from './types/response.js';64export {HTTPError} from './errors/HTTPError.js';65export {TimeoutError} from './errors/TimeoutError.js';66export {isKyError, isHTTPError, isTimeoutError} from './utils/type-guards.js';6768// Intentionally not exporting this for now as it's just an implementation detail and we don't want to commit to a certain API yet at least.69// export {NonError} from './errors/NonError.js';
modified:test/helpers/with-performance.ts+2 added-2 removed
7 unmodified lines
8 test: () => Promise<void>;9};1011// We allow the tests to take more time on CI than locally, to reduce flakiness12// Node.js 24 has higher overhead on CI (~400-450ms), so we increase the tolerance12// Node.js 22+ has higher overhead on CI (~400-650ms), so we increase the tolerance13const nodeVersion = Number(process.versions.node.split('.')[0]);14const allowedOffset = process.env.CI ? (nodeVersion >= 24 ? 500 : 300) : 200;14const allowedOffset = process.env.CI ? (nodeVersion >= 22 ? 700 : 300) : 200;1516export async function withPerformance({17 expectedDuration,18 t,
12 unmodified lines
modified:test/retry.ts+535 added-8 removed
1import {setTimeout as delay} from 'node:timers/promises';2import test from 'ava';3import ky from '../source/index.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';5import {withPerformance} from './helpers/with-performance.js';
690 unmodified lines
696697 t.is(requestCount, 4);698699 // Full jitter should produce delays between 0 and the computed delay699 // Add 20% tolerance for system overhead700 t.true(delays[0] >= 0 && delays[0] <= 360);701 t.true(delays[1] >= 0 && delays[1] <= 720);702 t.true(delays[2] >= 0 && delays[2] <= 1440);700 // Add 50% tolerance for system overhead and CI variability701 t.true(delays[0] >= 0 && delays[0] <= 450);702 t.true(delays[1] >= 0 && delays[1] <= 900);703 t.true(delays[2] >= 0 && delays[2] <= 1800);704705 await server.close();706});707
71 unmodified lines
779780 // With backoffLimit of 500, all delays should be <= 500ms781 // Even though the computed delays would be 300, 600, 1200782 // After jitter and backoffLimit, they should all be <= 500782 // Add 20% tolerance for system overhead783 t.true(delays[0] >= 0 && delays[0] <= 600);784 t.true(delays[1] >= 0 && delays[1] <= 600);785 t.true(delays[2] >= 0 && delays[2] <= 600);783 // Add 50% tolerance for system overhead and CI variability784 t.true(delays[0] >= 0 && delays[0] <= 750);785 t.true(delays[1] >= 0 && delays[1] <= 750);786 t.true(delays[2] >= 0 && delays[2] <= 750);787788 await server.close();789});790
72 unmodified lines
863 t.true(timeElapsedInMs >= 2000);864865 await server.close();866});867868test('retryOnTimeout: false (default) - does not retry on timeout', async t => {869 let requestCount = 0;870871 const server = await createHttpTestServer();872 server.get('/', async (_request, response) => {873 requestCount++;874 // Delay longer than timeout to trigger timeout875 await delay(1000);876 response.end(fixture);877 });878879 await t.throwsAsync(880 ky(server.url, {881 timeout: 500,882 retry: {883 limit: 3,884 },885 }).text(),886 {887 name: 'TimeoutError',888 },889 );890891 t.is(requestCount, 1); // Should not retry892893 await server.close();894});895896test('retryOnTimeout: true - retries on timeout', async t => {897 let requestCount = 0;898899 const server = await createHttpTestServer();900 server.get('/', async (_request, response) => {901 requestCount++;902 if (requestCount <= 2) {903 // Delay longer than timeout to trigger timeout904 await delay(1000);905 response.end(fixture);906 } else {907 response.end(fixture);908 }909 });910911 const result = await ky(server.url, {912 timeout: 500,913 retry: {914 limit: 3,915 retryOnTimeout: true,916 },917 }).text();918919 t.is(result, fixture);920 t.is(requestCount, 3); // Initial + 2 retries921922 await server.close();923});924925test('retryOnTimeout: true - respects retry limit on timeout', async t => {926 let requestCount = 0;927928 const server = await createHttpTestServer();929 server.get('/', async (_request, response) => {930 requestCount++;931 // Always timeout932 await delay(2000);933 });934935 await t.throwsAsync(936 ky(server.url, {937 timeout: 500,938 retry: {939 limit: 2,940 retryOnTimeout: true,941 },942 }).text(),943 {944 name: 'TimeoutError',945 },946 );947948 t.is(requestCount, 3); // Initial + 2 retries949950 await server.close();951});952953test('shouldRetry: returns true - forces retry bypassing all checks', async t => {954 let requestCount = 0;955956 const server = await createHttpTestServer();957 server.get('/', async (_request, response) => {958 requestCount++;959 if (requestCount <= 2) {960 // Delay longer than timeout to trigger timeout961 await delay(1000);962 response.end(fixture);963 } else {964 response.end(fixture);965 }966 });967968 const result = await ky(server.url, {969 timeout: 500,970 retry: {971 limit: 3,972 retryOnTimeout: false, // Disabled973 shouldRetry: () => true, // But shouldRetry forces retry974 },975 }).text();976977 t.is(result, fixture);978 t.is(requestCount, 3);979980 await server.close();981});982983test('shouldRetry: returns false - prevents retry', async t => {984 let requestCount = 0;985986 const server = await createHttpTestServer();987 server.get('/', (_request, response) => {988 requestCount++;989 response.sendStatus(500); // Normally retriable990 });991992 await t.throwsAsync(993 ky(server.url, {994 retry: {995 limit: 3,996 shouldRetry: () => false, // Prevent all retries997 },998 }).text(),999 {1000 message: /Internal Server Error/,1001 },1002 );10031004 t.is(requestCount, 1); // No retries10051006 await server.close();1007});10081009test('shouldRetry: returns undefined - uses default retry logic', async t => {1010 let requestCount = 0;10111012 const server = await createHttpTestServer();1013 server.get('/', (_request, response) => {1014 requestCount++;1015 if (requestCount <= 2) {1016 response.sendStatus(500); // Retriable1017 } else {1018 response.end(fixture);1019 }1020 });10211022 const result = await ky(server.url, {1023 retry: {1024 limit: 3,1025 shouldRetry: () => undefined, // Fall through to default1026 },1027 }).text();10281029 t.is(result, fixture);1030 t.is(requestCount, 3); // Default retry behavior10311032 await server.close();1033});10341035test('shouldRetry: receives correct state object', async t => {1036 let requestCount = 0;1037 const states: Array<{errorName: string; retryCount: number}> = [];10381039 const server = await createHttpTestServer();1040 server.get('/', (_request, response) => {1041 requestCount++;1042 if (requestCount <= 2) {1043 response.sendStatus(500);1044 } else {1045 response.end(fixture);1046 }1047 });10481049 await ky(server.url, {1050 retry: {1051 limit: 3,1052 shouldRetry({error, retryCount}) {1053 states.push({errorName: error.name, retryCount});1054 return undefined; // Use default logic1055 },1056 },1057 }).text();10581059 t.is(states.length, 2);1060 t.is(states[0].errorName, 'HTTPError');1061 t.is(states[0].retryCount, 1); // First retry1062 t.is(states[1].errorName, 'HTTPError');1063 t.is(states[1].retryCount, 2); // Second retry10641065 await server.close();1066});10671068test('shouldRetry: custom business logic with HTTPError', async t => {1069 let requestCount = 0;10701071 const server = await createHttpTestServer();1072 server.get('/', (_request, response) => {1073 requestCount++;1074 if (requestCount === 1) {1075 response.sendStatus(429); // Rate limit1076 } else if (requestCount === 2) {1077 response.sendStatus(500); // Server error1078 } else {1079 response.end(fixture);1080 }1081 });10821083 const result = await ky(server.url, {1084 retry: {1085 limit: 3,1086 async shouldRetry({error, retryCount}) {1087 const {HTTPError} = await import('../source/index.js');1088 if (error instanceof HTTPError) {1089 const {status} = error.response;1090 // Retry on 429 but only first attempt1091 if (status === 429 && retryCount <= 1) {1092 return true;1093 }10941095 // Don't retry on 4xx1096 if (status >= 400 && status < 500) {1097 return false;1098 }1099 }11001101 return undefined;1102 },1103 },1104 }).text();11051106 t.is(result, fixture);1107 t.is(requestCount, 3);11081109 await server.close();1110});11111112test('shouldRetry: error propagates if shouldRetry throws', async t => {1113 const server = await createHttpTestServer();1114 server.get('/', (_request, response) => {1115 response.sendStatus(500);1116 });11171118 await t.throwsAsync(1119 ky(server.url, {1120 retry: {1121 limit: 3,1122 shouldRetry() {1123 throw new Error('shouldRetry failed');1124 },1125 },1126 }).text(),1127 {1128 message: 'shouldRetry failed',1129 },1130 );11311132 await server.close();1133});11341135test('shouldRetry: works with TimeoutError', async t => {1136 let requestCount = 0;11371138 const server = await createHttpTestServer();1139 server.get('/', async (_request, response) => {1140 requestCount++;1141 if (requestCount <= 2) {1142 // Delay longer than timeout to trigger timeout1143 await delay(1000);1144 response.end(fixture);1145 } else {1146 response.end(fixture);1147 }1148 });11491150 const result = await ky(server.url, {1151 timeout: 500,1152 retry: {1153 limit: 3,1154 async shouldRetry({error}) {1155 const {TimeoutError} = await import('../source/index.js');1156 return error instanceof TimeoutError;1157 },1158 },1159 }).text();11601161 t.is(result, fixture);1162 t.is(requestCount, 3);11631164 await server.close();1165});11661167test('shouldRetry: precedence over retryOnTimeout', async t => {1168 let requestCount = 0;11691170 const server = await createHttpTestServer();1171 server.get('/', async (_request, response) => {1172 requestCount++;1173 // Delay longer than timeout to trigger timeout1174 await delay(1000);1175 response.end(fixture);1176 });11771178 await t.throwsAsync(1179 ky(server.url, {1180 timeout: 500,1181 retry: {1182 limit: 3,1183 retryOnTimeout: true, // Would retry1184 shouldRetry: () => false, // But shouldRetry prevents it1185 },1186 }).text(),1187 {1188 name: 'TimeoutError',1189 },1190 );11911192 t.is(requestCount, 1); // No retries11931194 await server.close();1195});11961197test('shouldRetry: works with synchronous function', async t => {1198 let requestCount = 0;11991200 const server = await createHttpTestServer();1201 server.get('/', (_request, response) => {1202 requestCount++;1203 if (requestCount <= 2) {1204 response.sendStatus(500);1205 } else {1206 response.end(fixture);1207 }1208 });12091210 const result = await ky(server.url, {1211 retry: {1212 limit: 3,1213 shouldRetry: () => true, // Sync function returning true1214 },1215 }).text();12161217 t.is(result, fixture);1218 t.is(requestCount, 3);12191220 await server.close();1221});12221223test('shouldRetry: non-boolean return values fall through to default logic', async t => {1224 let requestCount = 0;12251226 const server = await createHttpTestServer();1227 server.get('/', (_request, response) => {1228 requestCount++;1229 if (requestCount <= 2) {1230 response.sendStatus(500); // Retriable by default1231 } else {1232 response.end(fixture);1233 }1234 });12351236 // Test with various non-boolean return values - all should fall through1237 const result = await ky(server.url, {1238 retry: {1239 limit: 3,1240 shouldRetry: () => 42 as any, // Non-boolean (number) falls through1241 },1242 }).text();12431244 t.is(result, fixture);1245 t.is(requestCount, 3); // Should retry using default logic12461247 await server.close();1248});12491250test('shouldRetry: receives proper Error instance even for HTTPError', async t => {1251 const server = await createHttpTestServer();1252 server.get('/', (_request, response) => {1253 response.sendStatus(404);1254 });12551256 let receivedError: Error | undefined;12571258 await t.throwsAsync(1259 ky(server.url, {1260 retry: {1261 limit: 1,1262 shouldRetry({error}) {1263 receivedError = error;1264 // Verify it's a proper Error instance1265 t.true(error instanceof Error);1266 t.is(error.name, 'HTTPError');1267 return false;1268 },1269 },1270 }).text(),1271 );12721273 // Ensure shouldRetry was called1274 t.truthy(receivedError);12751276 await server.close();1277});12781279test('shouldRetry: combines with default status code logic when returning undefined', async t => {1280 let requestCount = 0;1281 const capturedStatuses: number[] = [];12821283 const server = await createHttpTestServer();1284 server.get('/', (_request, response) => {1285 requestCount++;1286 if (requestCount === 1) {1287 response.sendStatus(500); // Retriable1288 } else if (requestCount === 2) {1289 response.sendStatus(404); // Not retriable1290 } else {1291 response.end(fixture);1292 }1293 });12941295 await t.throwsAsync(1296 ky(server.url, {1297 retry: {1298 limit: 3,1299 async shouldRetry({error}) {1300 const {HTTPError} = await import('../source/index.js');1301 if (error instanceof HTTPError) {1302 capturedStatuses.push(error.response.status);1303 }13041305 return undefined; // Fall through to default logic1306 },1307 },1308 }).text(),1309 {1310 message: /Not Found/,1311 },1312 );13131314 // Should retry on 500, then fail on 4041315 t.is(requestCount, 2);1316 t.deepEqual(capturedStatuses, [500, 404]);13171318 await server.close();1319});13201321test('shouldRetry: retryCount starts at 1 for first retry', async t => {1322 const retryCounts: number[] = [];13231324 const server = await createHttpTestServer();1325 server.get('/', (_request, response) => {1326 response.sendStatus(500);1327 });13281329 await t.throwsAsync(1330 ky(server.url, {1331 retry: {1332 limit: 3,1333 shouldRetry({retryCount}) {1334 retryCounts.push(retryCount);1335 return retryCount < 3; // Stop at 3rd retry1336 },1337 },1338 }).text(),1339 );13401341 t.deepEqual(retryCounts, [1, 2, 3]);13421343 await server.close();1344});13451346test('shouldRetry: handles Promise return value correctly', async t => {1347 let requestCount = 0;13481349 const server = await createHttpTestServer();1350 server.get('/', (_request, response) => {1351 requestCount++;1352 if (requestCount <= 2) {1353 response.sendStatus(500);1354 } else {1355 response.end(fixture);1356 }1357 });13581359 const result = await ky(server.url, {1360 retry: {1361 limit: 3,1362 shouldRetry: async () => true,1363 },1364 }).text();13651366 t.is(result, fixture);1367 t.is(requestCount, 3);13681369 await server.close();1370});13711372test('shouldRetry: error propagates if shouldRetry returns rejected Promise', async t => {1373 const server = await createHttpTestServer();1374 server.get('/', (_request, response) => {1375 response.sendStatus(500);1376 });13771378 await t.throwsAsync(1379 ky(server.url, {1380 retry: {1381 limit: 3,1382 // eslint-disable-next-line @typescript-eslint/promise-function-async1383 shouldRetry: () => Promise.reject(new Error('shouldRetry Promise rejected')),1384 },1385 }).text(),1386 {1387 message: 'shouldRetry Promise rejected',1388 },1389 );13901391 await server.close();1392});
modified:readme.md+64 added-2 removed
204 unmodified lines
205- `maxRetryAfter`: `undefined`206- `backoffLimit`: `undefined`207- `delay`: `attemptCount => 0.3 * (2 ** (attemptCount - 1)) * 1000`208- `jitter`: `undefined`209- `retryOnTimeout`: `false`210- `shouldRetry`: `undefined`211210An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, and `maxRetryAfter` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.212An object representing `limit`, `methods`, `statusCodes`, `afterStatusCodes`, `maxRetryAfter`, `backoffLimit`, `delay`, `jitter`, `retryOnTimeout`, and `shouldRetry` fields for maximum retry count, allowed methods, allowed status codes, status codes allowed to use the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time, backoff limit, delay calculation function, retry jitter, timeout retry behavior, and custom retry logic.213214If `retry` is a number, it will be used as `limit` and other defaults will remain in place.215216If the response provides an HTTP status contained in `afterStatusCodes`, Ky will wait until the date, timeout, or timestamp given in the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header has passed to retry the request. If `Retry-After` is missing, the non-standard [`RateLimit-Reset`](https://www.ietf.org/archive/id/draft-polli-ratelimit-headers-05.html#section-3.3) header is used in its place as a fallback. If the provided status code is not in the list, the [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header will be ignored.
9 unmodified lines
226The `jitter` option adds random jitter to retry delays to prevent thundering herd problems. When many clients retry simultaneously (e.g., after hitting a rate limit), they can overwhelm the server again. Jitter adds randomness to break this synchronization. Set to `true` to use full jitter, which randomizes the delay between 0 and the computed delay. Alternatively, pass a function to implement custom jitter strategies.227228**Note:** Jitter is not applied when the server provides a `Retry-After` header, as the server's explicit timing should be respected.229228Retries are not triggered following a [timeout](#timeout).230The `retryOnTimeout` option determines whether to retry when a request times out. By default, retries are not triggered following a [timeout](#timeout).231232The `shouldRetry` option provides custom retry logic that **takes precedence over all other retry checks**. This function is called first, before any other retry validation.233234**Note:** This is different from the `beforeRetry` hook:235- `shouldRetry`: Controls WHETHER to retry (called before the retry decision is made)236- `beforeRetry`: Called AFTER retry is confirmed, allowing you to modify the request237238The function receives a state object with the error and retry count (starts at 1 for the first retry), and should return:239- `true` to force a retry (bypasses `retryOnTimeout`, status code checks, and other validations)240- `false` to prevent a retry (no retry will occur)241- `undefined` to use the default retry logic (`retryOnTimeout`, status codes, etc.)242243**General example**244245```js246import ky from 'ky';247248const json = await ky('https://example.com', {
5 unmodified lines
254 }255}).json();256```257258**Retrying on timeout:**259260```js261import ky from 'ky';262263const json = await ky('https://example.com', {264 timeout: 5000,265 retry: {266 limit: 3,267 retryOnTimeout: true268 }269}).json();270```271272**Using jitter to prevent thundering herd:**273274```js275import ky from 'ky';276277const json = await ky('https://example.com', {278 retry: {279 limit: 5,280281 // Full jitter (randomizes delay between 0 and computed value)282 jitter: true
6 unmodified lines
289 }290}).json();291```292293**Custom retry logic:**294295```js296import ky, {HTTPError} from 'ky';297298const json = await ky('https://example.com', {299 retry: {300 limit: 3,301 shouldRetry: ({error, retryCount}) => {302 // Retry on specific business logic errors from API303 if (error instanceof HTTPError) {304 const status = error.response.status;305306 // Retry on 429 (rate limit) but only for first 2 attempts307 if (status === 429 && retryCount <= 2) {308 return true;309 }310311 // Don't retry on 4xx errors except rate limits312 if (status >= 400 && status < 500) {313 return false;314 }315 }316317 // Use default retry logic for other errors318 return undefined;319 }320 }321}).json();322```323324> [!NOTE]325> Chromium-based browsers automatically retry `408 Request Timeout` responses at the network layer for keep-alive connections. This means requests may be retried by both the browser and ky. If you want to avoid duplicate retries, you can either set `keepalive: false` in your request options (though this may impact performance for multiple requests) or remove `408` from the retry status codes.326327##### timeout
722 unmodified lines