Why HTTP Status Codes Are Not Enough for Microservice Errors
HTTP status codes are essential to REST API design.
They tell us whether a request succeeded, failed because of a client problem, or encountered a server-side failure.
But when applications evolve into distributed systems, HTTP status codes become only part of the story.
Consider these questions:
- What exactly caused the failure?
- Which service owns the error?
- Can the caller safely retry?
- How should an unknown downstream error be handled?
- How can operators trace the failure across services?
A 409 Conflict or 503 Service Unavailable cannot answer all of them.
While building NERV Exception, an open-source exception-handling library for Java and Spring Boot, I explored how a consistent error contract can address these limitations without tightly coupling independently deployed microservices.
Let's examine the problem from an API consumer's perspective.
1. The Same HTTP Status Can Mean Different Things
Imagine an e-commerce application with three services:
API Gateway
|
+-- Order Service
|
+-- Payment Service
|
+-- Inventory Service
Each service encounters a different failure.
Order Service
HTTP/1.1 409 Conflict
The order has already been processed.
Payment Service
HTTP/1.1 409 Conflict
The payment has already been captured.
Inventory Service
HTTP/1.1 409 Conflict
Inventory is reserved by another transaction.
All three return 409 Conflict.
But should clients handle them identically?
Probably not.
An already-processed order may require no further action.
An already-captured payment may require reconciliation.
An inventory reservation conflict may require refreshing availability.
If the response contains only:
{
"status": 409,
"message": "Conflict"
}
the consumer cannot reliably distinguish these conditions.
Add stable application error codes
Instead, return:
{
"code": "ORDER_ALREADY_PROCESSED",
"message": "The order has already been processed",
"status": 409
}
For the payment failure:
{
"code": "PAYMENT_ALREADY_CAPTURED",
"message": "The payment has already been captured",
"status": 409
}
And for inventory:
{
"code": "INVENTORY_RESERVATION_CONFLICT",
"message": "Inventory is reserved by another transaction",
"status": 409
}
Now clients can identify each failure without parsing message text.
HTTP status codes classify failures. Application error codes identify them.
Both are useful, but they solve different problems.
2. Why Exception Messages Are Poor API Contracts
A common mistake is to use exception messages as machine-readable identifiers.
For example:
if ("Order has already been processed".equals(errorMessage)) {
// Handle already-processed order
}
This is fragile.
Suppose someone changes the message:
Old:
Order has already been processed
New:
This order has already been completed
The underlying business condition hasn't changed.
But the consumer may stop recognizing it.
Messages can change because of localization, improved wording, security requirements, or ordinary refactoring.
A stable error code avoids that problem:
if ("ORDER_ALREADY_PROCESSED".equals(errorCode)) {
// Handle already-processed order
}
The message remains useful for humans.
The code remains stable for software.
This introduces an important API design principle:
Application error codes should be treated as published contracts.
Renaming a code can break consumers even when the HTTP status and JSON structure remain unchanged.
3. Designing a More Expressive Error Response
A useful error contract should communicate more than an HTTP status and message.
For example:
{
"code": "ORDER_ALREADY_PROCESSED",
"message": "The order has already been processed",
"status": 409,
"retryable": false,
"category": "BUSINESS",
"traceId": "abc123",
"spanId": "def456",
"path": "/api/orders/123/process",
"timestamp": "2026-11-20T08:30:00Z",
"origin": {
"service": "order-service",
"instance": "order-service-1",
"version": "1.0.0",
"environment": "production"
},
"details": {}
}
This illustrates the response structure supported by NERV Exception's NervErrorResponse.
The business code, category, and example values are illustrative. Diagnostic fields depend on the application's configuration and available context.
Each field serves a purpose.
| Field | Purpose |
|---|---|
code |
Stable application error identifier |
message |
Human-readable explanation |
status |
HTTP status |
category |
General failure classification |
retryable |
Recovery guidance |
traceId |
Distributed tracing correlation |
spanId |
Span correlation |
path |
Request path |
timestamp |
Response timestamp |
origin |
Service-origin information |
details |
Structured error-specific information |
The goal isn't to expose as much information as possible.
It's to provide enough information for consumers to handle failures predictably while keeping sensitive internal details protected.
4. Modeling Application Errors in Spring Boot
Let's build a simplified example.
First, define an error response:
public record ApiError(
String code,
String message,
int status,
String category,
boolean retryable
) {}
This is an educational example, not the full NERV Exception API.
Next, define an application exception:
public class OrderAlreadyProcessedException
extends RuntimeException {
public OrderAlreadyProcessedException() {
super("The order has already been processed");
}
}
Then handle it using Spring MVC:
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderAlreadyProcessedException.class)
public ResponseEntity<ApiError> handle(
OrderAlreadyProcessedException exception
) {
ApiError error = new ApiError(
"ORDER_ALREADY_PROCESSED",
"The order has already been processed",
409,
"BUSINESS",
false
);
return ResponseEntity
.status(HttpStatus.CONFLICT)
.body(error);
}
}
This produces a consistent response for that particular exception.
But there's an architectural problem.
What happens when you have 20 Spring Boot services?
If each application independently implements its own response DTO, exception handler, and error classification, inconsistencies eventually emerge.
One service includes an error code.
Another returns only a message.
Another exposes internal exception causes.
Another uses a different validation response structure.
This is where reusable exception-handling infrastructure becomes valuable.
A shared library can standardize the response contract and conversion mechanism while allowing applications to own their business errors.
5. HTTP Status, Category, and Retryability Are Different Concerns
A common shortcut is to derive retryability directly from HTTP status.
For example:
boolean retryable = status >= 500;
That is not a reliable rule.
A 500 response doesn't guarantee that repeating an operation is safe.
Likewise, a 409 may represent a permanent business conflict or a concurrency condition that could be resolved through a controlled retry.
Consider these illustrative examples:
| Failure | HTTP status | Retryable |
|---|---|---|
| Invalid request | 400 | No |
| Resource not found | 404 | No |
| Already-processed order | 409 | No |
| Rate limit exceeded | 429 | Policy-dependent |
| Dependency unavailable | 503 | Potentially |
The key distinction is that retryability describes a possible recovery strategy, not a guarantee of safe execution.
Applications still need to consider idempotency, unknown outcomes, retry limits, and backoff.
NERV Exception represents categories as strings, allowing applications to define classifications appropriate to their domains.
However, teams should establish conventions so that categories remain meaningful across services.
6. What Happens When One Microservice Returns an Unknown Error?
Consider a typical service-to-service interaction:
API Gateway
|
v
Order Service
|
v
Payment Service
Payment Service returns:
{
"code": "PAYMENT_ALREADY_PROCESSED",
"message": "Payment has already been processed",
"status": 409,
"category": "BUSINESS",
"retryable": false
}
But Order Service doesn't recognize PAYMENT_ALREADY_PROCESSED.
What should happen?
There are three common approaches.
Option A: Replace the error
Order Service converts the response into a generic integration failure.
{
"code": "DOWNSTREAM_SERVICE_ERROR",
"message": "Unable to process order",
"status": 500
}
This may be appropriate when the downstream failure should be hidden behind Order Service's public API.
But it can discard useful information.
Option B: Share every error code
Every microservice imports a common library containing all business error definitions.
This makes errors recognizable but introduces coupling.
When Payment Service adds a new code, other services may need dependency updates despite having no direct ownership of that business rule.
Option C: Preserve unknown codes
Services agree on the error response structure without requiring every application to register every downstream business code.
This allows independently deployed services to evolve more freely.
NERV Exception's Feign integration supports this approach using RemoteNervErrorCode.
For unknown downstream codes, it can preserve the remote code, message, response-body status, category, and retryability.
For codes registered locally, the local definition determines status, category, and retryability.
That distinction matters.
Registering a downstream error code locally can change how the receiving service interprets it.
A shared error contract improves interoperability, but it does not eliminate decisions about semantic ownership.
7. Error Propagation Is Not Always Transparent
Suppose Payment Service generates an error while handling:
POST /payments
Order Service receives that failure while handling:
POST /orders
Which request path should appear in the final error response?
The original downstream path?
Or the current request path?
Both describe useful but different contexts.
The same question applies to timestamps and tracing information.
In the reviewed NERV Exception implementation, the downstream exception retains supported remote information such as the message, origin, and details.
It does not retain the original downstream traceId, spanId, path, or timestamp for direct reuse.
When the receiving application generates a new HTTP response, those fields are populated from its current context.
This is why consistent error contracts and distributed tracing solve different problems.
An error contract identifies and classifies failures.
Distributed tracing helps reconstruct how those failures moved through the system.
Neither replaces the other.
8. Why HTTP 503 Doesn't Automatically Mean Retry
Consider a payment operation.
Order Service submits a payment request.
The payment provider processes it successfully.
But the response is lost because of a network interruption.
Order Service
|
| Submit payment
v
Payment Service
|
| Payment succeeds
v
Payment Provider
|
X Response lost
Order Service experiences a timeout.
Did the payment fail?
Or did it succeed without confirmation reaching the caller?
The caller doesn't know.
Retrying without idempotency protection could produce a duplicate payment.
Now consider this response:
{
"code": "PAYMENT_PROVIDER_UNAVAILABLE",
"message": "Payment provider is temporarily unavailable",
"status": 503,
"category": "DEPENDENCY",
"retryable": true
}
The response communicates that retrying may be appropriate.
But the application must still decide whether the operation is safe to repeat.
NERV Exception's Feign decoder can wrap a retryable downstream failure in Feign's RetryableException.
However, the library does not automatically configure a retry policy.
Actual retry behavior depends on the application's Feign configuration.
There is another important consideration: after retry exhaustion, a generic exception handler may map the wrapper to an internal server error unless the application handles it explicitly.
Therefore:
Retry classification, retry execution, and final error presentation are separate responsibilities.
9. Error Contracts Are Also Compatibility Contracts
Consider an application that returns:
{
"code": "PAYMENT_TIMEOUT",
"retryable": false
}
Later, the service changes its response to:
{
"code": "PAYMENT_TIMEOUT",
"retryable": true
}
The JSON schema hasn't changed.
The error code hasn't changed.
But the semantics have.
Consumers may begin retrying operations they previously treated as final.
Similarly, changing an error code from CUSTOMER_DISABLED to CUSTOMER_INACTIVE can break consumers that rely on the original identifier.
This is why error contract compatibility should consider:
- Error code stability
- HTTP status mappings
- Category semantics
- Retryability changes
- Unknown-code behavior
- Diagnostic information exposure
A structurally compatible response is not necessarily behaviorally compatible.
10. What Should API Consumers Depend On?
Different fields serve different purposes.
A consumer should use the appropriate information for the decision it needs to make.
| Consumer decision | Relevant information |
|---|---|
| Determine the HTTP outcome | HTTP status |
| Identify a specific business failure | Application error code |
| Display an explanation | Safe message |
| Classify the failure | Category |
| Evaluate potential recovery | Retryability and operation semantics |
| Investigate an incident | Tracing and origin information |
| Handle validation failures | Structured details |
The goal is not to replace HTTP status codes.
It's to supplement them with application-level meaning.
11. Where NERV Exception Fits
NERV Exception provides reusable infrastructure for consistent error handling in Java and Spring Boot applications.
Its modules include:
| Module | Responsibility |
|---|---|
nerv-exception-api |
Shared error contracts |
nerv-exception-core |
Core exception and error-code behavior |
nerv-exception-spring-web |
Spring Web exception handling |
nerv-exception-spring-feign |
OpenFeign error decoding |
nerv-exception-spring-boot-starter |
Spring Boot integration |
nerv-exception-jpa |
Persistence-related support |
nerv-exception-event |
Event-related support |
nerv-exception-spring-kafka |
Kafka-related support |
The library doesn't eliminate application-specific responsibilities.
Each service still needs to own its business errors, define appropriate recovery policies, and determine what information is safe to expose.
The objective is to standardize common infrastructure without centralizing every business decision.
Final Thoughts
HTTP status codes remain essential to REST API design.
They provide a standardized way to communicate the outcome of an HTTP interaction.
But microservice architectures require more information.
Consumers need to distinguish business failures, interpret downstream errors, evaluate potential recovery, and correlate failures across service boundaries.
Stable application error codes, meaningful classifications, retryability guidance, and diagnostic context help address these requirements.
HTTP status codes tell us how a request ended. A well-designed error contract tells us what the failure means.
Explore NERV Exception
NERV Exception is part of the open-source NERV ecosystem of reusable Java and Spring Boot libraries.
Explore the projects on GitHub:
https://github.com/czetsuyatech
For the canonical article and the rest of the NERV Exception series, visit:
Top comments (0)