What are gRPC rich error details and why do string messages fail as a contract?
A gRPC call that fails always returns a status code and a message string. Rich error details extend that with a structured payload: a google.rpc.Status message containing an integer code, a developer-facing message, and a repeated details field of google.protobuf.Any. Each entry in details is a typed protobuf message, such as a field violation, a retry delay, or a machine-readable reason. The client can unpack it by type instead of interpreting text.
This guide is for backend and platform engineers who own APIs that other teams or external clients consume. For these APIs, every error is part of the contract whether you planned it or not.
The message string is a poor contract for three reasons:
- Prose changes. Someone rewords "user not found" to "no such account" during a refactor, or the message gets localized. Any client that matched on the old text breaks silently, and no compiler or schema check catches it.
- Clients differ. Each language's client library exposes the message through its own error type. Regex logic written in one language then has to be rewritten, and kept in sync, in every other.
- Intent is ambiguous. Free text gives no stable way to tell "retry in 30 seconds" from "field
emailis malformed, fix your input." Callers guess, and they either retry requests that can never succeed or give up on ones that would.
Typed details remove those guesses. Clients branch on fields rather than wording, so their logic keeps working when messages change. Callers also learn exactly what to fix, which cuts the support threads that begin with "what does this error mean?"
How does google.rpc.Status travel over the wire?
The status travels in HTTP/2 trailers, the headers sent after the last message on a stream. Two text trailers carry the basics. grpc-status holds the numeric code and grpc-message holds the human-readable message, percent-encoded. The rich model rides alongside them. The server serializes the entire google.rpc.Status (code, message, and a repeated details field) into the binary trailer grpc-status-details-bin. The -bin suffix tells the transport to base64-encode the bytes. Each entry in details is a google.protobuf.Any, which pairs a type URL with serialized bytes. A client can therefore check which detail types are present and unpack only the ones it understands.
SERVER PROXY / GATEWAY CLIENT
status = {code, msg, may pass, strip, or code-only: reads
details: [Any, Any]} re-encode the -bin trailer grpc-status + grpc-message
| | rich-aware: also decodes
v v grpc-status-details-bin
trailers:
grpc-status: 3 --------------------------------------> code
grpc-message: bad%20input ----------------------------> message
grpc-status-details-bin: <base64 Status> ---?---------> details (if it survived)
This layout degrades gracefully. A client that knows nothing about rich details still gets a correct code and message. The binary trailer duplicates the code and message, so keep them identical to the plain trailers to avoid ambiguous reads.
Two costs follow from living in metadata. First, details count against header and trailer size limits on servers, clients, and every proxy in between. A large BadRequest with hundreds of field violations can push the trailers past a limit, and the call then fails with an unrelated error. Second, any hop that translates the protocol can drop an unfamiliar binary trailer or rewrite it. Examples include gRPC-Web bridges, JSON transcoders, and HTTP/1.1 gateways. Test the full path to the client, not only the server in isolation.
+------------------------------------------+
| SERVER: builds google.rpc.Status |
| { code, message, details: [Any, Any] } |
+--------------------+---------------------+
| HTTP/2 trailers, sent after the last message
v
+------------------------------------------------------+
| grpc-status: 3 text: numeric code |
| grpc-message: bad%20input text: pct-encoded msg |
| grpc-status-details-bin: ... binary: base64 Status |
+--------------------+---------------------------------+
| all three count toward header/trailer size limits
v
+------------------------------------------------------+
| PROXY / GATEWAY (optional) |
| text trailers: carry code + message |
| -bin trailer: may be passed, stripped, re-encoded, |
| or dropped if it exceeds size limits |
+--------+-----------------------------+---------------+
| |
v v
+---------------------+ +------------------------------+
| CODE-ONLY CLIENT | | RICH-AWARE CLIENT |
| reads grpc-status + | | decodes -bin into Status, |
| grpc-message only | | unpacks Any types it knows; |
+---------------------+ | if -bin is lost: code + msg |
+------------------------------+
The code and message travel in plain text trailers that every client reads, while the full google.rpc.Status with its Any-packed details rides in the base64 grpc-status-details-bin trailer, which size limits or intermediaries can drop or re-encode.
Which gRPC status code should you return? Decide by what the caller does next
The status code is what generic machinery acts on: retry policies, client libraries, load balancers, dashboards and alerting. Most of that machinery never parses details. Choose the code by asking what the caller should do next. Details then refine that answer; they cannot correct it. A retryable INVALID_ARGUMENT with a perfect BadRequest attached will still be treated as non-retryable.
| What the caller should do next | Code | Example |
|---|---|---|
| Fix the input; retrying unchanged is pointless | INVALID_ARGUMENT |
Malformed email, negative page size |
| Fix the system state, then retry | FAILED_PRECONDITION |
Deleting a non-empty bucket |
| Adjust the position or range | OUT_OF_RANGE |
Reading past end of file |
| Retry the same call with backoff | UNAVAILABLE |
Server overloaded or restarting |
| Retry the whole read-modify-write sequence | ABORTED |
Optimistic-lock or transaction conflict |
| Wait, reduce load or raise quota | RESOURCE_EXHAUSTED |
Rate limit hit |
| Give up and report | INTERNAL / UNKNOWN |
Broken invariant / unclassified failure |
INVALID_ARGUMENT means the request is wrong whatever the system state. OUT_OF_RANGE means the request could become valid as state changes, such as a file growing. Iterators can treat it as a clean end-of-data signal.
Use NOT_FOUND instead of PERMISSION_DENIED when the caller should not learn that the resource exists. Apply this consistently, or response differences will leak existence.
Use INTERNAL when your own invariant broke. Use UNKNOWN only when you cannot classify the failure, for example an error mapped from a dependency that has no equivalent code.
What standard error detail types exist and when should each be used?
The standard detail messages live in google/rpc/error_details.proto. Clients branch on the message type, so choose it by what the caller should do next.
| Detail type | Typical status code | What the client does with it |
|---|---|---|
ErrorInfo (reason, domain, metadata) |
Any | Branches on reason + domain; reads metadata for parameters |
BadRequest (field_violations) |
INVALID_ARGUMENT |
Highlights the offending form fields |
PreconditionFailure |
FAILED_PRECONDITION |
Tells the user which state to fix first |
QuotaFailure |
RESOURCE_EXHAUSTED |
Identifies which quota subject ran out |
RetryInfo (retry_delay) |
UNAVAILABLE, RESOURCE_EXHAUSTED, ABORTED |
Waits at least retry_delay before retrying |
ResourceInfo |
NOT_FOUND, ALREADY_EXISTS, PERMISSION_DENIED |
Names the resource involved |
RequestInfo (request_id) |
Any | Logs it and shows it in support tickets |
Help, LocalizedMessage |
Any | Shows links or text to a human |
DebugInfo |
INTERNAL |
Internal callers only |
ErrorInfo is the one to attach almost every time. Its reason is the stable identifier your contract depends on. The other types add context to it.
Avoid code/detail mismatches. RetryInfo on INVALID_ARGUMENT tells a well-behaved client to resend a request that can never succeed. BadRequest on INTERNAL blames the caller for your own bug. Clients that trust the details will act on the contradiction.
DebugInfo leaks internals. Stack entries reveal file paths, library choices and sometimes data. Strip it at your public edge. It belongs only between services you operate.
LocalizedMessage vs client-side mapping. LocalizedMessage is worth it when the server owns the wording, for example for thin or third-party clients or for many locales that change often. If you control the clients, mapping reason to text on the client keeps copy changes out of server deploys. It also keeps the UI consistent across platforms.
How do you implement rich error details on the server and client?
On the server, the steps are the same in every language. Build a google.rpc.Status with a code and a developer-facing message. Pack each detail message into google.protobuf.Any, which records its type URL so clients can decode it later. Then hand the result to your language's status helper. The helper serializes the Status into the grpc-status-details-bin trailer alongside the plain code and message, so clients that ignore details still get a valid status.
In Go, the status and errdetails packages cover this. Call status.New(codes.FailedPrecondition, "..."), then WithDetails(&errdetails.ErrorInfo{...}), and return st.Err() from the handler. WithDetails returns a new status and an error. The error is non-nil if a detail fails to marshal. Handle that case by returning the bare status, so you don't lose the code.
On the client, call status.FromError(err) and range over st.Details() with a type switch:
*errdetails.ErrorInfo: branch onReasonandDomain, never on the message text.*errdetails.RetryInfo: treatRetryDelayas a hint, not a command. Cap it, add jitter, and count the attempt against your retry budget. This stops a misbehaving server from stalling callers or causing synchronized retries.- Unknown types: Go returns these as
errorvalues inside the slice. Skip them.
If no details are present, or none are recognized, fall back to handling by code alone. That path must always be correct.
Other languages expose different helper APIs and ship the error_details protos as separate dependencies. Check your stack instead of assuming the Go shapes carry over.
// Go. Imports: codes, status, errdetails (genproto), durationpb, math/rand, time.
// Server: build the status, attach typed details, return st.Err().
func quotaError() error {
st := status.New(codes.ResourceExhausted, "project quota exceeded")
ds, err := st.WithDetails(
&errdetails.ErrorInfo{Reason: "QUOTA_EXCEEDED", Domain: "billing.example.com",
Metadata: map[string]string{"project": "demo-project"}},
&errdetails.RetryInfo{RetryDelay: durationpb.New(2 * time.Second)},
)
if err != nil {
return st.Err() // a detail failed to marshal: keep the code anyway
}
return ds.Err()
}
// Client: decide on Reason/Domain, treat RetryInfo as a capped, jittered hint.
// The caller still charges every retry against its retry budget.
func classify(err error) (retry bool, wait time.Duration) {
st, ok := status.FromError(err)
if !ok {
return false, 0
}
retry = st.Code() == codes.Unavailable // code-only fallback, always valid
for _, d := range st.Details() {
switch info := d.(type) {
case *errdetails.ErrorInfo:
if info.GetDomain() == "billing.example.com" && info.GetReason() == "QUOTA_EXCEEDED" {
retry = true
}
case *errdetails.RetryInfo:
wait = min(info.GetRetryDelay().AsDuration(), 10*time.Second) // cap
wait += time.Duration(rand.Int63n(int64(wait/2) + 1)) // jitter
default:
// Unknown detail type (returned as an error value): ignore it.
}
}
return retry, wait
}
Go server code that attaches ErrorInfo and RetryInfo with status.New, WithDetails and Err, and client code that uses status.FromError and a type switch over Details() to branch on Reason and Domain, cap and jitter the retry hint, and fall back to the status code.
How should you design reason codes and handle errors across service boundaries?
Treat reasons as API surface
ErrorInfo.reason should be an UPPER_SNAKE_CASE constant such as INSUFFICIENT_BALANCE or ORDER_ALREADY_SHIPPED, documented next to the RPCs that return it. Use one domain per service or product, for example orders.example.com, so two teams can both define QUOTA_EXCEEDED without colliding. Put parameters such as the offending resource ID or the limit that was hit in metadata, never in the reason itself. Clients branch on reasons, so renaming or removing one is a breaking change, and you should version it like a field removal. Without review, reasons drift into near-duplicates and one-off values, and callers fall back to matching text again.
Decide what crosses each boundary
When a downstream call fails, choose deliberately what to do with its error. You can preserve it when the caller can act on it, translate it into your own domain, or strip it to a bare code. Forwarding blindly leaks your internal topology and couples your clients to services they never call. At trust boundaries, remove DebugInfo and internal resource names.
Details travel in the grpc-status-details-bin binary trailer. HTTP/JSON transcoding, gateways, proxies, and gRPC-Web can drop, rewrite, or re-encode that trailer. Test the behavior of your own stack rather than assuming details arrive intact.
Operate on structure
Log and emit metrics on code plus reason, not message text. Put a request ID in RequestInfo so support can correlate reports with server logs. Add contract tests for key failure paths that assert the code, the reason, and the detail types the client receives.
from google.rpc import code_pb2, error_details_pb2, status_pb2
from grpc_status import rpc_status
ORDERS_DOMAIN = "orders.example.com"
# Explicit map from downstream (domain, reason) to our documented reasons.
REASON_MAP = {("payments.internal", "FUNDS_UNAVAILABLE"): "INSUFFICIENT_BALANCE"}
def abort_from_payment_error(err, context, order_id, log):
"""Translate a downstream payments RpcError into an orders-domain error."""
downstream = rpc_status.from_call(err) # None if no grpc-status-details-bin
reason, request_id = "PAYMENT_FAILED", ""
for detail in (downstream.details if downstream else []):
if detail.Is(error_details_pb2.ErrorInfo.DESCRIPTOR):
info = error_details_pb2.ErrorInfo()
detail.Unpack(info)
reason = REASON_MAP.get((info.domain, info.reason), reason)
elif detail.Is(error_details_pb2.RequestInfo.DESCRIPTOR):
req = error_details_pb2.RequestInfo()
detail.Unpack(req)
request_id = req.request_id
# Everything else (DebugInfo, internal ResourceInfo) is dropped here.
status = status_pb2.Status(
code=code_pb2.FAILED_PRECONDITION,
message="Payment could not be completed for this order.",
)
status.details.add().Pack(error_details_pb2.ErrorInfo(
reason=reason, domain=ORDERS_DOMAIN,
metadata={"order_id": order_id}, # parameters live in metadata
))
if request_id:
status.details.add().Pack(error_details_pb2.RequestInfo(request_id=request_id))
# Log structured fields, not message text, so metrics can group by them.
log.warning("rpc_error", extra={"code": "FAILED_PRECONDITION",
"reason": reason, "domain": ORDERS_DOMAIN, "request_id": request_id})
context.abort_with_status(rpc_status.to_status(status))
A Python gRPC server handler that translates a downstream payments error into its own documented orders-domain reason. It keeps the RequestInfo, drops DebugInfo and other internal details, and logs the code and reason instead of the message text.
When should you avoid rich error details, what are the alternatives, and what do they cost?
Rich details pay off when many clients you don't control need to branch on failures: public APIs, multi-team platforms, SDKs. For a small internal service with one or two callers, the status code plus a log line is often enough. Skip rich details if a proxy, gateway, or browser bridge in your path drops or rewrites the grpc-status-details-bin trailer. Clients would then see details in testing but not in production.
| Approach | Machine-readable | Survives intermediaries | Main cost |
|---|---|---|---|
| Code only | Coarse | Yes | Clients can't distinguish causes |
| Custom trailing metadata keys | Ad hoc | Same risk as details | Untyped, no shared schema |
Error fields in response (oneof result) |
Yes, typed | Yes, it's the payload | Must be in each RPC; status may report OK on failure |
| Message-string conventions | Fragile | Yes | Rewording breaks clients |
google.rpc.Status details |
Yes, typed | Usually | Dependencies and governance |
Rich details have real costs:
- Shared helpers so teams don't hand-build
Statusprotos. - Review guidelines or lint rules.
- An owner for the reason vocabulary.
- Extra proto dependencies.
- Discipline to stay under metadata size limits.
- Retry-amplification risk. If every layer honours
RetryInfo, attempts multiply: three layers making three attempts each can send 27 requests to the bottom service.
Weigh these against the time saved debugging, answering support tickets, and fixing clients that broke on reworded messages.
Migrate incrementally:
- Keep current codes and messages.
- Add
ErrorInfoto the errors you already return. - Move clients to match on
reasoninstead of message strings. - Add type-specific details such as
BadRequestorQuotaFailureonly where a client actually needs them.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to grpc rich error details, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.