gRPC
gRPC uses Protocol Buffers to define a service contract once, generating strongly typed client and server code for fast, compact, binary communication over HTTP/2.
Overview
A versioned .proto file describes packages, services, methods, messages, enums, field numbers, and streaming direction; build tooling generates client stubs and server base classes so consumers do not hand-write serialization. ASP.NET Core hosts gRPC over HTTP/2 and integrates it with dependency injection, logging, authentication, authorization, interceptors, health checks, and OpenTelemetry. Unary calls fit request-response work, while server, client, and bidirectional streaming support ordered message sequences with cancellation and flow control. Production reliability depends on deadlines propagated through every downstream call, safe retries only for idempotent operations, bounded message sizes, keepalive and proxy compatibility, channel reuse, load-balancing behavior, status-code mapping, and contract compatibility. Fields may be added additively, but published numbers and wire meanings must never be reused; removed fields should be reserved. Browser, public-partner, and debugging needs may favor JSON HTTP, gRPC-Web, or a transcoding gateway, so protocol choice belongs to the consumer boundary rather than a performance slogan.
What you will learn
- Design stable protobuf packages, services, messages, field numbers, and evolution rules.
- Choose unary or streaming RPC shapes from workload behavior.
- Host and consume gRPC through ASP.NET Core HTTP/2 with reusable channels.
- Apply deadlines, cancellation, status codes, metadata, interceptors, and safe retry policy.
- Secure methods with transport encryption, authenticated identity, and authorization.
- Test generated clients against the real in-process HTTP/2 service and verify deployment infrastructure.
Prerequisites
- HTTP/2, asynchronous C#, dependency injection, and distributed call fundamentals.
- Basic schema evolution and authentication or authorization concepts.
- A .NET 10 SDK to run the dedicated inventory sample.
When to use gRPC
Good fit
- Use gRPC for controlled service-to-service boundaries that benefit from generated contracts, compact messages, and streaming.
- Use unary RPCs for independent request-response operations and streaming only for a real ordered flow.
- Use gRPC-Web or transcoding when browser or JSON consumers must share the service boundary.
Choose another approach when
- Do not require generated clients from unknown public consumers without an adoption plan.
- Do not retry non-idempotent methods blindly or omit deadlines.
- Do not change protobuf field numbers, reuse removed numbers, or change an established field's wire meaning.
- Do not assume every proxy, ingress, load balancer, or browser supports the required HTTP/2 behavior.
Key concepts
A compact, schema-first binary format defines message shapes once and generates typed code for multiple languages.
A .proto file declares RPC methods and their request/response types, acting as the single source of truth between client and server.
Multiplexed streams over one connection let gRPC support concurrent calls and native streaming without HTTP/1.1's per-request overhead.
Server, client, and bidirectional streaming let either side send a sequence of messages over one long-lived call.
A caller bounds how long work may take and the server propagates cancellation to databases and downstream RPCs.
Canonical status codes describe RPC outcomes while headers and trailers carry bounded cross-cutting metadata.
A long-lived channel multiplexes calls over HTTP/2; creating one per call wastes sockets and handshakes.
Additive fields preserve old readers, while reserved numbers prevent removed fields from acquiring conflicting meanings.
Architecture
A shared .proto contract generates client and server code; the client calls generated stubs, and the server implements the matching generated base class.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The dedicated inventory sample compiles one protobuf contract into client and server types, authenticates metadata in an interceptor, exposes unary lookup and server streaming, bounds receive size, maps validation to canonical statuses, and tests calls through an in-memory HTTP/2 host.
- 01Define the package contract
Choose a versioned protobuf package and model methods, messages, enums, optionality, and stable field numbers.
- 02Generate both boundaries
Use Grpc.Tools during build and review generated API changes through the .proto diff.
- 03Implement thin services
Derive from generated bases and delegate domain work to injected application services.
- 04Set call policy
Define deadlines, cancellation, message limits, idempotency, retry, and status mapping per method.
- 05Secure metadata and methods
Use TLS, authenticated credentials, authorization, and interceptors without logging tokens or sensitive payloads.
- 06Test real transport behavior
Run generated clients against an in-process HTTP/2 server for unary, streaming, denial, status, and cancellation paths.
- 07Verify infrastructure
Smoke-test HTTP/2, TLS termination, ingress, health, load balancing, observability, and graceful shutdown in the deployed route.
Code example
A generated base class exposes strongly typed request and response messages, so the implementation stays focused on behavior.
public sealed class OrderGrpcService(IOrderQueries queries) : OrderService.OrderServiceBase
{
public override async Task<OrderReply> GetOrder(
OrderRequest request, ServerCallContext context)
{
var order = await queries.FindAsync(Guid.Parse(request.OrderId), context.CancellationToken);
if (order is null)
throw new RpcException(new Status(StatusCode.NotFound, "Order not found"));
return new OrderReply { OrderId = order.Id.ToString(), Total = (double)order.Total };
}
}Testing strategy
Generated types alone do not prove routing, middleware, HTTP/2, status, or streaming behavior.
- Host the real ASP.NET Core pipeline and call it through a generated client.
- Cover authentication metadata, invalid arguments, not found, and internal-error redaction.
- Read server streams to completion and cancel mid-stream to prove resource cleanup.
- Test client deadlines and propagate cancellation to downstream work.
- Run protobuf compatibility checks so field removal, reuse, or type changes fail CI.
Security considerations
Binary encoding is not security; every RPC remains a network authorization boundary.
- Use TLS in transit and authenticate workload or user credentials through supported ASP.NET Core schemes.
- Authorize each service and method, including tenant and resource decisions inside application logic.
- Limit message and metadata sizes before allocation and validate every field after deserialization.
- Keep credentials, authorization metadata, and sensitive protobuf bodies out of logs and traces.
- Disable reflection publicly unless discovery is intentional and protected.
Performance and scalability
gRPC efficiency comes from compact contracts and connection reuse, not from removing operational bounds.
- Reuse channels and generated clients; do not create a channel per call.
- Set send and receive limits and stream incrementally rather than buffering unbounded sequences.
- Prefer async I/O, propagate cancellation, and avoid blocking service methods.
- Configure keepalive and concurrency only from measured infrastructure requirements.
- Measure method latency, status, bytes, active streams, and deadline expiry without high-cardinality labels.
Deployment and operations
HTTP/2 behavior must survive every network hop between generated client and service.
- Verify TLS, ALPN, HTTP/2, ingress protocol, idle timeout, maximum stream duration, and request size.
- Use readiness and graceful shutdown so new streams stop before existing calls drain.
- Confirm service discovery and load balancing match long-lived channel behavior.
- Deploy compatible servers before clients send newly added fields or call new methods.
- Smoke-test unary, streaming, authentication, deadline, and status behavior through the real route.
Common problems and fixes
Calls fail with UNAVAILABLE.
Likely cause: The endpoint, TLS, DNS, proxy, HTTP/2 route, or readiness is unavailable.
Fix: Inspect channel and server telemetry and test the exact deployed HTTP/2 path.
Calls hang much longer than expected.
Likely cause: No deadline was set or cancellation was not propagated.
Fix: Set a caller deadline and pass ServerCallContext.CancellationToken through all work.
A browser cannot call the endpoint.
Likely cause: Browsers do not expose framing required by native gRPC.
Fix: Use gRPC-Web, JSON transcoding, or a browser-facing gateway.
Old clients misread a deployment.
Likely cause: A field number or wire type was reused or semantics changed.
Fix: Restore compatible meaning, reserve removed numbers, and enforce compatibility checks.
Streaming consumes excessive memory.
Likely cause: Messages or the whole stream are buffered without limits.
Fix: Bound message size, process incrementally, observe flow control, and cancel abandoned streams.
Credentials fail through ingress.
Likely cause: Metadata was stripped or TLS and credential forwarding differ from local hosting.
Fix: Verify approved forwarding and use standard bearer, certificate, or workload identity.
Best practices
- Version .proto contracts additively—add new fields and methods rather than reusing or removing field numbers.
- Keep gRPC for controlled service boundaries where consumers can share the generated contract.
- Set and propagate deadlines and cancellation on every remote call.
- Retry only transient statuses for operations proven idempotent.
- Reuse channels and bound messages, metadata, concurrency, and stream duration.
- Map domain outcomes to canonical statuses without revealing internal details.
- Secure methods with TLS, authentication, authorization, and redacted telemetry.
- Test protobuf compatibility and the deployed HTTP/2 route, not only service classes.
Production checklist
- The versioned .proto package and ownership are documented.
- Published field numbers and meanings are stable and removed fields are reserved.
- Every call has deadline, cancellation, idempotency, retry, and status policy.
- Channels are reused and message, metadata, and stream work are bounded.
- TLS, authentication, method and resource authorization, and secret handling are reviewed.
- Unary, streaming, negative, deadline, and compatibility tests run in CI.
- HTTP/2, ingress, load balancing, health, graceful shutdown, and observability are verified.
- Reflection, detailed errors, and production discovery follow an explicit policy.
Common interview questions
Why is gRPC often faster than a typical JSON REST API?
It uses Protocol Buffers, a compact binary format, over HTTP/2, which supports multiplexed streams on one connection—together this reduces both payload size and connection overhead compared to text-based JSON over HTTP/1.1.
When would you choose REST over gRPC?
When the API needs to be broadly consumable by browsers and third parties without generated clients, or when human-readable payloads and simple tooling matter more than raw performance.
What are the three streaming modes gRPC supports beyond unary calls?
Server streaming, where the server sends multiple responses to one request; client streaming, where the client sends multiple requests for one response; and bidirectional streaming, where both sides send messages independently over the same call.
Why should a gRPC client set a deadline?
A deadline bounds caller resources and propagates cancellation to the server instead of allowing a remote call to wait indefinitely.
How do protobuf contracts evolve compatibly?
Add fields with new numbers, preserve existing meanings, tolerate unknown fields, and reserve removed names and numbers.
Why should channels be reused?
A channel owns reusable HTTP/2 connections and multiplexes calls; recreating it per call adds handshake cost and risks socket exhaustion.
How should a gRPC service report domain failures?
Map them to canonical status codes such as InvalidArgument, NotFound, FailedPrecondition, or PermissionDenied, with safe bounded detail for clients.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
gRPC Inventory
A contract-first .NET 10 gRPC service demonstrating protobuf evolution, unary and server-streaming calls, metadata authentication, bounded messages, canonical statuses, and real HTTP/2 client tests.
- Run
dotnet run --project src/GrpcInventory- Test
dotnet test GrpcInventory.slnx