GRPC Client Deadline Cancel Propagation

Set per-call deadlines on gRPC clients, propagate cancellation through context, and classify DEADLINE_EXCEEDED versus CANCELED codes.

GoData Fetching

Code

gosnippet
60 lines
package main

import (
	"context"
	"fmt"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	pb "example.com/proto/inventory/v1"
)

func reserveWithDeadline(
	ctx context.Context,
	client pb.InventoryClient,
	sku string, qty int32,
) (*pb.ReserveReply, error) {
	ctx, cancel := context.WithTimeout(ctx, 1200*time.Millisecond)
	defer cancel()

	reply, err := client.Reserve(ctx, &pb.ReserveRequest{
		Sku: sku, Quantity: qty,
	})
	if err != nil {
		st := status.Convert(err)
		switch st.Code() {
		case codes.DeadlineExceeded:
			return nil, fmt.Errorf("reserve timed out: %v", st.Message())
		case codes.Canceled:
			return nil, fmt.Errorf("reserve canceled by caller: %v", st.Message())
		case codes.Unavailable:
			return nil, fmt.Errorf("service unavailable, retry later: %v", st.Message())
		default:
			return nil, fmt.Errorf("reserve failed: %v", err)
		}
	}
	return reply, nil
}

func main() {
	conn, err := grpc.NewClient(
		"inventory.example.com:443",
		grpc.WithDefaultCallTimeout(5*time.Second),
	)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()

	client := pb.NewInventoryClient(conn)

	parent, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	reply, err := reserveWithDeadline(parent, client, "SKU-1", 3)
	fmt.Println(reply, err)
}

How it works

GRPC Client Deadline Cancel Propagation keeps everything in the functions reserveWithDeadline and main.

Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

What to watch for

  • Plan for an install step: google.golang.org/grpc, google.golang.org/grpc/codes and google.golang.org/grpc/status are a real dependency, resolved by the package manager.
  • Handle err before the other return values; that ordering is the whole contract.

Using it

The main signature reads func reserveWithDeadline( ctx context.Context, client pb.InventoryClient, sku string, qty int32, ) (*pb.Res…

main is the driver: it invokes reserveWithDeadline before returning.

Key statements

return nil, fmt.Errorf("service unavailable, retry later: %v", st.Message())
return nil, fmt.Errorf("reserve canceled by caller: %v", st.Message())
return nil, fmt.Errorf("reserve timed out: %v", st.Message())

Interactive Tools for This Topic

FAQ

What is the error handling style?
The Go way: `err` comes back from each call, and 2 checkpoints here test it before proceeding.
Which packages must be installed first?
Yes. The imports resolve to `google.golang.org/grpc`, `google.golang.org/grpc/codes` and `google.golang.org/grpc/status`, which the package manager must provide.