How to Use gRPC Deadlines and Timeouts in Go

Web
Set gRPC deadlines and timeouts in Go by creating a context with context.WithTimeout or context.WithDeadline and passing it to your client call.

Use context.WithTimeout or context.WithDeadline to create a context with a time limit, then pass that context to your gRPC client call. The context controls both the client-side timeout and the server-side deadline.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

resp, err := client.MyService(ctx, &MyRequest{})
if err != nil {
    // Handle timeout or other errors
}

For server-side handlers, the incoming context.Context already contains the deadline set by the client. Check ctx.Deadline() or ctx.Err() to detect if the deadline has passed.