loading experience

ASP.NET Core

gRPC in .NET: fast communication between services

Contracts defined with Protocol Buffers, compact binary messages and streaming: when gRPC beats REST.

gRPC in .NET: fast communication between services

gRPC is a remote procedure call framework based on HTTP/2 and Protocol Buffers. Messages are binary, compact and fast to serialise, and the contract between client and server is defined in a shared file.

Often both are used: REST outside, gRPC between services.
Often both are used: REST outside, gRPC between services.

The contract

syntax = "proto3";
option csharp_namespace = "Warehouse";

service Stock {
  rpc Availability (AvailabilityRequest) returns (AvailabilityReply);
  rpc Movements (MovementsRequest) returns (stream Movement);
}

message AvailabilityRequest { string code = 1; }
message AvailabilityReply { string code = 1; int32 quantity = 2; }
message MovementsRequest { string code = 1; }
message Movement { string date = 1; int32 delta = 2; }

C# classes for client and server are generated automatically from the .proto file.

The server

public class StockService(IWarehouse warehouse) : Stock.StockBase
{
    public override async Task<AvailabilityReply> Availability(
        AvailabilityRequest req, ServerCallContext ctx)
    {
        var q = await warehouse.QuantityAsync(req.Code, ctx.CancellationToken);
        return new AvailabilityReply { Code = req.Code, Quantity = q };
    }
}

builder.Services.AddGrpc();
app.MapGrpcService<StockService>();

When to choose it

  • Communication between internal services, where performance and strict contracts matter.
  • Streaming data in one or both directions.
  • Clients in different languages: the same .proto file generates code for many languages.

When to stay with REST

For public APIs consumed by browsers and third parties, REST with JSON remains easier to explore and integrate. Browsers do not speak native gRPC: you need gRPC-Web or a gateway. Many architectures use both: REST towards the outside, gRPC between internal services.

Comments (0)

No comments yet.

Leave a comment