Got HTTP Retry With Exponential Backoff

Configure the got client to retry transient failures with exponential backoff, status-code allowlists, and per-attempt timeouts for safer polling.

JavascriptNodeResilience

Code

javascriptsnippet
21 lines
import got from 'got';

const client = got.extend({
  retry: {
    limit: 4,
    methods: ['GET'],
    statusCodes: [408, 429, 500, 502, 503, 504],
    calculateDelay: ({ computedValue }) => Math.min(computedValue, 8000),
    errorCodes: ['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED'],
  },
  timeout: { request: 10_000 },
  hooks: {
    beforeRetry: [
      ({ attemptCount, url }) => {
        console.log('retrying', url.href, 'attempt', attemptCount);
      },
    ],
  },
});

const body = await client('https://api.example.com/orders').json();

Inside the snippet

Every asynchronous step is awaited, so rejections surface where the call happens.

All steps draw their inputs from the top-level bindings: client, body.

What to watch for

  • Dependency check: got — not built-in, must be present in the project.

Putting it to use

Running the file prints labeled results such as retrying — each operation’s effect is visible in the output.

Core lines

const body = await client('https://api.example.com/orders').json();
({ attemptCount, url }) => {
console.log('retrying', url.href, 'attempt', attemptCount);
},

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `got` must be present in the project or the import fails at load time.