Which gRPC status code should a Go service return?
Choose the code that tells the caller what it can do next. A malformed order ID calls for InvalidArgument. A well-formed ID with no matching order calls for NotFound. If the order exists but has already shipped, cancelling it may fail with FailedPrecondition. Those three failures can come from the same RPC and require three different responses.
In Go, return status.Error(codes.InvalidArgument, "order ID is required") from the handler. On the client, branch on status.Code(err). Keep the message readable for a person. A client that parses the message will break when someone edits the wording. Go status package
Which code fits the failure?
| Code | When it fits | Example |
|---|---|---|
| 0 · OK | The RPC succeeded. Return a nil error. | The order was fetched. |
| 1 · Canceled | The operation was cancelled. | A caller abandoned a request. |
| 2 · Unknown | The cause cannot be classified. | A Go handler returned an ordinary error with no gRPC status. |
| 3 · InvalidArgument | An input is invalid regardless of system state. | An order ID has an invalid format. |
| 4 · DeadlineExceeded | The deadline expired before the caller received a successful result. | A write timed out and the caller needs to check whether it committed. |
| 5 · NotFound | The requested entity could not be found. | A valid order ID has no matching record. |
| 6 · AlreadyExists | The entity being created already exists. | Creating a second record with a reserved name failed. |
| 7 · PermissionDenied | The caller lacks permission for the operation. | A reader tried to cancel an order. |
| 8 · ResourceExhausted | A quota or capacity has been exhausted. | The caller reached its storage quota. |
| 9 · FailedPrecondition | The system must change state before this operation can succeed. | An order has already shipped. |
| 10 · Aborted | A concurrency conflict requires restarting a higher-level operation. | A compare-and-swap failed during a read–modify–write sequence. |
| 11 · OutOfRange | The requested position is outside the current range. | A reader sought past the end of a collection. |
| 12 · Unimplemented | The operation is unsupported or disabled. | An older server lacks a newly added method. |
| 13 · Internal | A service invariant failed. | Stored state violates an internal consistency check. |
| 14 · Unavailable | The service is temporarily unable to serve the request. | A dependency is restarting. |
| 15 · DataLoss | Data was irrecoverably lost or corrupted. | The service detected unrecoverable record corruption. |
| 16 · Unauthenticated | The request lacks valid credentials. | The caller presented an expired token. |
The gRPC specification distinguishes these codes by meaning. Several map to different recovery actions even when an HTTP API might use the same status for them. Official gRPC status code definitions
How does the client see the code?
This example runs a server and client on loopback using gRPC’s standard health service. It checks a service name that was never registered. You can run it without generating protobuf files.
package main
import (
"context"
"fmt"
"log"
"net"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health"
pb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
)
func main() {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
server := grpc.NewServer()
pb.RegisterHealthServer(server, health.NewServer())
go server.Serve(listener)
defer server.Stop()
conn, err := grpc.NewClient(listener.Addr().String(),
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client := pb.NewHealthClient(conn)
_, err = client.Check(ctx, &pb.HealthCheckRequest{Service: "orders"})
fmt.Println(status.Code(err))
}
Save it in an empty directory as main.go, then run:
go mod init example.com/grpc-status
go get google.golang.org/grpc@v1.80.0
go run .
It prints NotFound. Change Service: "orders" to Service: "" to check overall server health. The default gRPC-Go health server starts with that entry registered, so the same client prints OK. The insecure transport in this example is for the local loopback connection. gRPC-Go health server
When should the client retry?
Unavailable can justify a bounded retry for an operation that is safe to repeat. Aborted can mean the caller needs to redo an entire transaction. FailedPrecondition calls for a state change first. A timed-out write can already have committed. Check the result or use an idempotency key before sending it again.
See handling gRPC errors on the caller for a Go example. Chris Shepherd’s production gRPC course curriculum covers building and testing services end to end.