← Back to Angular, page 5

angular-0081 · Medium mid

Write an HTTP interceptor that retries failed GET requests with exponential backoff, respects Retry-After, and does not retry unsafe requests. How do you test it?

Retry only idempotent requests (GET and HEAD) on transient failures such as network errors, 429, 502, 503 and 504. Use retry with a delay function that uses the Retry-After header when present and exponential backoff otherwise, cap the attempts, and rethrow other errors immediately. Test it with HttpTestingController and fakeAsync.

Full answer

A retry interceptor must be careful. Retrying the wrong request or retrying too fast can make an outage worse or duplicate a payment.

Rules for a safe design:

  1. Which requests: only safe, idempotent methods (GET, HEAD). A POST can create two orders if retried. PUT and DELETE are idempotent by definition, but retry them only if your API guarantees it.
  2. Which errors: network failure (status === 0), 429, 502, 503, and 504. Never retry 400, 401, 403, 404, or 422, because they will fail the same way.
  3. How many: a small number, for example 3.
  4. How long to wait: exponential backoff (base * 2^(attempt - 1)), capped at a maximum. Add random jitter in production so many clients do not retry together. If the server sends Retry-After (seconds), wait that long.
  5. Opt-out: let a request disable retries, for example with an HttpContextToken.

Implementation with RxJS 7: retry({ count, delay }). The delay callback receives the error and the attempt number, and returns an Observable that emits when to retry. To stop retrying for an error, return throwError(() => error) from it. The interceptor is a function, so it can inject() settings.

Testing: provide HttpClient, the testing backend, and the interceptor. Use fakeAsync: call get, expectOne(url).flush('', { status: 503, statusText: 'Unavailable' }), then tick(delay) and expectOne again. Assert the number of attempts, that 404 is not retried, and that POST is not retried. Call http.verify() at the end.

Where else it lives: some teams retry inside a service for chosen calls only, since a global retry may hide problems. Show user feedback (a "retrying" message) for long delays.

typescript
// file: retry.interceptor.ts
import { HttpContextToken, HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { Observable, retry, throwError, timer } from 'rxjs';

export const MAX_RETRIES = new HttpContextToken<number>(() => 3);

const RETRYABLE_STATUS = new Set([0, 429, 502, 503, 504]);
const BASE_DELAY_MS = 100;
const MAX_DELAY_MS = 5000;

function delayFor(error: unknown, attempt: number): Observable<number> {
  if (!(error instanceof HttpErrorResponse) || !RETRYABLE_STATUS.has(error.status)) {
    return throwError(() => error);
  }
  const retryAfter = Number(error.headers.get('Retry-After'));
  const wait = Number.isFinite(retryAfter) && retryAfter > 0
    ? retryAfter * 1000
    : Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_DELAY_MS);
  return timer(wait);
}

export const retryInterceptor: HttpInterceptorFn = (req, next) => {
  const safe = req.method === 'GET' || req.method === 'HEAD';
  const count = safe ? req.context.get(MAX_RETRIES) : 0;
  return next(req).pipe(retry({ count, delay: delayFor }));
};

// file: retry.interceptor.spec.ts
import { HttpClient, provideHttpClient, withInterceptors } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { retryInterceptor } from './retry.interceptor';

describe('retryInterceptor', () => {
  let http: HttpClient;
  let backend: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(withInterceptors([retryInterceptor])), provideHttpClientTesting()],
    });
    http = TestBed.inject(HttpClient);
    backend = TestBed.inject(HttpTestingController);
  });

  afterEach(() => backend.verify());

  it('retries a GET after 503 with backoff and then succeeds', fakeAsync(() => {
    let result: unknown;
    http.get('/api/data').subscribe((r) => (result = r));

    backend.expectOne('/api/data').flush('', { status: 503, statusText: 'Unavailable' });
    tick(100); // first backoff
    backend.expectOne('/api/data').flush('', { status: 503, statusText: 'Unavailable' });
    tick(200); // second backoff
    backend.expectOne('/api/data').flush({ ok: true });

    expect(result).toEqual({ ok: true });
  }));

  it('does not retry a 404', fakeAsync(() => {
    let status = 0;
    http.get('/api/missing').subscribe({ error: (e) => (status = e.status) });

    backend.expectOne('/api/missing').flush('', { status: 404, statusText: 'Not Found' });
    tick(10000);

    expect(status).toBe(404);
  }));

  it('does not retry a POST', fakeAsync(() => {
    let status = 0;
    http.post('/api/orders', {}).subscribe({ error: (e) => (status = e.status) });

    backend.expectOne('/api/orders').flush('', { status: 503, statusText: 'Unavailable' });
    tick(10000);

    expect(status).toBe(503);
  }));
});

Angular 20.3 and RxJS 7, type-checked, and the spec was run in headless Chrome with `ng test`, and all three specs pass. The delays are 100 ms base so the spec is fast.

Key points

  • Retry only GET and HEAD, and only for transient errors (0, 429, 502, 503, 504).
  • Use `retry({ count, delay })` with exponential backoff, a cap, and `Retry-After`.
  • Return `throwError` from `delay` to stop retrying.
  • Test with `HttpTestingController` and `fakeAsync` with `tick`.

Common mistakes

  • Retrying POST requests, which can duplicate side effects.
  • Retrying on 4xx errors that will never succeed.
  • Retrying immediately without a delay, increasing load on a failing server.

Follow-ups

  • Why add jitter to the backoff?
  • How would you let one request opt out of retries?
  • How would you show the user that a retry is happening?

Tips

  • Start with what you will not retry. It shows engineering judgement.
  • Mention idempotency by name.
  • Say that you test the "no retry" cases as carefully as the retry cases.

Evaluation rubric

  • Chooses requests and errors to retry with reasons.
  • Implements backoff and Retry-After correctly.
  • Tests with fakeAsync and verify.