Introduction
In real-world applications, not every request should run forever. Sometimes a client only wants to wait for a limited time, and if the response takes too long, it should stop the request.
This is where deadlines and cancellation come into play in gRPC.
In this article, we will understand how deadlines and cancellation work in gRPC .NET and how to implement them in a simple and practical way.
What are Deadlines in gRPC?
A deadline is a time limit set by the client for a request.
It means:
This helps prevent unnecessary waiting and improves performance.
What is Cancellation?
Cancellation allows either the client or server to stop an ongoing request.
This is useful when:
The user cancels an operation
The request is no longer needed
The system wants to free resources
How Deadlines Work Internally
When a client sets a deadline:
The deadline is sent with the request
The server monitors the remaining time
If time expires, the request is automatically cancelled
This ensures efficient resource usage.
Setting Deadline on Client Side
In .NET, you can set a deadline using CallOptions.
var deadline = DateTime.UtcNow.AddSeconds(5);
var response = await client.GetDataAsync(
new MyRequest(),
deadline: deadline);
Here, the client is saying: “Wait only 5 seconds for the response.”
If the server takes longer, the request will fail.
Handling Deadline on Server Side
On the server, you can check if the request is cancelled.
public override async Task<MyResponse> GetData(MyRequest request, ServerCallContext context)
{
for (int i = 0; i < 10; i++)
{
if (context.CancellationToken.IsCancellationRequested)
{
Console.WriteLine("Request cancelled");
break;
}
await Task.Delay(1000);
}
return new MyResponse { Message = "Completed" };
}
This allows the server to stop work early when cancellation happens.
Using Cancellation Token in .NET
The CancellationToken is the key part of handling cancellation.
It allows you to:
Detect cancellation
Stop long-running tasks
Release resources early
Always pass this token to async operations when possible.
Handling Exceptions for Deadlines
When a deadline is exceeded, the client receives an error.
try
{
var response = await client.GetDataAsync(new MyRequest(), deadline: DateTime.UtcNow.AddSeconds(2));
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded)
{
Console.WriteLine("Request timed out");
}
This helps you handle timeout scenarios properly.
Best Practices for Deadlines and Cancellation
Always set deadlines for external calls
Handle cancellation tokens in server code
Avoid long-running operations without checks
Free resources when cancellation happens
These practices improve performance and reliability.
Common Mistakes to Avoid
These can lead to performance issues and resource wastage.
When to Use Deadlines and Cancellation
You should use them in:
They help make your system more responsive and efficient.
Summary
Deadlines and cancellation in gRPC .NET help control how long a request should run and allow stopping it when needed. By setting deadlines on the client side and handling cancellation properly on the server side, you can build efficient, responsive, and resource-friendly applications.