Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 12 · Lesson 119 · 7 min read

gRPC in .NET: Contracts, Deadlines and Security

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Contract, a Service, a Client with a Deadline and Authorization
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Define a gRPC contract with Protocol Buffers, implement a service and client in .NET, use deadlines and error codes correctly, evolve messages without breaking clients, and secure internal calls with mutual TLS and token-based authorization.

Concept Explanation

gRPC is a remote procedure call framework that runs over HTTP/2 and uses Protocol Buffers, a compact binary format, to define messages and services in a .proto file. From that contract, tools generate strongly typed client and server code, so calling another service feels like calling a method. Compared with JSON over REST, messages are smaller and faster to serialize, HTTP/2 multiplexes many calls over one connection, and the framework supports four call styles: a simple request and response, server streaming, client streaming, and bidirectional streaming. That makes it a good fit for internal service-to-service calls where performance and a strict contract matter, and a poor fit for public browser-facing APIs, since browsers cannot use the full protocol. gRPC-Web, with a translating layer, bridges that gap, but for a React front end a plain REST API through the BFF remains the simpler choice.

The contract is the core discipline. Each field has a number, and that number is what identifies it on the wire, so you may add new fields and mark old ones obsolete, but you must never reuse or change a field number, and you should reserve numbers and names you have removed. Adding optional fields is backward compatible; changing a type or reusing a number is a break that fails in confusing ways. Keep the contract in a shared repository or package, and run a breaking-change check, such as buf, in CI in the same way Day 25 protected REST clients.

Two operational rules matter more than any other. Every call should have a deadline, an absolute point in time by which the caller no longer cares, and the deadline propagates to downstream calls, so a slow dependency cannot hold a chain of services forever. This is the cure for the cascading waits that Day 69 described. And use the rich status codes that gRPC defines, such as InvalidArgument, NotFound, PermissionDenied, Unauthenticated, DeadlineExceeded, and Unavailable, mapping them to and from HTTP responses at the edge, and treating only appropriate ones, such as Unavailable, as retryable. Configure a maximum message size, because the default receive limit of four megabytes exists for a reason, and stream large data instead of raising it.

Internal does not mean trusted. Between services, use TLS everywhere, and mutual TLS where each side presents a certificate, so that a service can be sure who is calling. Layer on token-based authorization, passing a JWT in call metadata that the receiving service validates, with the caller identity coming from workload identity, which Day 131 covers under machine-to-machine authentication, and not from a shared secret in configuration. Validate every incoming message as carefully as you would an HTTP body, since a strict schema does not check business rules or sizes of strings and lists. Disable server reflection in production unless it is needed, because it lists your services and methods, and make sure a gRPC port is never exposed publicly by accident. Denial of service protections remain relevant: the HTTP/2 Rapid Reset attack in 2023 exploited the protocol itself, and servers needed patches.

TopicGuidelineWhy
Field numbersNever reuse or renumber, reserve removed onesThe number identifies the field on the wire
Adding fieldsSafe, old clients ignore themBackward compatible
DeadlinesAlways set, propagate downstreamPrevents slow calls from piling up
Status codesUse the specific gRPC codesClients can decide what to retry
Message sizeKeep the limit, stream large dataProtects memory
Transport securityTLS everywhere, mutual TLS between servicesIdentifies both parties

Worked Example: A Contract, a Service, a Client with a Deadline and Authorization

The proto defines the contract with a reserved field. The C# implements the service with validation and status codes, and configures the client.

Protobuf
syntax = "proto3";
option csharp_namespace = "Acme.Reporting.V1";
package acme.reporting.v1;

service ReportService {
  rpc GetProjectSummary (ProjectSummaryRequest) returns (ProjectSummaryReply);
  rpc StreamTaskChanges (TaskChangesRequest) returns (stream TaskChange);   // server streaming
}

message ProjectSummaryRequest { int32 project_id = 1; }
message ProjectSummaryReply {
  int32 project_id = 1;
  int32 open_tasks = 2;
  int32 done_tasks = 3;
  reserved 4;                 // a removed field: its number can never be reused
  reserved "legacy_score";
}
message TaskChangesRequest { int32 project_id = 1; }
message TaskChange { int32 task_id = 1; string state = 2; }
C#
// Server: validate, authorize, and return precise status codes.
[Authorize(Policy = "InternalService")]
public sealed class ReportServiceImpl(AppDb db, ILogger<ReportServiceImpl> log) : ReportService.ReportServiceBase
{
    public override async Task<ProjectSummaryReply> GetProjectSummary(ProjectSummaryRequest request, ServerCallContext context)
    {
        if (request.ProjectId <= 0) throw new RpcException(new Status(StatusCode.InvalidArgument, "project_id must be positive"));

        var ct = context.CancellationToken;                                    // honours the caller's deadline and cancellation
        var counts = await db.Tasks.AsNoTracking().Where(t => t.ProjectId == request.ProjectId)
            .GroupBy(t => t.State).Select(g => new { State = g.Key, N = g.Count() }).ToListAsync(ct);
        if (counts.Count == 0 && !await db.Projects.AnyAsync(p => p.Id == request.ProjectId, ct))
            throw new RpcException(new Status(StatusCode.NotFound, "Project not found"));

        return new ProjectSummaryReply
        {
            ProjectId = request.ProjectId,
            OpenTasks = counts.Where(c => c.State != TaskState.Done).Sum(c => c.N),
            DoneTasks = counts.Where(c => c.State == TaskState.Done).Sum(c => c.N),
        };
    }
}

