SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • What is an API?
  • API Styles
  • Idempotency
  • Data Formats
  • REST, GraphQL, gRPC
  • Pagination, Filtering and Sorting
  • API Versioning
  • Error Handling and Status Codes
  • OpenAPI / Swagger
  • Bulk APIs and File Upload
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Design

Error Handling and Status Codes

Tell the caller clearly what went wrong, and whether to try again.

⏱ 13 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Error handling in an API means telling the caller clearly what went wrong, whose fault it is, and whether to try again. HTTP status codes are the short, shared language for this.

  • The first digit of the code tells the story: 2xx success, 3xx go elsewhere, 4xx the client got it wrong, 5xx the server got it wrong.
  • A good error also has a body with a stable error type, a short message and a request id.
  • Never leak internal details (stack traces, SQL, file paths) to the caller. Log them on the server instead.

02Concept: What is it?

When a request fails, two readers need to understand why: the program that made the call (should it retry? log in again? fix its input?) and the person who debugs it later. The status code is for the program. The body is for both.

ClassMeaningWhose problemRetry?
2xxIt workedNobodyUsually no
3xxLook somewhere else, or use your cached copyNobodyFollow the redirect
4xxThe request was wrongThe clientNot until the request is fixed (429 and 409 are special)
5xxThe server failedThe serverOften yes, later, with backoff
Reading a status code
πŸ“¨Responsestatus code
→↓
2️⃣2xxuse the result
4️⃣4xxfix the request
5️⃣5xxtry again later
The first digit tells the client what kind of thing to do next.
🧠401 versus 403
401 means "I do not know who you are" (no login, or an expired one). 403 means "I know who you are, and you may not do this". The name "Unauthorized" for 401 is a historical oddity: it really means unauthenticated.

03Real-Life Example

🍡The Parcel Delivery Slip
A courier cannot deliver a parcel and leaves a slip. A useful slip says why: "wrong address" (your mistake: fix it), "nobody home, we will come back tomorrow" (try again later), or "our van broke down" (our mistake: we will retry). A useless slip just says "failed". Status codes are the checkboxes on the slip, and the error body is the handwritten note.
Delivery slip
API response
Delivered
200 / 201 / 204
Wrong address on the parcel
400 / 422 (fix the request)
You must show ID
401 (log in)
This parcel is not yours
403 (not allowed)
No such address
404 (not found)
Too many parcels at once, slow down
429 + Retry-After
Our van broke down
500 / 502 / 503 / 504
Tracking number on the slip
A request id in the error body
What a client should do with each class
βœ…2xxcarry on
→↓
πŸ› οΈ4xxfix, do not blindly retry
→↓
πŸ”5xx / 429wait, then retry with backoff

04Why Do We Need It?

🧭Clients can act
A client knows whether to fix, log in, wait or give up, without parsing English.
πŸ”Safe retries
Tools and libraries retry on 503 and 429, and never on 400. That only works with correct codes.
πŸ”Faster debugging
A request id in the error lets support find the exact log line in seconds.
πŸ›‘οΈNo information leaks
A clean error hides stack traces and internals from attackers.
πŸ“ŠHonest monitoring
Dashboards split 4xx from 5xx. A bug returned as 200 hides outages.
🀝Same language everywhere
One style across all endpoints is easier to learn and to build tools for.
The right status code is the cheapest documentation you will ever write. Pick it for the client's next move.

05Where Do We Use It?

πŸ”ŒEvery REST API
Each endpoint should map outcomes to the right class and code.
🧰SDKs and clients
Libraries turn 4xx into typed errors and retry 5xx for you.
πŸšͺAPI gateways
Gateways return their own 401, 403, 429 and 502 and 504 codes before the request reaches your code.
βš–οΈLoad balancers
They watch for 5xx to decide that a server is unhealthy.
πŸ“ˆMonitoring
Error rate alerts are usually based on the share of 5xx responses.
πŸ§ͺTests
Contract tests check that each failure returns the documented code and body.

06Types / Parts / How It Works

The codes you will use most

