Errors, Deadlines and Cancellation
What the client sees when a call does not work.
Every failed call arrives as a code. The runtime produces two of them for you.
All seventeen codes
Enumerated from the library, not from memory:
package main
import (
"fmt"
"google.golang.org/grpc/codes"
)
func main() {
for i := 0; i <= 17; i++ {
fmt.Printf("%2d %s\n", i, codes.Code(i))
}
}Seventeen, 0 to 16. The eighteenth has no name.
Returning one
status.Error takes a code and a message:
syntax = "proto3";
package dl;
option go_package = "xz/grpc/dlpb";
service Slow {
rpc Work(WorkRequest) returns (WorkReply);
rpc Peek(WorkRequest) returns (WorkReply);
}
message WorkRequest { int32 ms = 1; }
message WorkReply { string result = 1; }package main
import (
"context"
"fmt"
"log"
"net"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
"xz/grpc/dlpb"
)
type server struct{ dlpb.UnimplementedSlowServer }
func (s *server) Peek(ctx context.Context, req *dlpb.WorkRequest) (*dlpb.WorkReply, error) {
d, ok := ctx.Deadline()
if !ok {
return &dlpb.WorkReply{Result: "no deadline"}, nil
}
left := time.Until(d).Round(100 * time.Millisecond)
return &dlpb.WorkReply{Result: fmt.Sprintf("deadline in %v", left)}, nil
}
func (s *server) Work(ctx context.Context, req *dlpb.WorkRequest) (*dlpb.WorkReply, error) {
select {
case <-time.After(time.Duration(req.GetMs()) * time.Millisecond):
return &dlpb.WorkReply{Result: "finished"}, nil
case <-ctx.Done():
log.Println("handler stopped:", ctx.Err())
return nil, status.FromContextError(ctx.Err()).Err()
}
}
func main() {
lis, _ := net.Listen("tcp", ":50054")
s := grpc.NewServer()
dlpb.RegisterSlowServer(s, &server{})
log.Fatal(s.Serve(lis))
}status.Errorf is the formatting version.
Reading one
status.FromError unpacks it, and the second return says whether it was a status at all:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/dlpb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50054",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := dlpb.NewSlowClient(conn)
r, err := c.Work(context.Background(), &dlpb.WorkRequest{Ms: 1})
fmt.Println(r.GetResult())
st, ok := status.FromError(err)
fmt.Println("ok", ok, "code", st.Code())
}A nil error unpacks to OK, so this works on the success path.
A plain Go error
The code is the part a caller can act on, and errors.New has none:
package main
import (
"errors"
"fmt"
"google.golang.org/grpc/status"
)
func main() {
st, _ := status.FromError(errors.New("nope"))
fmt.Println(st.Code(), st.Message())
}Which code for which failure
The seven that cover almost everything:
| Failure | Code |
|---|---|
| Bad input from the caller | InvalidArgument |
| Thing does not exist | NotFound |
| Thing already exists | AlreadyExists |
| Not logged in | Unauthenticated |
| Logged in, not allowed | PermissionDenied |
| Rate limited or out of quota | ResourceExhausted |
| Your bug | Internal |
FailedPrecondition means a retry will not help until something changes; Aborted means retry the
whole transaction.
Not HTTP status codes
Some agree, some have no equivalent:
| gRPC | HTTP |
|---|---|
NotFound |
404 |
PermissionDenied |
403 |
Unauthenticated |
401 |
ResourceExhausted |
429 |
Internal |
500 |
Unavailable |
503 |
FailedPrecondition |
nothing useful |
Unavailable is the one that matters operationally: the call never reached a handler.
Setting a deadline
A deadline is a context, set by the caller:
package main
import (
"context"
"fmt"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/dlpb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50054",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := dlpb.NewSlowClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
r, _ := c.Peek(ctx, &dlpb.WorkRequest{})
fmt.Println(r.GetResult())
}The deadline travels
That 1.9s was printed by the server. It read the remaining time off the request:
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"xz/grpc/dlpb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50054",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := dlpb.NewSlowClient(conn)
r, _ := c.Peek(context.Background(), &dlpb.WorkRequest{})
fmt.Println(r.GetResult())
}Without a timeout, ctx.Deadline() reports none. The client’s budget is part of the request,
which HTTP has no equivalent of.
The 2s read as 1.9s because the clock was already running: the server gets the time left.
Seeing it expire
A 100ms deadline against work that takes five seconds:
package main
import (
"context"
"fmt"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"xz/grpc/dlpb"
)
func main() {
conn, _ := grpc.NewClient("localhost:50054",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer conn.Close()
c := dlpb.NewSlowClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
_, err := c.Work(ctx, &dlpb.WorkRequest{Ms: 5000})
st, _ := status.FromError(err)
fmt.Println(st.Code())
}The message varies: usually context deadline exceeded, sometimes a stream reset, depending on
which reply wins the race. Branch on the code, never the message.
Honouring it in a handler
The handler above selects on ctx.Done(), and the server log shows what happened:
trueThe server stopped working. It was told the client had gone, and gave up.
Work that ignores ctx cannot be interrupted at all.
Propagating downstream
Pass the handler’s ctx to the next call and the budget carries:
package main
import (
"context"
"fmt"
"time"
)
func handler(ctx context.Context) {
_, inherited := ctx.Deadline()
fmt.Println("inherited deadline:", inherited)
fresh := context.Background()
_, has := fresh.Deadline()
fmt.Println("fresh context deadline:", has)
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
handler(ctx)
}Retryable versus not
Which codes a retry should act on:
| Code | Retry |
|---|---|
Unavailable |
yes — nothing ran |
DeadlineExceeded |
only with a fresh budget |
ResourceExhausted |
yes, with backoff |
Aborted |
yes, the whole transaction |
Internal, Unknown |
no — the server is broken |
InvalidArgument, NotFound |
never — the answer will not change |