# In the FDE coding round, a 429 can mean slow down or stop calling

> A 60-minute practice run builds a retry function in Python, and the hard part is judging which errors to retry, how long to wait and when to quit.

Original: https://fdetimes.net/en/guides/fde-interview-429-retry-backoff/

"Write exponential backoff with jitter for a flaky external API." An FDE interview guide on the Harvard FAS careers blog uses that exact sentence as a sample prompt for a 60-minute coding round.

The guide describes FDE coding rounds as close-to-real problems. Another guide, on aiagentskit, sketches what a strong answer to this kind of prompt looks like: backoff with full jitter, and a unique idempotency key on every request that changes data.

The prompt sounds like an exercise in writing a loop, but the hard part is judgment: which errors to retry, how long to wait, and when to stop. The 429 code is where candidates slip most easily, because the same code can mean "slow down" or "stop calling".

## What you will build, and what you need

You will write a `call_api` function that does five things: classifies errors, logs every failure, waits exactly as long as the Retry-After header says, retries a limited number of times with backoff and jitter, and attaches an idempotency key to POST requests. All you need is Python 3 and a stopwatch.

The code here is **simplified**. You pass in a `send` function yourself, which returns a tuple `(status, headers, body)` with lower-case header names. That lets you practice without a network or an API key; in real use, wrap the HTTP library you know in the same interface.

## Minutes 0–10: read the docs before typing any code

Open the Claude API's error-code page and build the table below yourself. The third column matters most, because those are the decisions you will have to explain out loud to the interviewer.

| Code | What the docs say | Decision |
|---|---|---|
| 400 | Malformed request; sending it again fails again | Stop, fix the request |
| 429 with Retry-After | The header says how long to wait | Wait exactly that long, then call again |
| 429 without Retry-After | For the Claude API, a 429 caused by hitting a spend cap carries no such header and keeps failing until access is restored | Cautious assumption: treat it as a spend cap, stop and alert the owner |
| 500 | Server-side error | Retry with exponential backoff; if it persists, send the request ID to support |
| Code not in the table | Unknown | Stop by default, log it, reread the docs |

The third row is the trap. The docs do not say every 429 without Retry-After is a spend cap, so this is your assumption, and you need to say so clearly. Then turn the table into code:

```python
RETRYABLE = {500}  # add other 5xx codes after reading the docs

def decide(status, headers):
    if status == 0:
        return "backoff"      # timeout or connection error, see minute 35
    if status < 400:
        return "ok"
    if status == 429:
        # Claude API only: no retry-after means treat it as a spend cap
        return "wait" if headers.get("retry-after") else "stop"
    if status in RETRYABLE:
        return "backoff"
    return "stop"             # 400 and any unknown code
```

**Check yourself:** for every branch, you can say one sentence beginning "because the docs say…" or "because I assume…".

## Does the 429 rule carry over to other APIs?

Not wholesale. RFC 6585, the document that defines the 429 code, says only that the response *may* include Retry-After, so a 429 without the header is still valid and the client needs a fallback. MDN also notes that support for Retry-After remains uneven on both clients and servers.

OpenAI's documentation treats 429 as a temporary rate-limit signal, but warns that failed requests still count toward the per-minute limit, so resending them continuously will not help. Google's Cloud Storage documentation classes 429 and 5xx as transient errors that can be retried with exponential backoff and jitter.

So for other APIs, the sensible fallback when Retry-After is missing is bounded backoff, never an immediate resend. Only the Claude API, whose docs say plainly that the spend-cap case will keep failing, justifies stopping early. Being able to state that difference in front of the interviewer earns you points.

## Minutes 10–35: retry in moderation, and leave a trail

The Claude API docs state that the official SDK automatically retries transient errors such as connection errors, rate limits and 5xx, using exponential backoff, twice by default, and honors `retry-after` when that header is present. Your function can follow the same structure.

AWS explains that when several layers retry at once, load multiplies, and the fix is almost always to cap how many times the client retries. MDN adds a detail that is easy to miss: Retry-After comes in two formats, either a number of seconds or an HTTP date.

For persistent 500 errors, the Claude API docs advise contacting support with the request ID. So on every failure, the function writes a log line with the method, URL, status code, request ID and attempt number. The header name `request-id` is a simplifying assumption; use the exact name from the docs of the API you are calling.

```python
import random, time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

MAX_RETRIES = 2  # matches the SDK default

def parse_retry_after(value):
    value = value.strip()
    if value.isdigit():
        return int(value)
    when = parsedate_to_datetime(value)
    return max(0, (when - datetime.now(timezone.utc)).total_seconds())

def call_api(send, method, url, body=None, log=print):
    headers = {}
    for attempt in range(MAX_RETRIES + 1):
        try:
            status, resp_headers, resp_body = send(method, url, headers, body)
        except TimeoutError:
            status, resp_headers, resp_body = 0, {}, "timeout"
        action = decide(status, resp_headers)
        if action == "ok":
            return resp_body
        log(f"{method} {url} -> {status} "
            f"request-id={resp_headers.get('request-id')} attempt={attempt}")
        if action == "stop" or attempt == MAX_RETRIES:
            raise RuntimeError(f"{status}: {resp_body}")
        if action == "wait":
            delay = parse_retry_after(resp_headers["retry-after"])
        else:
            delay = random.uniform(0, 2 ** attempt)  # full jitter, simplified
        time.sleep(delay)
```

The second-to-last line is the jitter. According to AWS, jitter adds a little randomness to the wait so that retries spread out over time, instead of every client calling back at once.

**Check yourself:** faced with repeated 500s, the function makes exactly three calls and stops, and the log holds enough for someone else to take the request ID to the API provider. This version still has a hole: it retries a timed-out POST without an idempotency key.

## Minutes 35–45: can a timed-out POST be sent again?

A hypothetical: you POST to create a ticket in a client's CRM, the request times out, but the server had in fact created the ticket. Retry naively, and the client ends up with two tickets.

Stripe handles this with idempotency keys: with a key, you can resend after a connection error without fear of creating a second object. Stripe accepts the key on every POST request, while GET and DELETE are already idempotent, so sending a key with them has no effect.

Google Cloud Storage follows the same principle: an operation that is safe only under a condition may be retried only when that condition holds.

You add just three lines right after `headers = {}`:

```python
import uuid

IDEMPOTENCY_HEADER = "..."  # take the exact header name from the API's docs

def call_api(send, method, url, body=None, log=print):
    headers = {}
    if method == "POST":
        headers[IDEMPOTENCY_HEADER] = str(uuid.uuid4())  # generate ONCE
    for attempt in range(MAX_RETRIES + 1):
        ...  # the rest stays the same
```

The crux is where the key lives: it is generated **once**, outside the loop, and every attempt shares the same `headers`.

## Minutes 45–60: set your own traps, then say your decisions out loud

Build a fake server that returns responses from a preset script. In the practice version, replace `time.sleep` with an empty function so you do not have to wait; never carry that line into real code. Calls expected to stop are wrapped in `try/except`.

```python
def fake(responses):
    it = iter(responses)
    return lambda method, url, headers, body: next(it)

time.sleep = lambda s: None  # practice only

print(call_api(fake([(500, {"request-id": "req_1"}, ""),
                     (200, {}, "ok")]), "GET", "/items"))

try:
    call_api(fake([(429, {"request-id": "req_2"}, "spend cap")]),
             "POST", "/items")
except RuntimeError as e:
    print("stopped correctly after one call:", e)

seen = []
def flaky(method, url, headers, body):
    seen.append(dict(headers))
    if len(seen) == 1:
        raise TimeoutError
    return (200, {}, "created")

call_api(flaky, "POST", "/tickets")
assert seen[0].get(IDEMPOTENCY_HEADER)   # the first attempt already has a key
assert seen[0] == seen[1]                # the retry reuses that same key
```

The first `assert` matters: without it, the test would pass even if the function sent no key at all, because two empty dicts are equal. Then write two more scenarios yourself: a 429 with `retry-after: 3`, and a 400. For each one, state your reasoning out loud as if the interviewer were sitting across from you.

**Key point:** Retrying an error that never clears on its own only makes the client's system worse.

## How this skill shows up on a client site

The exercise mirrors the real job of connecting to an external API you do not control. So on day one of an integration engagement, build the same error-code table from minutes 0–10 and send it to the client to confirm before writing any code.

When the API returns a code that is not in the table, the default branch of `decide` stops; your job is to read the log, state your assumption and update the table.

When reading job ads, watch for phrases such as integrating with customer systems or working with third-party APIs. They may signal a coding round close to this exercise.

On a CV, a line such as "made integration X resilient to transient failures with backoff and idempotency keys" is worth more than a list of libraries, provided it comes with real numbers of your own.

Practice this exercise three times against three different APIs. By the third run, opening the error-code page before typing will be a reflex, and 429 will no longer be a trap.

**Try this week:**

- Set a 10-minute timer, read the error-code page of an API you have never used, and build a table of codes, meanings and decisions before writing the first line of code.
- Write the call_api function from this article, then run it through five scenarios with a fake server: 500 then 200, 429 with Retry-After, 429 without Retry-After, 400, and a timed-out POST.
- Add a line to your CV, with real numbers, about a time you made an integration resilient to transient failures.

## Sources

- [Claude API errors](https://platform.claude.com/docs/en/api/errors)

- [Retry-After header - HTTP | MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After)

- [RFC 6585: Additional HTTP Status Codes](https://www.rfc-editor.org/rfc/rfc6585.html)

- [Timeouts, retries, and backoff with jitter](https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter)

- [Idempotent requests | Stripe API Reference](https://docs.stripe.com/api/idempotent_requests)

- [Rate limits | OpenAI API](https://developers.openai.com/api/docs/guides/rate-limits)

- [Cloud Storage retry strategy](https://docs.cloud.google.com/storage/docs/retry-strategy)

- [Forward Deployed Engineer Interview: The Definitive 2026 Guide (FDE)](https://careerservices.fas.harvard.edu/blog/2026/08/01/forward-deployed-engineer-interview-the-definitive-2026-guide-fde/)

- [Cracking the Forward Deployed Engineer Interview: Questions, Rubrics, and Decomposition Guide](https://aiagentskit.com/blog/forward-deployed-engineer-interview-questions/)