CodeNameUse it whenClient should
200OKA request succeeded and has a bodyUse the body
201CreatedA new resource was created (send its location)Use the new resource
204No ContentSuccess, nothing to return (for example a delete)Carry on
301 / 308MovedA resource has a new permanent addressFollow and update links
304Not ModifiedA conditional GET matched, use your cached copyUse the cache
400Bad RequestThe request is malformed or cannot be parsedFix the request
401UnauthorizedNo valid credentialsLog in or refresh
403ForbiddenKnown user, not allowedAsk for access
404Not FoundNo such resourceDo not retry
409ConflictThe request clashes with the current stateReload, merge, retry
422Unprocessable ContentWell-formed, but the values break the rulesFix the values
429Too Many RequestsA rate limit was hit (send Retry-After)Wait, then retry
500Internal Server ErrorSomething unexpected brokeRetry later with backoff
502 / 504Bad Gateway / Gateway TimeoutA server behind a proxy failed or was too slowRetry later with backoff
503Service UnavailableDown or overloaded for now (send Retry-After)Retry later

A good error body

Problem-details style error (example)
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://example.com/errors/invalid-quantity",
  "title": "Quantity is invalid",
  "status": 422,
  "detail": "quantity must be 1 or more, but was -5",
  "instance": "/orders",
  "request_id": "req-4f9a21",
  "errors": [{ "field": "quantity", "message": "must be at least 1" }]
}

The shape above follows the widely used problem details idea: a stable machine-readable type, a human title and detail, the status and a pointer to what failed. Add a request_id so support can find the log line. Any single consistent shape across your API beats a perfect shape used in only half of it.

VisualizerPick the right status code, and decide whether to retryGo through the 11 situations. Choose a code and read the feedback. Try 401 versus 403, and 422 versus 400. Then switch the response body between a vague message and a structured error.
Situation
Situation 1 of 11
A client POSTs a new order and it is saved.
POST /orders β†’ the order was created with id 77.
Which status code would you send?
Read the situation, then pick a status code. You will see if it fits, and whether the client should retry.
Answered
0/11
Score
0/22
2 = best, 1 = acceptable
What does the response body look like?
HTTP/1.1 201
Content-Type: application/problem+json

{
  "type": "https://example.com/errors/created",
  "title": "Created",
  "status": 201,
  "detail": "POST /orders β†’ the order was created with id 77.",
  "request_id": "req-4f9a21"
}

A structured body has a stable type, a human title and detail, the status, and a request id that support can look up in the logs. Never put a stack trace in it.

07How to Use It / Steps / Implementation

Designing errors well

  1. 1
    Choose the class first
    Is it the client’s fault (4xx), the server’s (5xx) or a success (2xx)? Get the class right before the exact code.
  2. 2
    Use a small, fixed set of codes
    Ten or so well-chosen codes beat forty obscure ones. Document the ones each endpoint can return.
  3. 3
    Never return 200 with an error inside
    Monitors, proxies, caches and retry logic all trust the status code. A hidden failure breaks all of them.
  4. 4
    Use one error format everywhere
    Same fields on every endpoint: type, title, status, detail, request id. Add field-level errors for validation.
  5. 5
    Say whether it is retryable
    Send Retry-After on 429 and 503. Treat 4xx (except 408, 409 and 429) as not retryable.
  6. 6
    Hide internals, keep a correlation id
    Log the stack trace on the server and return only a request id. That id links the caller to the log.
  7. 7
    Test the failures
    Write tests for bad input, missing login, no permission, not found and server failure, not only the happy path.
πŸ’‘Pair retries with idempotency
A client that retries a 503 on a payment must not charge twice. Pair retryable errors with idempotency keys, so a repeated request is safe.
⚠️404 versus 403 for secrets
Returning 403 for "exists, but not yours" tells an attacker that the id is real. For sensitive resources, many APIs return 404 in both cases.

08Key Terms to Know

TermMeaning in easy words
Status codeA three-digit number at the start of an HTTP response that says how the request went
Status classThe first digit of the code: 2xx, 3xx, 4xx or 5xx
Client error (4xx)The request itself was wrong
Server error (5xx)The server failed to handle a good request
Retry-AfterA header that tells the client how long to wait before trying again
Problem detailsA standard-style JSON shape for errors: type, title, status, detail
Request id / correlation idA unique id on a request, repeated in logs and error bodies
Validation errorA failure because input values break the rules
Retryable errorA failure that may succeed if the same request is sent again later
Fail fastReturn an error right away instead of letting the caller wait
Error budgetHow many failures you accept, used to decide if you are reliable enough

