aspnetcore/grpc/deadlines-cancellation.md
Deadlines and cancellation are features used by gRPC clients to abort in-progress calls. This article discusses why deadlines and cancellation are important, and how to use them in .NET gRPC apps.
A deadline allows a gRPC client to specify how long it will wait for a call to complete. When a deadline is exceeded, the call is canceled. Setting a deadline is important because it provides an upper limit on how long a call can run for. It stops misbehaving services from running forever and exhausting server resources. Deadlines are a useful tool for building reliable apps and should be configured.
Deadline configuration:
CallOptions.Deadline when a call is made.DateTime.UtcNow.AddSeconds(5) is a deadline of 5 seconds from now.If a deadline is exceeded, the client and service have different behavior:
DeadlineExceeded error. The client app can choose to catch the error and display a timeout message to the user.Configure CallOptions.Deadline to set a deadline for a gRPC call:
Using ServerCallContext.CancellationToken in a gRPC service:
When a gRPC call is configured with retry fault handling and a deadline, the deadline tracks time across all retries for a gRPC call. If the deadline is exceeded, a gRPC call immediately aborts the underlying HTTP request, skips any remaining retries, and throws a DeadlineExceeded error.
When a gRPC call is made from an executing gRPC service, the deadline should be propagated. For example:
FrontendService.GetUser with a deadline.FrontendService calls UserService.GetUser. The deadline specified by the client should be specified with the new gRPC call.UserService.GetUser receives the deadline. It correctly times-out if the client app's deadline is exceeded.The call context provides the deadline with ServerCallContext.Deadline:
Manually propagating deadlines can be cumbersome. The deadline needs to be passed to every call, and it's easy to accidentally miss. An automatic solution is available with gRPC client factory. Specifying EnableCallContextPropagation:
CallOptions.Deadline. When multiple deadlines are available, the smallest deadline is used.For more information, see xref:grpc/clientfactory#deadline-and-cancellation-propagation.
Cancellation allows a gRPC client to cancel long running calls that are no longer needed. For example, a gRPC call that streams realtime updates is started when the user visits a page on a website. The stream should be canceled when the user navigates away from the page.
A gRPC call can be canceled in the client by passing a cancellation token with CallOptions.CancellationToken or calling Dispose on the call.
gRPC services that can be cancelled should:
ServerCallContext.CancellationToken to async methods. Canceling async methods allows the call on the server to complete quickly.EnableCallContextPropagation() automatically propagates the cancellation token.