Choose among all 17 gRPC status codes, return a status error in Go, and inspect a real RPC failure on the client.
· 4 min read
Last updated on

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?

CodeWhen it fitsExample
0 · OKThe RPC succeeded. Return a nil error.The order was fetched.
1 · CanceledThe operation was cancelled.A caller abandoned a request.
2 · UnknownThe cause cannot be classified.A Go handler returned an ordinary error with no gRPC status.
3 · InvalidArgumentAn input is invalid regardless of system state.An order ID has an invalid format.
4 · DeadlineExceededThe deadline expired before the caller received a successful result.A write timed out and the caller needs to check whether it committed.
5 · NotFoundThe requested entity could not be found.A valid order ID has no matching record.
6 · AlreadyExistsThe entity being created already exists.Creating a second record with a reserved name failed.
7 · PermissionDeniedThe caller lacks permission for the operation.A reader tried to cancel an order.
8 · ResourceExhaustedA quota or capacity has been exhausted.The caller reached its storage quota.
9 · FailedPreconditionThe system must change state before this operation can succeed.An order has already shipped.
10 · AbortedA concurrency conflict requires restarting a higher-level operation.A compare-and-swap failed during a read–modify–write sequence.
11 · OutOfRangeThe requested position is outside the current range.A reader sought past the end of a collection.
12 · UnimplementedThe operation is unsupported or disabled.An older server lacks a newly added method.
13 · InternalA service invariant failed.Stored state violates an internal consistency check.
14 · UnavailableThe service is temporarily unable to serve the request.A dependency is restarting.
15 · DataLossData was irrecoverably lost or corrupted.The service detected unrecoverable record corruption.
16 · UnauthenticatedThe 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.