Explains gRPC in ASP.NET Core: .proto contracts and code generation, HTTP/2 framing, unary and streaming calls, deadlines and cancellation, status codes, comparison with REST/JSON, and browser support through gRPC-Web and JSON transcoding.
gRPC is a contract-first RPC framework. You define services and messages in a .proto file, and Grpc.Tools generates a C# base class for the server and a typed client at build time. Messages are serialised with Protocol Buffers, a compact binary format, and sent over HTTP/2, which gives multiplexed streams and trailers for the status. There are four call types: unary, server streaming, client streaming and bidirectional streaming. Every call should have a deadline, which flows to the server as a cancellation token. Compared with REST/JSON it is faster, smaller on the wire and strongly typed, with first-class streaming. But browsers can't call it directly, so you need gRPC-Web or JSON transcoding, and it is harder to debug and cache.
The trade-off: gRPC wins for internal service-to-service traffic; REST stays the default for public and browser APIs.
"gRPC is RPC with a strict contract. I write a
.protofile with services and messages, reference it in the project with<Protobuf Include=... GrpcServices="Server" />, andGrpc.Toolsgenerates a base class I override on the server and a typed client for callers. On the server it isbuilder.Services.AddGrpc()andapp.MapGrpcService<OrdersService>(). On the client I register it withAddGrpcClient<Orders.OrdersClient>(), which gives meIHttpClientFactoryhandling, so I don't create channels by hand.Messages are Protocol Buffers: binary, with fields identified by numbers, so payloads are typically several times smaller than JSON and much cheaper to serialise. The field numbers are the contract. You can add fields and rename them freely, but you never change or reuse a number. Transport is HTTP/2. Each call is a stream on a multiplexed connection, and the result status travels in trailers as
grpc-status. That gives four shapes of call: unary, which looks like a normal request; server streaming, for example a price feed; client streaming, for example uploading telemetry; and bidirectional, for example a chat or a sync protocol. Deadlines are central. The client setsdeadline: DateTime.UtcNow.AddSeconds(2), that is sent as thegrpc-timeoutheader, and on the server it surfaces ascontext.CancellationToken, which I pass down to EF Core andHttpClient. WithEnableCallContextPropagationthe remaining deadline also flows to downstream gRPC calls.Versus REST, gRPC is faster and stricter, and streaming is built in. REST is human-readable, cacheable, and works in every browser and tool. Browsers can't speak native gRPC because they don't expose HTTP/2 frames and trailers, so for a browser I use gRPC-Web (
app.UseGrpcWeb()), or JSON transcoding, which maps the same service to REST endpoints withgoogle.api.httpannotations. The mistake I see is teams using gRPC for a public API and then needing transcoding, gateways and docs for every consumer. I use gRPC for internal hops and keep REST at the edge."
| Type | Client sends | Server sends | Example | C# signature (server) |
|---|---|---|---|---|
| Unary | 1 message | 1 message | GetOrder |
Task<OrderReply> GetOrder(GetOrderRequest, ServerCallContext) |
| Server streaming | 1 | many | Price ticks, export rows | Task Watch(Req, IServerStreamWriter<Tick>, ServerCallContext) |
| Client streaming | many | 1 | Telemetry upload | Task<Summary> Upload(IAsyncStreamReader<Reading>, ServerCallContext) |
| Bidirectional | many | many | Chat, sync | Task Chat(IAsyncStreamReader<Msg>, IServerStreamWriter<Msg>, ServerCallContext) |
| gRPC | REST/JSON | |
|---|---|---|
| Contract | .proto, code generated, compile-time checked |
OpenAPI, optional |
| Payload | Protobuf binary | JSON text |
| Transport | HTTP/2 (HTTP/3 supported) | Any HTTP version |
| Streaming | Four call types built in | SSE, WebSockets, chunked responses |
| Browser | Only through gRPC-Web or transcoding | Native |
| Caching, CDNs | No (everything is POST) | GET caching, ETags |
| Errors | StatusCode in trailers, rich details with google.rpc.Status |
HTTP status plus ProblemDetails |
| Tooling | grpcurl, Postman, gRPC reflection | curl, browsers, everything |
| Option | What it does | Limits |
|---|---|---|
gRPC-Web (Grpc.AspNetCore.Web) |
Wraps gRPC so it works over HTTP/1.1 or HTTP/2 from JavaScript | No client or bidirectional streaming |
JSON transcoding (Microsoft.AspNetCore.Grpc.JsonTranscoding) |
Exposes the same service as REST + JSON using google.api.http annotations |
You design the REST mapping; OpenAPI needs the extra Swagger package |
Between our [pricing] and [checkout] services at [company] we replaced a REST/JSON call that ran [about 3,000 times per second]. Moving to gRPC with a 300 ms deadline cut payload size by roughly [70%] and p99 latency from [45 ms to 12 ms], and the generated client removed a class of mapping bugs because the contract was checked at compile time.
Checks whether the candidate understands how gRPC works (contracts, protobuf, HTTP/2, call types, deadlines) and can judge when it fits better than REST.
Green flags
Red flags
orders.proto ──Grpc.Tools (protoc + C# plugin, at build)──▶ Orders.OrdersBase (server: you override)
└──▶ Orders.OrdersClient (client: typed methods)
└──▶ GetOrderRequest, OrderReply message classes
Protobuf encodes each field as a tag (field number plus wire type) followed by the value, with varints for integers. Unknown fields are skipped by older readers, which is why adding fields is backward compatible and renumbering is not. Use reserved for removed fields.
HEADERS :method POST :path /orders.Orders/GetOrder content-type application/grpc grpc-timeout 2S
DATA [1 byte compressed flag][4 byte length][protobuf bytes]
────────── server ──────────
HEADERS :status 200 content-type application/grpc
DATA [length-prefixed protobuf reply]
HEADERS (trailers) grpc-status 0 grpc-message
The HTTP status is almost always 200. The real result is the grpc-status trailer, which is why proxies that drop trailers or don't support HTTP/2 end to end break gRPC.
client: deadline = now + 2 s ──grpc-timeout: 2S──▶ server: context.Deadline, context.CancellationToken
└─ passed to EF Core / HttpClient
└─ EnableCallContextPropagation ─▶ downstream gRPC gets the remaining ~1.8 s
when the deadline passes: client gets StatusCode.DeadlineExceeded, server token is cancelled
Without a deadline, a call to a stuck server waits for as long as the connection lives. Set a default per client with a CallOptions interceptor, or deadline: on every call.
A GrpcChannel keeps one long-lived HTTP/2 connection per server address and multiplexes calls on it (up to the server's max concurrent streams, often 100). That is efficient, but it means a layer 4 load balancer pins all calls from one client to one backend. You need layer 7 (HTTP/2-aware) balancing, a service mesh, or client-side balancing with DnsResolverFactory and RoundRobin. For high call rates, SocketsHttpHandler.EnableMultipleHttp2Connections = true avoids queuing when the stream limit is reached.
Servers throw RpcException(new Status(StatusCode.NotFound, "Order 42 not found")). Clients catch RpcException and switch on StatusCode. Retries are safe for Unavailable and, for idempotent calls, DeadlineExceeded; configure them declaratively with ServiceConfig retry policies instead of hand-written loops.
dotnet new grpc, add a server-streaming method, and call it with grpcurl -plaintext localhost:5000 list after enabling AddGrpcReflection().Task.Delay(500, context.CancellationToken) on the server; observe DeadlineExceeded and the server-side cancellation.JsonSerializer and message.ToByteArray().google.api.http options and call the same method with curl as REST.A gRPC service with unary and server-streaming methods, deadlines, a typed client and JSON transcoding.
// Protos/orders.proto
syntax = "proto3";
option csharp_namespace = "Shop.Orders";
import "google/api/annotations.proto";
service Orders {
rpc GetOrder (GetOrderRequest) returns (OrderReply) {
option (google.api.http) = { get: "/v1/orders/{order_id}" }; // JSON transcoding route
}
rpc WatchStatus (GetOrderRequest) returns (stream OrderReply);
}
message GetOrderRequest { int32 order_id = 1; }
message OrderReply {
int32 order_id = 1;
string status = 2;
reserved 3; // removed field: never reuse its number
}
<!-- Server .csproj -->
<ItemGroup>
<Protobuf Include="Protos\orders.proto" GrpcServices="Server" />
<PackageReference Include="Grpc.AspNetCore" Version="2.*" />
<PackageReference Include="Microsoft.AspNetCore.Grpc.JsonTranscoding" Version="10.*" />
</ItemGroup>
// Server: Program.cs (.NET 10)
using Grpc.Core;
using Shop.Orders;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc().AddJsonTranscoding();
var app = builder.Build();
app.MapGrpcService<OrdersService>();
app.Run();
public sealed class OrdersService(ILogger<OrdersService> logger) : Orders.OrdersBase
{
public override Task<OrderReply> GetOrder(GetOrderRequest request, ServerCallContext context)
{
if (request.OrderId <= 0)
throw new RpcException(new Status(StatusCode.InvalidArgument, "order_id must be positive"));
return Task.FromResult(new OrderReply { OrderId = request.OrderId, Status = "Packed" });
}
public override async Task WatchStatus(GetOrderRequest request, IServerStreamWriter<OrderReply> stream, ServerCallContext context)
{
// context.CancellationToken fires on client cancel or when the deadline passes.
var ct = context.CancellationToken;
foreach (var status in new[] { "Packed", "Dispatched", "Delivered" })
{
await Task.Delay(TimeSpan.FromSeconds(1), ct);
await stream.WriteAsync(new OrderReply { OrderId = request.OrderId, Status = status }, ct);
}
logger.LogInformation("Finished streaming order {OrderId}", request.OrderId);
}
}
// Client (another service): typed client through IHttpClientFactory, with deadlines.
using Grpc.Core;
using Shop.Orders;
builder.Services.AddGrpcClient<Orders.OrdersClient>(o => o.Address = new Uri("https://orders.internal"))
.EnableCallContextPropagation(); // pass the incoming deadline/cancellation downstream
public sealed class CheckoutService(Orders.OrdersClient orders)
{
public async Task<string> GetStatusAsync(int orderId, CancellationToken ct)
{
try
{
var reply = await orders.GetOrderAsync(
new GetOrderRequest { OrderId = orderId },
deadline: DateTime.UtcNow.AddMilliseconds(300), // always set a deadline
cancellationToken: ct);
return reply.Status;
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.DeadlineExceeded)
{
return "Unknown"; // degrade instead of hanging the checkout
}
}
}
context.CancellationToken down.reserved, and run a breaking-change check (for example buf breaking) in CI..proto files into each consuming repository, in each language. Why it is wrong: Copies drift: a Go or TypeScript client built from an old copy deserialises new fields wrongly or not at all. Instead: Keep one source of truth (a shared contracts repository or package), generate every language's code from it, and version it.GrpcChannel per call. Why it is wrong: You pay TCP and TLS set-up each time and lose HTTP/2 multiplexing. Instead: Use AddGrpcClient or reuse a long-lived channel.StatusCode.Unknown or Internal, or catching RpcException without looking at the code. Why it is wrong: Clients can't tell retryable errors (Unavailable, Aborted from a concurrency conflict) from bad requests (InvalidArgument, NotFound). Instead: Throw the right code on the server, switch on ex.StatusCode on the client, and retry only the safe ones.gRPC's real value is the contract, not just the speed. A .proto file in a shared repository, with breaking-change checks in CI, gives teams compile-time safety across services that OpenAPI rarely achieves in practice. The cost is operational: HTTP/2 end to end, layer 7 load balancing, binary payloads you can't read in logs, and tooling (grpcurl, reflection) that the team must learn.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| gRPC | Internal service-to-service, high call rates, streaming, polyglot teams | HTTP/2 infrastructure, tooling | Public APIs, browser-first clients |
| gRPC + JSON transcoding | One service serving internal gRPC and external REST | Annotation design, two surfaces to test | When REST is the main product |
| gRPC-Web | Browser clients that want the typed contract | Proxy or middleware, no client streaming | Two-way browser streaming |
| REST/JSON | Public, cacheable, simple CRUD | Larger payloads, hand-written clients unless generated | Chatty internal hops with tight latency budgets |
Measure before switching: payload size, serialisation CPU and p99 latency on the real call path. For a service that spends 40 ms in the database, saving 2 ms on serialisation changes nothing.
A load balancer spreads traffic across healthy instances.
Health checks remove unhealthy instances (in Kubernetes: readiness for traffic, liveness for restarts). Algorithms: round robin, least connections/requests, hashing. Sticky sessions pin a user to one instance, which hurts scaling and failover. Connection draining stops new traffic to an instance before shutdown so in-flight requests finish.
gRPC uses long-lived HTTP/2 connections, so an L4 balancer balances connections, not calls: one client connection carries all its calls to one pod. Use L7 balancing (mesh/Envoy) or client-side load balancing.
HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.
GET/HEAD/OPTIONS are safe; GET, PUT, DELETE are idempotent (repeating has the same effect); POST and usually PATCH are not, so retries need an idempotency key.Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.A timeout should cancel the work, not just stop waiting. Use a CancellationTokenSource with CancelAfter (linked to the caller's token) and pass it down. Task.WaitAsync(timeout) only stops waiting. For HTTP, HttpClient.Timeout is a single total timeout (100 seconds by default) that throws TaskCanceledException with an inner TimeoutException; in production I prefer AddStandardResilienceHandler, which sets attempt and total timeouts plus retries. In ASP.NET Core 8+, the request timeouts middleware cancels RequestAborted after a configured time. Timeouts must be layered: each inner timeout shorter than the outer one.
Treat it as three separate problems. Protocol failures ("protocol error", Unavailable, missing grpc-status) mean HTTP/2 isn't working end to end: a proxy downgrades to HTTP/1.1, drops trailers, or the endpoint isn't configured for HTTP/2 (plain-text HTTP/2 needs Http2-only endpoints; TLS needs ALPN). One pod gets all the traffic because a layer 4 load balancer pins each long-lived HTTP/2 connection to one backend; the fix is layer 7 balancing, a service mesh, or client-side round robin. DeadlineExceeded under load is usually queuing, not slowness: the 100-stream limit per connection, ThreadPool starvation, or deadlines stacked per hop instead of propagated. I diagnose with gRPC client and server logs at Debug, grpcurl from inside the network, Application Insights dependency timings and the gRPC EventCounters.
The trade-off: long-lived HTTP/2 connections are efficient, but they move load balancing and timeouts into your design.
Last updated 23 Nov 2026.