When an ASP.NET Core gRPC service calls another gRPC service, how do AddGrpcClient, deadlines and EnableCallContextPropagation keep the chain bounded?
answer
- AddGrpcClient<T> returns IHttpClientBuilder
- deadline: DateTime.UtcNow.AddSeconds(2)
- RpcException with DeadlineExceeded
- EnableCallContextPropagation copies deadline and token
- SuppressContextNotFoundErrors defaults to false
basics
~10 sRegister the downstream client with AddGrpcClient<T>(o => o.Address = ...), pass a deadline on each call, and add EnableCallContextPropagation() so calls made inside a gRPC handler inherit the incoming call's deadline and cancellation token.
solid answer
~40 s`builder.Services.AddGrpcClient<Inventory.InventoryClient>(o => o.Address = new Uri("https://inventory"))` registers the generated client as transient and returns an `IHttpClientBuilder`, so the channel's `HttpMessageHandler` is managed by the HTTP client factory. A call such as `client.CheckStockAsync(req, deadline: DateTime.UtcNow.AddSeconds(2))` sends a deadline; when it passes, the client aborts the request and throws `RpcException` with `StatusCode.DeadlineExceeded`, while the server's `context.CancellationToken` fires but its method keeps running until it returns. Chaining `.EnableCallContextPropagation()` copies the current `ServerCallContext`'s deadline and cancellation token onto child calls, and the smaller deadline wins if the child sets its own. Used outside a gRPC call, for example from a `BackgroundService`, a propagating client throws `InvalidOperationException` unless `SuppressContextNotFoundErrors` is true.
code
csharp · 14 linesbuilder.Services.AddGrpc();
builder.Services
.AddGrpcClient<Inventory.InventoryClient>(o => o.Address = new Uri("https://inventory"))
.EnableCallContextPropagation();
public class PriceQuoteService(Inventory.InventoryClient inventory) : PriceQuote.PriceQuoteBase
{
public override async Task<QuoteReply> GetQuote(QuoteRequest request, ServerCallContext context)
{
// deadline and cancellation of the incoming call flow into this call
var stock = await inventory.CheckStockAsync(new StockRequest { Sku = request.Symbol });
return new QuoteReply { Symbol = request.Symbol, InStock = stock.Available };
}
}go deeper
Recall that AddGrpcClient registers a generated client and that a deadline is passed per call and surfaces as DeadlineExceeded.
Explain the client and server behaviour when a deadline passes, and how EnableCallContextPropagation carries deadline and cancellation to child calls.
Bound whole call chains: deadlines on every call, cancellation tokens passed into I/O, propagation where a call context exists and explicit handling where it does not.
Set deadline budgets across services so each hop has a share, and make timeouts traceable to the hop that consumed the budget.
## The call chain The internal price-quote service answers `GetQuote` by asking an inventory service whether the item is in stock. If the quote's caller gave up after two seconds, the inventory call should give up too, and nothing should wait forever. Three tools cover it. ## AddGrpcClient `AddGrpcClient<TClient>` comes from `Grpc.Net.ClientFactory`, which `Grpc.AspNetCore` already references. - `services.AddGrpcClient<Inventory.InventoryClient>(o => o.Address = new Uri("https://inventory"))` registers the generated client type as **transient**. - It returns an `IHttpClientBuilder`: the channel's handler is created and recycled by the HTTP client factory, so the usual builder extensions apply. - `.ConfigureChannel(o => ...)` sets `GrpcChannelOptions` such as message size limits; the client's receive limit defaults to 4 MB, like the server's. - `.AddInterceptor<T>()` and `.AddCallCredentials(...)` add client interceptors and per-call credentials. Inject `Inventory.InventoryClient` into the service constructor and call it; do not build a new `GrpcChannel` per request. ## Deadlines A deadline is an absolute UTC time passed in `CallOptions`, most often through the generated method's `deadline:` parameter. | Side | What happens when the deadline passes | |---|---| | client | aborts the HTTP request and throws `RpcException` with `StatusCode.DeadlineExceeded` | | server | aborts the request and raises `context.CancellationToken`; the method keeps running until it returns | Two consequences: 1. Server code must pass `context.CancellationToken` to database queries, HTTP calls and gRPC calls, or the work continues after nobody is waiting. 2. With no deadline sent, `context.Deadline` is `DateTime.MaxValue`; a caller that never sets one can keep a server busy indefinitely. When retries are configured on the channel, the deadline covers all attempts together. ## EnableCallContextPropagation Passing `deadline: context.Deadline, cancellationToken: context.CancellationToken` to every child call by hand is easy to forget. The extension from `Grpc.AspNetCore.Server.ClientFactory` does it: - `services.AddGrpcClient<Inventory.InventoryClient>(...).EnableCallContextPropagation();` - On each call it finds the current `ServerCallContext` through `IHttpContextAccessor` and copies its deadline and cancellation token into the call options. - If the child call specifies its own deadline, the **smaller** one is used; if it passes its own token, the two are linked. - If no server call is in progress, it throws `InvalidOperationException` ("Unable to propagate server context values to the call"). Set `SuppressContextNotFoundErrors = true` in `EnableCallContextPropagation(o => ...)` for a client shared with background code; the call then goes out without propagated values. ## Putting it together - Clients that call the price-quote service set a deadline on every call. - The price-quote service propagates it to inventory with `EnableCallContextPropagation()` and passes `context.CancellationToken` to its own I/O. - Log `DeadlineExceeded` at each hop, so a timeout can be traced to the service that used up the budget. Retries, hedging and the resilience handlers on the underlying `HttpClient` are an HTTP client topic; the deadline is what bounds the gRPC call as a whole. ## Choosing deadline values | Caller | Reasonable approach | |---|---| | interactive dashboard | a short deadline per call, close to what a user will wait | | batch job | a longer deadline, still finite, plus cancellation on shutdown | | service in the middle of a chain | propagate the incoming deadline rather than inventing a new one | A deadline is not a retry policy: when it passes, the call is over. If a downstream call may be retried, the retries must fit inside the same deadline, which is why the channel's retry policy counts against it.
- A BackgroundService reuses the propagating Inventory client and every call throws. Why, and what are the options?`EnableCallContextPropagation` looks for the current `ServerCallContext`; a background worker has none, so the interceptor throws `InvalidOperationException`. Either set `SuppressContextNotFoundErrors = true` so calls go out without propagation, or register a second named client without propagation for background use and set an explicit deadline there.
- The parent call has 10 seconds left and the child call passes deadline: DateTime.UtcNow.AddSeconds(5). Which deadline applies?The five-second one. Propagation uses the smallest deadline available, so a child can tighten the budget but never extend it beyond the parent's deadline.
- When the deadline passes, ASP.NET Core aborts the handler's thread on the server.
- AddGrpcClient registers the client as a singleton, so it should be cached in a static field.
- EnableCallContextPropagation lets a child call extend the parent's deadline.
- A propagating client silently skips propagation when used from a BackgroundService.
- A call that sends no deadline gets a default server-side deadline from ASP.NET Core.