gRPC changes how backend services communicate. Instead of sending loosely structured JSON over traditional HTTP endpoints, gRPC uses strongly typed contracts defined with Protocol Buffers and communicates over HTTP/2.
For ASP.NET Core developers, the challenge is usually not creating the first gRPC service. The harder part is preparing an existing application so that gRPC traffic works reliably alongside authentication, authorization, logging, health checks, streaming, deployment, and traditional REST APIs.
A well-prepared ASP.NET Core application can support both REST and gRPC without forcing every client to use the same communication model.
Understanding Where gRPC Fits
REST and gRPC solve different problems.
REST is usually a good choice when APIs are consumed directly by browsers, external clients, or systems where HTTP and JSON provide a simple integration model.
gRPC is particularly useful for internal services, high-frequency service-to-service communication, strongly typed contracts, and streaming scenarios.
A typical application may therefore expose both:
ASP.NET Core Application
|
+-- REST API
|
+-- gRPC Services
|
+-- Health Endpoints
|
+-- Authentication
|
+-- ObservabilityThe important point is that gRPC should be treated as another first-class communication layer rather than an isolated feature added to an existing project.
Define the Contract First
gRPC APIs are based on .proto files.
A simple contract might look like this:
syntax = "proto3";
option csharp_namespace = "Catalog.Contracts";
package catalog;
service CatalogService {
rpc GetProduct (GetProductRequest) returns (ProductReply);
}
message GetProductRequest {
int32 id = 1;
}
message ProductReply {
int32 id = 1;
string name = 2;
double price = 3;
}The contract defines the service method and the request and response messages.
This gives both sides a common interface. The client and server can generate strongly typed code from the same contract instead of manually maintaining JSON models and endpoint documentation.
Keep contracts focused. Avoid creating a single service containing dozens of unrelated operations.
Add gRPC to ASP.NET Core
The ASP.NET Core application needs the gRPC services registered during startup.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.MapGrpcService<CatalogService>();
app.Run();This allows the same application to expose both conventional API controllers and gRPC services.
For example:
/api/productscan remain a REST endpoint while:
catalog.CatalogService/GetProductis handled by the gRPC service.
Configure HTTP/2 Correctly
The HTTP protocol configuration is one of the most important parts of a gRPC deployment.
gRPC requires HTTP/2 for normal gRPC communication. The server therefore needs an HTTPS endpoint configured for HTTP/2.
A Kestrel configuration can explicitly define the protocol:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://0.0.0.0:5001",
"Protocols": "Http2"
}
}
}
}For an application serving both REST and gRPC traffic, you may need to support HTTP/1.1 and HTTP/2 on the same endpoint.
Kestrel can negotiate the protocol using HTTPS and ALPN:
{
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://0.0.0.0:5001",
"Protocols": "Http1AndHttp2"
}
}
}
}This configuration is useful when the same application needs to handle conventional HTTP APIs and gRPC traffic.
The exact protocol configuration should match the deployment architecture. If a reverse proxy or gateway sits in front of the application, verify that it also supports the required HTTP/2 path.
Keep REST and gRPC Models Separate
One common mistake is trying to reuse every model between REST and gRPC.
For example, a REST API might use:
public sealed record ProductResponse(
int Id,
string Name,
decimal Price);The gRPC contract generates its own types:
ProductReplyThese models serve different purposes.
REST models define an HTTP/JSON contract. Protobuf messages define a gRPC contract.
The domain model should remain independent from both:
Domain Model
/ \
/ \
REST DTO gRPC MessageThis separation prevents changes to one external contract from accidentally changing internal application behavior.
Keep Business Logic Out of the gRPC Service
The gRPC service should coordinate the request, not contain the entire business operation.
For example:
public sealed class CatalogService : Catalog.CatalogBase
{
private readonly IProductService _products;
public CatalogService(IProductService products)
{
_products = products;
}
public override async Task<ProductReply> GetProduct(
GetProductRequest request,
ServerCallContext context)
{
var product = await _products.GetAsync(
request.Id,
context.CancellationToken);
if (product is null)
{
throw new RpcException(
new Status(
StatusCode.NotFound,
"Product was not found."));
}
return new ProductReply
{
Id = product.Id,
Name = product.Name,
Price = (double)product.Price
};
}
}The gRPC service handles protocol-specific concerns while IProductService handles application logic.
This makes the business logic easier to test and reuse.
Handle Errors Using gRPC Status Codes
A REST API often communicates errors through HTTP status codes and JSON responses.
gRPC uses status codes.
For example:
throw new RpcException(
new Status(
StatusCode.InvalidArgument,
"Product ID must be greater than zero."));Common status codes include:
gRPC Status | Typical Use |
|---|---|
OK | Successful operation |
InvalidArgument | Invalid request data |
NotFound | Requested resource does not exist |
AlreadyExists | Resource already exists |
Unauthenticated | Authentication is missing or invalid |
PermissionDenied | Caller is authenticated but not authorized |
Unavailable | Temporary service or dependency failure |
DeadlineExceeded | Operation exceeded its allowed time |
Internal | Unexpected server-side failure |
Do not return Internal for every problem. Use meaningful status codes so clients can make appropriate decisions.
Pass Cancellation Through the Application
gRPC supports cancellation through ServerCallContext.
Use the request cancellation token when calling downstream services.
var product = await _products.GetAsync(
request.Id,
context.CancellationToken);This matters when clients disconnect or cancel requests.
Without cancellation propagation, the server may continue doing database or network work after the client has already stopped waiting for the result.
For long-running operations, cancellation should be passed through every layer that supports it.
Configure Deadlines
A client can specify a deadline for a gRPC operation.
Server-side code can inspect the deadline through the call context:
if (context.Deadline < DateTime.UtcNow)
{
throw new RpcException(
new Status(
StatusCode.DeadlineExceeded,
"The request deadline has expired."));
}In practice, application code should normally rely on the gRPC infrastructure and cancellation token rather than manually implementing deadline logic everywhere.
The important design principle is that service calls should have reasonable time limits.
A request that can wait indefinitely can eventually consume threads, connections, database resources, or other infrastructure.
Secure gRPC Endpoints
Authentication should be applied to gRPC services just as it is to REST APIs.
For JWT authentication:
builder.Services
.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "catalog-api";
});
builder.Services.AddAuthorization();Then configure the middleware:
app.UseAuthentication();
app.UseAuthorization();Authorization can be applied directly to a gRPC service:
[Authorize]
public sealed class CatalogService : Catalog.CatalogBase
{
}For more granular policies:
[Authorize(Policy = "Catalog.Read")]Authentication answers who the caller is. Authorization determines what that caller is allowed to do.
Do not rely solely on a gateway or load balancer for application-level authorization.
Add Health Checks
Health checks are especially important when gRPC services are deployed behind a load balancer or routing layer.
ASP.NET Core health checks can be registered with:
builder.Services.AddHealthChecks();Then expose a health endpoint:
app.MapHealthChecks("/health");This endpoint should remain lightweight.
Avoid making the health check perform a full business operation. If a service has multiple dependencies, decide carefully whether the endpoint represents process health, readiness, or dependency health.
For larger deployments, separating liveness and readiness concepts can make service orchestration more reliable.
Support gRPC Health Checking
For gRPC-specific infrastructure, the application can also implement the standard gRPC health checking protocol.
A typical setup uses the gRPC health checking package:
builder.Services.AddGrpcHealthChecks();The service can then expose the health service:
app.MapGrpcHealthChecksService();This is useful when the infrastructure expects a gRPC-native health check rather than a normal HTTP endpoint.
The exact health-check strategy should match the platform handling traffic for the service.
Prepare for Streaming
gRPC supports four communication patterns:
Pattern | Client Messages | Server Messages |
|---|---|---|
Unary | 1 | 1 |
Server streaming | 1 | Many |
Client streaming | Many | 1 |
Bidirectional streaming | Many | Many |
For example, server streaming can be defined as:
rpc WatchProducts (WatchRequest)
returns (stream ProductReply);The implementation can write multiple responses:
public override async Task WatchProducts(
WatchRequest request,
IServerStreamWriter<ProductReply> responseStream,
ServerCallContext context)
{
await foreach (var product in _products.StreamAsync(
context.CancellationToken))
{
await responseStream.WriteAsync(
new ProductReply
{
Id = product.Id,
Name = product.Name,
Price = (double)product.Price
});
}
}Streaming changes the operational requirements of the application.
You need to consider connection duration, cancellation, timeouts, memory usage, backpressure, and client reconnection behavior.
Do not assume that a service tested successfully with unary calls is automatically ready for production streaming traffic.
Configure Observability
A production gRPC service should provide enough telemetry to answer basic questions:
Which RPC is failing?
How long does it take?
Which status code is returned?
Which dependency is slow?
Which client or service initiated the request?
Did the request exceed its deadline?
ASP.NET Core logging can include the gRPC method name and request information.
Avoid logging sensitive request payloads by default.
For distributed systems, correlation and trace propagation are particularly useful:
Client
|
v
API Gateway
|
v
gRPC Service
|
v
DatabaseA trace should make it possible to follow the request across these boundaries without exposing confidential data in logs.
Version gRPC Contracts Carefully
Protobuf provides useful compatibility rules, but developers still need to design contracts carefully.
Avoid reusing field numbers after removing fields.
For example:
message ProductReply {
int32 id = 1;
string name = 2;
double price = 3;
}If a field is removed, reserve its number:
message ProductReply {
reserved 3;
int32 id = 1;
string name = 2;
}This helps prevent accidental reuse of an old field number.
When evolving a contract, prefer adding new fields rather than changing the meaning of existing fields.
Common Mistakes
Treating gRPC like REST
gRPC has different protocol, serialization, error-handling, and streaming behavior. Avoid designing it as a JSON API with a different transport.
Forgetting HTTP/2
A service can be correctly implemented but still fail after deployment because an intermediary does not preserve the required HTTP/2 connection.
Returning generic errors
Using Internal for validation, authentication, and missing-resource errors makes client behavior harder to implement correctly.
Ignoring cancellation
Long-running operations should stop when the client cancels the request.
Coupling protobuf messages to domain models
Generated contract classes should not become the application's internal data model.
Testing only local development
A local gRPC call may work while the production path fails because of TLS, proxy, gateway, HTTP/2, routing, or timeout configuration.
Best Practices
Use .proto files as explicit API contracts.
Keep gRPC services focused on communication and orchestration.
Keep domain logic in application services.
Use appropriate gRPC status codes.
Propagate cancellation tokens.
Set sensible deadlines.
Secure services with authentication and authorization.
Test unary and streaming calls separately.
Monitor latency, status codes, failures, and dependency calls.
Treat protobuf contracts as versioned public interfaces.
Verify every proxy, gateway, and load balancer in the request path for HTTP/2 compatibility.
Advantages
Advantage | Description |
|---|---|
Strong contracts | Protobuf provides explicit service and message definitions |
Efficient serialization | Binary Protobuf messages are compact |
Streaming | Supports server, client, and bidirectional streaming |
Generated clients | Client code can be generated from the contract |
Internal communication | Works well for service-to-service communication |
Clear error model | Standard gRPC status codes simplify error handling |
Disadvantages and Considerations
Consideration | Impact |
|---|---|
Browser compatibility | Direct browser support is more limited than REST |
Debugging | Binary payloads are less convenient to inspect manually |
HTTP/2 dependency | Infrastructure must correctly support HTTP/2 |
Contract management | Protobuf changes require careful compatibility practices |
Streaming complexity | Long-lived connections require additional operational planning |
External APIs | REST may remain simpler for many public-facing integrations |
Troubleshooting Checklist
When a gRPC API works locally but fails after deployment, check the request path layer by layer:
Confirm the client uses HTTPS.
Confirm HTTP/2 is available where required.
Check the TLS certificate and hostname.
Verify the reverse proxy or gateway configuration.
Confirm the gRPC service is registered in ASP.NET Core.
Check authentication and authorization.
Verify the requested RPC exists in the deployed contract version.
Check gRPC status codes in application logs.
Verify cancellation and deadline behavior.
Test streaming independently from unary RPCs.
Check health and readiness behavior.
Compare direct backend traffic with traffic passing through the production gateway.
This process usually identifies whether the problem is in the application, protocol configuration, or infrastructure.
Summary
Preparing an ASP.NET Core API for modern gRPC traffic involves more than adding AddGrpc() and creating a .proto file.
The application needs a clear contract, correct HTTP/2 configuration, separation between transport and domain models, proper authentication and authorization, meaningful gRPC status codes, cancellation handling, deadlines, health checks, observability, and careful contract versioning.
A production-ready architecture should look roughly like this:
Client
|
HTTPS/HTTP2
|
v
Gateway / Front Door
|
v
ASP.NET Core Application
/ \
/ \
REST gRPC
| |
v v
REST DTOs Protobuf Contract
\ /
\ /
Domain Layer
|
v
Data / ServicesThe key is to treat gRPC as a first-class API style inside the application. Once protocol handling, business logic, security, observability, and contract management are separated properly, ASP.NET Core can support gRPC traffic without turning the rest of the application into a specialized system.

Join the conversation! Your thoughts help the community grow.