// Program.cs
builder.Services.AddGrpc(o => { o.MaxReceiveMessageSize = 1 * 1024 * 1024; });      // keep limits deliberate
app.MapGrpcService<ReportServiceImpl>();
if (app.Environment.IsDevelopment()) app.MapGrpcReflectionService();               // reflection off in production
C#
// Client: a typed client with retries only for Unavailable, a deadline on every call, and a token from workload identity.
builder.Services.AddGrpcClient<ReportService.ReportServiceClient>(o => o.Address = new Uri("https://reporting.internal"))
    .ConfigureChannel(o => o.ServiceConfig = new ServiceConfig
    {
        MethodConfigs = { new MethodConfig
        {
            Names = { MethodName.Default },
            RetryPolicy = new RetryPolicy { MaxAttempts = 3, InitialBackoff = TimeSpan.FromMilliseconds(200), MaxBackoff = TimeSpan.FromSeconds(2),
                                            BackoffMultiplier = 2, RetryableStatusCodes = { StatusCode.Unavailable } },
        } },
    })
    .AddCallCredentials(async (context, metadata, sp) =>
    {
        var token = await sp.GetRequiredService<ITokenProvider>().GetTokenAsync("api://reporting", context.CancellationToken);
        metadata.Add("Authorization", $"Bearer {token}");
    });

var reply = await client.GetProjectSummaryAsync(new ProjectSummaryRequest { ProjectId = id },
    deadline: DateTime.UtcNow.AddSeconds(2), cancellationToken: ct);             // never call without a deadline
Code
// Kestrel requires a client certificate for the internal gRPC port (mutual TLS).
builder.WebHost.ConfigureKestrel(k => k.ConfigureHttpsDefaults(h => h.ClientCertificateMode = ClientCertificateMode.RequireCertificate));

Because the message is small and the deadline short, a slow reporting service fails fast for the caller, which shows a degraded chart instead of a hung page.

The calling service sends a request over mutual TLS with a bearer token from workload identity and a deadline of two seconds. The receiving service validates the message, passes the caller cancellation token to the database, and answers with a specific status code. Only Unavailable is retried.
The calling service sends a request over mutual TLS with a bearer token from workload identity and a deadline of two seconds. The receiving service validates the message, passes the caller cancellation token to the database, and answers with a specific status code. Only Unavailable is retried.

Real-World Examples

  • Google open-sourced gRPC in 2015, based on Stubby, the internal RPC system it had used between its services for many years. Its broad adoption for microservices comes from that origin: a framework built for very high call volumes between services under one organization's control.
  • In October 2023, the HTTP/2 Rapid Reset vulnerability, CVE-2023-44487, was used for record-setting denial of service attacks against HTTP/2 servers, and vendors including Microsoft released patches for Kestrel and other servers. It shows that protocol-level attacks apply to gRPC endpoints too, and that keeping the runtime patched and putting internal services behind proper network controls matters.
Key TakeawaysUse gRPC for internal service-to-service calls that benefit from strict contracts and performance, and keep REST for browser-facing APIs. Never reuse field numbers, set and propagate deadlines on every call, use specific status codes and retry only safe ones, keep message limits, and secure calls with mutual TLS plus token authorization, with reflection off in production.

Review Questions & Answers

The number is what identifies the field in the binary message, so an old client sending or reading that number would interpret data of a different meaning or type. Reserving retired numbers prevents an accidental reuse from silently corrupting data.

A deadline is an absolute time that travels with the call and applies to downstream calls, so the whole chain stops working once the caller no longer cares. A local timeout at each hop can add up, letting a slow dependency hold resources far longer than the original caller waited.

Browsers cannot use the full gRPC protocol with HTTP/2 trailers, so a translation layer such as gRPC-Web is needed, and it does not support all call types. A REST API through the BFF is simpler and fits browser features like cookies and HTTP caching.

Use TLS everywhere, mutual TLS so both sides prove their identity, and a validated token in call metadata that identifies the calling workload. Also validate every message and keep reflection and public exposure off in production.