Skip to content
mentoor

Topic 3 of 4 · 5 min read

Testing rate limits, timeouts and malformed output

Goal: Write tests that force rate-limit, timeout, truncated-stream and malformed-output paths and assert that the app recovers.

Failure paths almost never happen in development and always happen in production, so force them in tests: make the fake provider fail in each way and assert what your app does next. If you only test the happy path, your retry logic, fallbacks and error messages are untested code.

Check yourself · 1 of 3

Your retry code handles 429 responses. How do you test it without waiting for real backoff delays?

Choose one answer

Why it matters

Model APIs fail often enough to plan for it. They return 429 when you exceed a rate limit, 5xx or an "overloaded" error when capacity is short, and they can stall mid-stream. The model itself can return text that is not valid JSON, or a reply cut off at the token limit. Your users meet these on a busy day, not in your demo.

The four cases to force

  1. Rate limit (429). Return a 429 with a retry-after header. Assert that the app waits at least that long, retries a bounded number of times, and then gives a clear error. Use fake timers so the test does not really sleep.
  2. Timeout or stalled stream. Make the fake never answer, or stop sending chunks. Assert that the request is cancelled after your timeout and that the UI leaves its loading state.
  3. Truncated output. Return a reply with a stop reason of max_tokens or a stream that ends early. Assert that the app does not treat half a reply as complete. It should retry with a higher limit or show a notice.
  4. Malformed output. Return JSON with a missing field, an extra sentence before the object, or a broken bracket. Assert that validation catches it and the app repairs it, retries or fails with a readable message.

Assert the recovery, not only the error

For each case, check three things: the app does not crash, the user sees a specific message with what to do next, and the retry count is bounded. An unbounded retry loop against a 429 makes the outage worse.

Before and after

// Before: only the happy path
const data = JSON.parse(reply.text);
// After: a test feeds bad text and expects a clean failure
it("retries once on invalid JSON, then reports it", async () => {
  const complete = vi.fn().mockResolvedValue({ text: "Sure! {\"total\": 4" });
  await expect(extractOrder(msg, { complete })).rejects.toThrow("invalid_model_output");
  expect(complete).toHaveBeenCalledTimes(2);
});

What goes wrong

  • Real sleeps in tests. A test that waits 30 seconds for a backoff gets deleted.
  • Testing only the first failure. The second attempt, after a retry, is where state bugs show up.
  • No cap on retries. Every client retries at once and keeps the provider down.
  • Treating truncation as success. A cut-off JSON object parses as an error, but cut-off prose looks fine and ships.

Examples

A 429 with retry-after

The fake returns status 429 with retry-after: 2 once, then a normal reply. With fake timers the test advances 2 seconds and asserts exactly two calls and a final success. A second test returns 429 five times and asserts that the app stops after three tries and shows "The service is busy, try again in a minute".

A stalled stream

The fake yields two chunks and then waits forever. The test advances the clock past the 20 second idle timeout and asserts that the request was aborted, partial text is kept visible, and a "Retry" button appears.

Key points

  • Force each failure on purpose: 429, overloaded, stalled stream, truncated reply and invalid JSON.
  • Use fake timers so backoff and timeout tests run instantly instead of sleeping.
  • Assert the recovery: no crash, a specific message for the user and a bounded number of retries.
  • Check the stop reason: a reply cut off at the token limit must not be handled as complete.
  • Test the second attempt too, since retry code is where state bugs hide.

Common mistakes

  • Using real timers, so backoff tests take minutes and get skipped.
  • Writing a retry loop with no maximum and no test that proves it stops.
  • Parsing model JSON without a test for extra text, missing fields or a cut-off object.
  • Checking that an error is thrown but not what the user sees afterwards.

Check yourself · 2 of 3

A fake provider returns a reply with stop reason max_tokens and half a JSON object. What should the test assert?

Choose one answer

Check yourself · 3 of 3

A test shows the client retries a 429 forever when the fake keeps returning it. What is the real-world risk?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic