SevyDevy

API Error Handling: Problem Details, Status Codes and Safe Retries

, Last updated , 18 min read

Summary

  • Good API error handling means every failure tells the client three things: what went wrong, who must fix it, and whether trying again can help.
  • The HTTP status code is the first signal. A 4xx code (400 to 499) means the request needs changing. A 5xx code (500 to 599) means the server failed.
  • RFC 9457 problem details is the standard error body, defined by the IETF, the group that writes internet standards. It is a small JSON object with fixed fields such as type, title, status, detail and instance.
  • A retryable error is one that may succeed later without changes, such as an overload. A terminal error fails the same way every time until someone changes something.
  • Beginners can stop after the status code table. Engineers then get a tested Python error builder, a client retry decision function and a leak-free 500 handler.

What goes wrong when an API reports errors badly?

When API error handling is poor, the apps calling the API guess, and they guess wrong. They retry requests that will never work, give up on requests that would, and show users text meant for engineers.

Picture a common setup. A food-delivery checkout API answered every failure with status 500 and the raw text of the exception. The setup is made up, but each failure in it is a realistic one.

During a busy dinner hour, the payment partner slowed down. The mobile app saw 500 and retried each order three times. A few customers were charged twice, and one error screen showed a database host address.

Three separate design gaps caused this. The status code did not say who was at fault. The body did not say whether a retry was safe. The message carried internal details nobody outside should see.

Which words do you need before designing API errors?

You need five words. Each one comes back in the sections below.

  • Status code: the three-digit number at the top of every HTTP response, such as 404. Its first digit gives the class, so 4xx means client error.
  • Response body: the content after the headers. For errors, this is where the details live.
  • Header: a named line of metadata on a request or response, such as Content-Type, which names the body's format.
  • Idempotent: a request you can send twice with the same effect as sending it once. RFC 9110 calls GET, HEAD, OPTIONS, TRACE, PUT and DELETE idempotent.
  • Retry-After: a response header that says how long to wait, as seconds or as a date. Servers send it with 503, 429 and some redirects.

POST and PATCH are not idempotent by definition. Sending a POST twice may create two orders. That one fact drives most of the retry rules later.

What does good API error handling look like?

Good API error handling gives every failure a contract: a status code from the HTTP standard, a body in one fixed format, and a clear retry signal. A contract here means a promise clients can write code against.

The client code then never reads English sentences to decide what to do. It reads the status code, then a machine-readable type, then the retry signal. People read the human text.

Here is the same checkout failure designed properly. The payment partner is slow, so the API returns 503 with a wait time. The app waits, then retries safely with a key that stops double charges.

A retryable failure, handled well

Notice that the client does not guess. The 503 code, the Retry-After header and the idempotency key together make the second attempt safe.

Diagram connections:

  • Mobile app to Checkout API (POST /orders)
  • Checkout API to Payment partner (charge)
  • Payment partner to 503 problem response (timeout)
  • 503 problem response to Wait 30 seconds (client reads signal)
  • Wait 30 seconds to Same request again (then)
  • Same request again to Checkout API (no double charge)
  • Mobile app: App → API: POST /orders with an idempotency key
  • Checkout API: App → API: places the order
  • Payment partner: API → partner: slow, times out
  • 503 problem response: API → app: retryable true, Retry-After 30
  • Wait 30 seconds: App: waits as Retry-After says, with a cap
  • Same request again: App → API: same idempotency key

What is RFC 9457 problem details?

RFC 9457 problem details is the IETF standard format for HTTP API error bodies. It defines a JSON object with five standard members, none of them required, and the media type application/problem+json. A media type is the format label sent in the Content-Type header.

The IETF is the body that publishes internet standards, called RFCs. RFC 9457 came out in July 2023 and replaced the older RFC 7807, which used the same idea. As of 31 October 2026 it is the current version.

A problem details body is like a printed courier failure slip. The tick box for the reason is the type. The printed heading is the title. The handwritten note is the detail. The slip's reference number is the instance.

Where the picture breaks: a courier decides on its own when to try again. In an API, the server only gives signals. The client decides whether to retry.

The five standard members

The standard members of an RFC 9457 problem details object (none is required)
MemberJSON typeWhat it holdsRule worth knowing
typestring (URI reference)The problem's identity, written as a URI: a web-address-style ID, often a link to docsClients must use it as the main identifier. Missing means about:blank.
titlestringA short human summary of the problem typeShould stay the same for every occurrence, except translation.
statusnumberThe HTTP status code, copied into the bodyOnly advisory. The real response must carry the same code.
detailstringA human explanation of this one occurrenceShould help the client fix it. Clients should not parse it.
instancestring (URI reference)An identifier for this one occurrenceMay be a link to fetch, or just a unique ID.

The type value about:blank is special. It means the problem has no meaning beyond the status code. Its title should then be the standard status phrase, such as Not Found.

A member with the wrong JSON type must be ignored. So a status sent as the string "422" is dropped by any reader that follows the RFC.

Extension members

You may add your own members for a problem type. RFC 9457's own example adds an errors array, with a JSON pointer to each bad field. A JSON pointer is a path into the request body, such as #/pincode.

Clients must ignore extension members they do not recognise. That rule lets you add fields later without breaking old apps. Names should start with a letter, use letters, digits or underscores, and be at least three characters.

This guide adds one extension, retryable, set to true or false. RFC 9457 does not define it. It is a design choice, so document it with each problem type.

http
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Some fields are not valid.",
  "status": 422,
  "detail": "2 fields need changes before we can place the order.",
  "retryable": false,
  "errors": [
    {"pointer": "#/quantity", "detail": "must be 1 or more"},
    {"pointer": "#/pincode", "detail": "must be 6 digits"}
  ]
}

Which HTTP status code should an API error use?

Use the most specific code whose meaning matches the failure, and fall back to 400 or 500 only when nothing fits. Clients, proxies and monitoring tools all act on the code before reading any body.

The first digit answers who must act. A 4xx code says the client must change something. A 5xx code says the server failed, and the same request might work later.

Common error codes for APIs, names as in the IANA registry (as of 31 October 2026)
CodeUse it whenRetry the same request?
400 Bad RequestThe request is malformed, such as broken JSONNo, fix it first
401 UnauthorizedCredentials are missing or invalid; send a WWW-Authenticate headerOnly after getting valid credentials
403 ForbiddenCredentials are valid but lack permissionNot with the same credentials; other credentials may help
404 Not FoundThe resource does not exist, or you hide that it existsNo
405 Method Not AllowedThe method is not supported here; send an Allow headerNo
409 ConflictThe request clashes with current state, such as stock already soldOnly after reading fresh state
412 Precondition FailedA conditional header, such as If-Match, did not matchOnly after fetching the new version
422 Unprocessable ContentSyntax is fine but the values break a ruleNo, it will fail the same way
429 Too Many RequestsThe client hit a rate limitYes, after Retry-After if sent
500 Internal Server ErrorAn unexpected server bugUnsafe to assume; see the retry section
502 Bad GatewayA gateway got an invalid reply from the server behind itOften, if the request is idempotent
503 Service UnavailableOverload or maintenance, expected to passYes, after Retry-After if sent
504 Gateway TimeoutA gateway got no reply in timeOften, if the request is idempotent

400 vs 422, and 401 vs 403

Send 400 when the server cannot even read the request, such as JSON with a missing bracket. Send 422 when the JSON parses but a value breaks a rule, such as a pincode of five digits.

Send 401 when the caller has not proved who they are. Send 403 when you know who they are and the answer is still no. To avoid confirming that a private resource exists, a server may send 404 instead of 403.

Do not send 200 with an error inside the body. Caches, retry libraries and dashboards all trust the status code. A 200 tells every one of them that the request worked.

Beginners can stop here. You now know the status classes, the problem details format and which code fits which failure. The rest of the guide is the engineering: retry rules, safe messages and tested code.

Which API errors are retryable and which are terminal?

An error is retryable when the same request may succeed later without changes. It is terminal when it will fail again until a person or program changes something, such as the input or the permissions.

Overloads, rate limits and gateway timeouts are usually retryable. Validation failures, missing permissions and missing resources are terminal. A 500 is the hard case, because a bug might fail every time.

Retryable is not the same as safe to retry

Pause and predict. A POST /orders call returns 503 with retryable set to true. Should the app retry it automatically?

Not by itself. The 503 says the server is overloaded, but the order might already have been half-processed. Retrying a POST could create a second order or a second charge.

Two conditions must both hold. The error must be retryable, and repeating the request must be safe. A request is safe to repeat when its method is idempotent, or when it carries an idempotency key.

An idempotency key is a unique ID the client attaches to a write. The server stores the result under that key and returns it again for a repeat. The SevyDevy guide on idempotency keys explains what the server stores.

How a client decides what to do with an error

Notice the two separate questions. Retryable asks whether waiting can help. Safe to repeat asks whether a second attempt could do harm.

Diagram connections:

  • Error response arrives to Retryable?
  • Retryable? to Safe to repeat? (Yes)
  • Retryable? to Is it a 4xx? (No)
  • Safe to repeat? to Wait, then retry (Yes)
  • Safe to repeat? to Do not auto-retry (No)
  • Is it a 4xx? to Fix the request (Yes)
  • Is it a 4xx? to Give up, show support ID (No, a 5xx)
  • Error response arrives: Read status, type and retryable
  • Retryable?: Body flag, else 429, 502, 503 or 504
  • Safe to repeat?: Idempotent method or idempotency key
  • Is it a 4xx?: Client must change the request
  • Wait, then retry: Honour Retry-After, cap the attempts
  • Do not auto-retry: Ask the user, or add a key next time
  • Fix the request: Map the type to a message or form error
  • Give up, show support ID: Show the instance value to the user

How long to wait

Retry-After holds either a number of seconds, such as 30, or an HTTP date. Honour it when it is present. When it is absent, use exponential backoff with jitter: waits that double each time, plus a little randomness. The SevyDevy retry backoff guide covers it in depth.

Always cap the wait and the number of attempts. RFC 6585 lets a 429 include Retry-After but does not require it. A broken server can also send an absurd value.

How do you write error messages that do not leak internals?

Write the detail for the person calling the API, and send everything else to your logs. RFC 9457 says problem details are not a debugging tool and warns against exposing stack dumps.

A stack trace is the list of function calls active when the error happened. It can reveal file paths, library versions, SQL text and host addresses. The OWASP error handling cheat sheet shows how such details help an attacker map your stack.

The fix is a catch-all handler. It gives every unexpected error a random ID, logs the full trace under that ID, and returns a generic problem with the ID in the instance member.

A leak-free 500: one ID, two audiences

Notice that the stack trace and the client response never meet. The shared ID is the only link between them.

Diagram connections:

  • Unexpected exception to Catch-all handler (raises)
  • Catch-all handler to Server logs (trace and ID)
  • Catch-all handler to Client response (ID only)
  • Client response to Support engineer (user quotes ID)
  • Support engineer to Server logs (finds trace)
  • Unexpected exception: Inside the checkout handler
  • Catch-all handler: Makes a random error ID
  • Server logs: Full stack trace plus the error ID
  • Client response: Generic 500 problem, instance holds the ID
  • Support engineer: Searches logs for the ID the user quotes

The Python below builds problem responses from one catalogue of problem types. It uses only the standard library. Each type has a fixed status, a fixed title and a retryable flag.

python
import json
import logging
import uuid

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("checkout")

BASE = "https://api.example.com/problems/"

# One row per problem type: status, fixed title, retryable
CATALOGUE = {
    "validation-error": (422, "Some fields are not valid.", False),
    "out-of-stock": (409, "An item in the cart is out of stock.", False),
    "payments-unavailable": (503, "Payments are briefly unavailable.", True),
    "internal-error": (500, "Something went wrong on our side.", False),
}


def problem(kind, detail, retry_after=None, **extensions):
    status, title, retryable = CATALOGUE[kind]
    body = {
        "type": BASE + kind,
        "title": title,
        "status": status,
        "detail": detail,
        "retryable": retryable,
        **extensions,
    }
    headers = {"Content-Type": "application/problem+json"}
    if retry_after is not None:
        headers["Retry-After"] = str(retry_after)
    return status, headers, json.dumps(body, indent=2)


def unexpected(exc):
    error_id = str(uuid.uuid4())
    # The full stack trace goes to your logs, never to the client
    log.error("error_id=%s", error_id, exc_info=exc)
    return problem(
        "internal-error",
        "We could not place your order. Quote the instance value to support.",
        instance="urn:uuid:" + error_id,
    )


if __name__ == "__main__":
    status, headers, body = problem(
        "validation-error",
        "2 fields need changes before we can place the order.",
        errors=[
            {"pointer": "#/quantity", "detail": "must be 1 or more"},
            {"pointer": "#/pincode", "detail": "must be 6 digits"},
        ],
    )
    print(status, headers)
    print(body)
    try:
        {}["db_password"]
    except KeyError as exc:
        status, headers, body = unexpected(exc)
        print(status, body)

We ran it on Python 3.13. It prints the 422 body shown earlier, then a 500 body with the generic detail and an instance made of urn:uuid plus a random ID.

The KeyError trace, including the db_password key name, appears only in the log output. That is the check: search the printed 500 body for db_password and find nothing.

We also served these responses over a real local HTTP server and checked one rule. A database error containing a host address appeared in the log and was absent from the response body.

What still leaks if you are careless

  • Detail text that echoes whole user inputs, such as a full card number, back into responses and logs.
  • A 403 for private records that exist but a 404 for IDs that do not, which tells a stranger which IDs are real.
  • Server and framework version headers, which have nothing to do with the body but reveal the same facts.

How should a client read problem details and decide what to do?

A client should branch on the status code and the type, read the retry signals, and never parse the detail text. RFC 9457 tells consumers not to parse detail. Its wording is written for people and can change between releases.

The function below follows the decision diagram. It trusts the retryable flag when the body has one, and falls back to the status code when it does not.

python
import json
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime

REPEATABLE = {"GET", "HEAD", "OPTIONS", "PUT", "DELETE"}


def wait_seconds(retry_after, default=2):
    if not retry_after:
        return default
    if retry_after.isdigit():
        return int(retry_after)
    when = parsedate_to_datetime(retry_after)
    return max(0, int((when - datetime.now(timezone.utc)).total_seconds()))


def decide(method, status, headers, raw_body, has_idempotency_key=False):
    body = {}
    if headers.get("Content-Type", "").startswith("application/problem+json"):
        body = json.loads(raw_body)
    can_repeat = method in REPEATABLE or has_idempotency_key
    retryable = body.get("retryable")
    if retryable is None:
        retryable = status in (429, 502, 503, 504)
    if retryable and can_repeat:
        return "retry in %ss" % wait_seconds(headers.get("Retry-After"))
    if retryable:
        return "do not auto-retry: add an idempotency key first"
    if status // 100 == 4:
        return "fix the request: " + body.get("type", "about:blank")
    return "give up, show support ID: " + body.get("instance", "none")


if __name__ == "__main__":
    cases = [
        ("POST", 422, {"Content-Type": "application/problem+json"},
         '{"type": "https://api.example.com/problems/validation-error",'
         ' "status": 422, "retryable": false}', True),
        ("POST", 503, {"Content-Type": "application/problem+json", "Retry-After": "30"},
         '{"type": "https://api.example.com/problems/payments-unavailable",'
         ' "status": 503, "retryable": true}', True),
        ("POST", 503, {"Retry-After": "30"}, "", False),
        ("GET", 429, {"Retry-After": "120"}, "", False),
        ("POST", 500, {"Content-Type": "application/problem+json"},
         '{"status": 500, "retryable": false, "instance": "urn:uuid:1b2c"}', True),
    ]
    for method, status, headers, raw, key in cases:
        print(method, status, "=", decide(method, status, headers, raw, key))

Running it on Python 3.13 prints exactly these five lines:

text
POST 422 = fix the request: https://api.example.com/problems/validation-error
POST 503 = retry in 30s
POST 503 = do not auto-retry: add an idempotency key first
GET 429 = retry in 120s
POST 500 = give up, show support ID: urn:uuid:1b2c

Two limits of this code. It looks up Content-Type in a plain dictionary, so pass a case-insensitive header map from your HTTP library. And wait_seconds trusts the server's number. In production, cap it at a maximum you choose and add jitter, so thousands of phones do not retry in the same second.

What mistakes break an API error contract?

Most broken contracts come from treating errors as text rather than data. These are the mistakes worth checking for in a review.

Common error contract mistakes and what to do instead
MistakeWhy it hurtsDo this instead
Status 200 with an error fieldCaches and retry libraries treat it as successSend the matching 4xx or 5xx code
Every failure is 500Clients cannot tell their bug from yoursUse 4xx codes for client mistakes
Clients match on detail textRewording a message breaks appsMatch on the type URI
Title changes per requestBreaks grouping in logs and dashboardsKeep one title per type; put specifics in detail
Body status differs from the real codeClients get two answersCopy the real code, or omit status
Stack traces in responsesLeaks paths, versions and hostsLog the trace; return an instance ID

Adding extension members is safe, because clients must ignore ones they do not know. Adding a new problem type is safe when clients fall back on the status code for unknown types.

Changing an existing type's status or meaning breaks clients. Treat it like any breaking API change, as the SevyDevy API versioning guide describes.

When several problems happen at once, RFC 9457 recommends returning the most relevant or urgent one. For many failures of the same type, such as several bad fields, use one type with an errors array.

How do you explain API error handling in a system design interview?

Interviewers want to see that errors are part of the contract, that you separate retryable from terminal, and that you keep internals private. This frame covers all three.

  1. Name the format

    Say every error uses RFC 9457 problem details with application/problem+json, and clients branch on the type URI.

  2. Map failures to status codes

    Give two or three examples: 422 for bad input, 409 for a stock conflict, 503 for a partner outage.

  3. Separate retryable from terminal

    Explain the retryable flag, Retry-After, and why writes need an idempotency key before any automatic retry.

  4. Protect internals

    Describe the catch-all handler: trace to logs, random ID to the client in the instance member.

  5. Close with operations

    Mention alerting on 5xx rates per type and capping client retries so an outage does not become a retry storm.

Questions people ask

Is RFC 9457 the same as RFC 7807?

RFC 9457 replaces RFC 7807 and keeps the same core format. The five members and the application/problem+json media type are unchanged. RFC 9457, published in July 2023, adds a shared IANA registry of common problem types. It also clarifies multiple problems and type URIs that cannot be fetched.

Should I use 400 or 422 for validation errors?

Use 400 when the server cannot parse the request at all, such as malformed JSON. Use 422 when the request parses but values break a rule, such as a quantity of zero. RFC 9110 names 422 Unprocessable Content. Either way, add a problem type and an errors array so the client can point to each field.

Do I have to use problem details for every error?

No. RFC 9457 itself says problem details are not the only way to describe an HTTP problem. It also notes that generic conditions are often clearer as a plain status code, such as 403 for a PUT the caller may not make. Use problem details when the client needs more than the code, like a field list or a retry signal.

Is retryable a standard field in problem details?

No. RFC 9457 defines only type, title, status, detail and instance. Retryable is an extension member that this guide recommends, so you must document it for each problem type. Clients that do not know it will ignore it, as RFC 9457 requires, and fall back on the status code.

Should the type URI point to a real web page?

It is a good idea but not required. RFC 9457 recommends absolute URIs and says a resolvable type should lead to documentation. Clients should not fetch the type URI automatically, though. Code should treat it as an identifier and compare it as a string.

Is it safe to retry a 500 Internal Server Error?

Only when repeating the request cannot cause harm. A 500 means an unexpected bug, so the same request may fail again, and a write may have partly happened. A cautious rule is one or two retries at most, only for idempotent methods or keyed requests, with backoff.

How do I return several validation errors at once?

Use one problem type for validation and put each failure in an extension array. RFC 9457's own example uses an errors array where each item has a detail and a pointer to the bad field. For problems of different types, RFC 9457 recommends returning the most relevant or urgent one.