Chapter 14: Deadlines, Timeouts, and Cancellation

Deadlines (Timeouts)

Every gRPC call should have a deadline. Without one, a hung server holds the client forever.

// Client: set a 5-second deadline
grpc::ClientContext ctx;
ctx.set_deadline(std::chrono::system_clock::now() + std::chrono::seconds(5));

grpc::Status status = stub->GetUser(&ctx, req, &resp);
if (status.error_code() == grpc::DEADLINE_EXCEEDED) {
  // Server took too long
}

Deadline Propagation

Client (deadline: 5s) → Service A (remaining: 4.8s) → Service B (remaining: 4.5s) The deadline propagates! If Client sets 5s, and Service A takes 200ms, Service B only has 4.8s left. If B takes too long, the entire chain fails with DEADLINE_EXCEEDED. No wasted work.

Cancellation

// Client cancels an in-progress RPC:
ctx.TryCancel();  // signals server to stop

// Server checks if client cancelled:
if (context->IsCancelled()) {
  // Stop work, clean up, return
  return grpc::Status(grpc::CANCELLED, "client cancelled");
}
⚠️ Always Set Deadlines

A missing deadline means "wait forever." In production, this causes resource leaks (threads/connections held indefinitely). Set a deadline on EVERY client call. Typical: 1-30 seconds depending on the operation.

Key Takeaways