09Pros, Cons and Trade-offs

βœ… Pros
  • Clients know exactly what to do next
  • Retry logic and monitors work on shared rules
  • Faster debugging with request ids
  • No leaked internals
  • Consistent across the whole API
⚠️ Cons
  • Mapping every case takes thought
  • Teams disagree on borderline codes (400 or 422?)
  • A rich error body needs a common library
  • Too much detail in errors can leak data
  • Changing a code later can break clients

Trade-offs

ChoiceWe gainWe lose
Precise codes (409, 422)Clients can react exactlyMore to learn and to document
Few coarse codes (400, 500)Simple for everyoneClients cannot tell cases apart
Detailed error messagesEasy to debugRisk of leaking internals or hints to attackers
Terse messages + request idSafe and traceableSupport needs log access
404 for hidden resourcesDoes not reveal that it existsSlightly harder to debug
Retry-After on 429 / 503Clients back off politelyYou must compute a sensible value

10Common Problems and Mistakes

Common mistakes

  1. 200 OK with an error in the body. Caches, monitors and clients treat it as success.
  2. 500 for everything. If a bad input returns 500, alerts fire and clients retry something that can never work.
  3. Leaking stack traces and SQL. They help attackers and confuse users.
  4. 401 and 403 swapped. The client then logs in again when it needed permission, or the reverse.
  5. Retrying every error. Retrying 400 or 404 just repeats the failure and wastes load.
  6. A different error shape per endpoint. Clients need a special case for each.
  7. No request id. A user says "it failed at 3pm" and nobody can find the log line.

Things to watch

🌩️Retry storms
Many clients retrying a 503 at once can keep a service down. Use backoff with jitter.
🎭Gateway codes
A 502 or 504 may come from a proxy, not your code. Check where it was produced.
πŸ”Information leaks
Different messages for β€œno such user” and β€œwrong password” let attackers probe accounts.
πŸ“‰Hidden errors
If errors are wrapped as 200, your error rate looks fine while users suffer.

11Real-World Examples

🚦Rate limiters
They answer 429 with a Retry-After header so clients can wait the right amount.
☁️Cloud APIs
Many return a typed error code and a request id in every failure body.
πŸ’³Payment APIs
They separate card errors (a 4xx the user can fix) from server errors that are safe to retry.
βš–οΈLoad balancers
A burst of 5xx from one server makes the balancer take it out of rotation.
πŸ§ͺClient libraries
SDKs retry 5xx and 429 automatically with backoff, and surface 4xx immediately.
πŸ•΅οΈSecurity teams
They review errors to make sure nothing sensitive leaks through messages.
πŸ“Note
Which code to use in a borderline case (400 or 422, 403 or 404) differs from team to team. Choose a rule, write it down and apply it everywhere.
Mini case: a safe retry
πŸ“±POST /payidempotency key K1
→↓503 + Retry-After
⏳Wait, back off
→↓same key K1
βœ…200 OKcharged once
Server failure Wait Safe retry
The client retries a 503 with backoff, and an idempotency key keeps it from charging twice.

12Related Topics to Read Next

What is an API?β†’

The basics of requests and responses.

HTTP / HTTPS→

Where status codes and headers come from.

Idempotency→

Makes retrying a failed request safe.

Retries with Backoff→

How to retry without making an outage worse.

Rate Limiting→

The reason for 429 and Retry-After.

Input Validation→

The source of most 400 and 422 errors.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Classes: 2xx worked, 3xx elsewhere, 4xx client wrong, 5xx server wrong.
  • βœ”Common: 200, 201, 204, 400, 401, 403, 404, 409, 422, 429, 500, 503.
  • βœ”401: not logged in. 403: logged in but not allowed.
  • βœ”Retry: 5xx and 429 with backoff. Not 400, 403 or 404.
  • βœ”Body: one shape everywhere: type, title, status, detail, request id.
  • βœ”Never: 200 with an error inside, or a stack trace in the response.
  • βœ”Pair with: idempotency keys and Retry-After.
  • βœ”One line: β€œPick the status code for the client's next move, and give support a request id.”
← Previous
API Versioning
Next β†’
OpenAPI / Swagger