📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is gRPC, and how does it work in ASP.NET Core? Explain protobuf contracts, why it needs HTTP/2, the four call types (unary, server streaming, client streaming, bidirectional), deadlines and cancellation, how it compares with REST, and what gRPC-Web and JSON transcoding are for.

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.

Intermediate Theory Intermediate aspnet-core grpc http2 microservices protobuf

🎯 Key points

  • Contract-first: .proto file compiled by Grpc.Tools into a C# base class (server) and client at build time; the shared contract gives compile-time safety across services and languages
  • Protobuf binary serialisation: compact and fast; field numbers, not names, define the wire format, so never reuse or renumber them
  • Runs over HTTP/2 as the standard transport (multiplexed streams, binary frames, trailers carry grpc-status); HTTP/3 is supported in .NET but still depends on clients and infrastructure
  • Four call types: unary, server streaming, client streaming, bidirectional streaming (IAsyncStreamReader / IServerStreamWriter)
  • Deadlines propagate to the server as ServerCallContext.CancellationToken; set one on every call or a hung call waits forever
  • Errors are StatusCode values via RpcException (InvalidArgument, NotFound, Aborted, Unavailable, DeadlineExceeded), not HTTP status codes
  • Browsers can't do native gRPC: use gRPC-Web (Grpc.AspNetCore.Web) or JSON transcoding to expose REST from the same service
  • Best for internal service-to-service calls and streaming; REST stays better for public, cacheable, browser-first APIs; benchmark serialisation and latency on the real path before switching

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"gRPC is RPC with a strict contract. I write a .proto file with services and messages, reference it in the project with <Protobuf Include=... GrpcServices="Server" />, and Grpc.Tools generates a base class I override on the server and a typed client for callers. On the server it is builder.Services.AddGrpc() and app.MapGrpcService<OrdersService>(). On the client I register it with AddGrpcClient<Orders.OrdersClient>(), which gives me IHttpClientFactory handling, 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 sets deadline: DateTime.UtcNow.AddSeconds(2), that is sent as the grpc-timeout header, and on the server it surfaces as context.CancellationToken, which I pass down to EF Core and HttpClient. With EnableCallContextPropagation the 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 with google.api.http annotations. 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."


The four call types

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 vs REST

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

Browser options

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains field numbers as the wire contract and backward compatibility rules
  • Names all four call types with realistic examples
  • Sets deadlines and passes the server cancellation token down
  • Knows browsers need gRPC-Web or transcoding and why
  • Mentions load-balancing implications of long-lived HTTP/2 connections

Red flags

  • "gRPC is always faster, so use it everywhere"
  • No idea what a deadline is
  • Thinks gRPC works in the browser with fetch

📚 Learn in depth

1. From .proto to C#

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.

2. A unary call on the wire

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.

3. Deadlines and cancellation

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.

4. Connections and load balancing

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.

5. Errors

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.

Try it yourself

  1. Create a service with dotnet new grpc, add a server-streaming method, and call it with grpcurl -plaintext localhost:5000 list after enabling AddGrpcReflection().
  2. Add a deadline of 100 ms and a Task.Delay(500, context.CancellationToken) on the server; observe DeadlineExceeded and the server-side cancellation.
  3. Compare payload sizes: serialise the same object with JsonSerializer and message.ToByteArray().
  4. Add JSON transcoding with google.api.http options and call the same method with curl as REST.
  5. Use BenchmarkDotNet to compare a unary gRPC call with an equivalent Minimal API JSON call on localhost.

💻 Code

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
        }
    }
}

⚠ Common mistakes

  • Mistake: Not setting deadlines. Why it is wrong: A slow or stuck server holds the call, a stream and often the caller's request forever. Instead: Set a deadline on every call (or a default through an interceptor) and pass context.CancellationToken down.
  • Mistake: Changing or reusing protobuf field numbers. Why it is wrong: Old clients decode the bytes as the wrong field, silently corrupting data. Instead: Add new numbers, mark removed ones reserved, and run a breaking-change check (for example buf breaking) in CI.
  • Mistake: Copying .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.
  • Mistake: Creating a new 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.
  • Mistake: Choosing gRPC for a public, browser-facing API. Why it is wrong: Browsers can't call native gRPC, responses can't be cached, and third parties expect REST and OpenAPI. Instead: REST at the edge; gRPC internally, or JSON transcoding if you need both.
  • Mistake: Mapping every failure to 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.
  • Mistake: Putting gRPC behind a layer 4 load balancer and expecting even load. Why it is wrong: Each client's long-lived HTTP/2 connection pins all its calls to one backend. Instead: Use a layer 7 balancer, a mesh, or client-side load balancing.
  • Mistake: Assuming gRPC-Web supports every call type. Why it is wrong: It supports unary and server streaming only. Instead: Use SignalR or WebSockets for two-way browser streaming.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions running gRPC services behind a load balancer. Why: Checks why long-lived HTTP/2 connections pin traffic to one pod with layer 4 balancing.
    How to answer

    A load balancer spreads traffic across healthy instances.

    • Layer 4 (TCP/UDP: Azure Load Balancer, AWS NLB, Kubernetes Services via kube-proxy) picks a backend per connection using IPs and ports. Fast, protocol-agnostic, no HTTP awareness.
    • Layer 7 (HTTP: App Gateway, ALB, Front Door, ingress controllers, Envoy, YARP) picks per request, can route by path/host/header, terminate TLS, retry and add headers.

    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.

  2. When: Candidate mentions HTTP/2 multiplexing or trailers. Why: Checks the HTTP version differences that gRPC depends on.
    How to answer

    HTTP is a request/response protocol: method + path + headers (+ body) in, status + headers (+ body) out.

    • Methods: 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.
    • Status codes: 2xx success, 3xx redirect/not modified, 4xx client error (400, 401 vs 403, 404, 409, 422, 429), 5xx server error (500, and 502/503/504 usually from proxies or gateways).
    • Headers: Content-Type, Accept, Authorization, Cache-Control, ETag/If-None-Match, Retry-After, traceparent.
    • Versions: HTTP/1.1 is text with one request at a time per connection; HTTP/2 is binary with multiplexed streams and header compression on one TCP connection; HTTP/3 does the same over QUIC/UDP, removing TCP head-of-line blocking.
  3. When: Candidate mentions deadlines. Why: Checks broader timeout and cancellation design across calls.
    How to answer

    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.

  4. When: Candidate says gRPC works locally and mentions deploying it behind a load balancer or App Service. Why: Checks practical diagnosis of HTTP/2, load-balancing and deadline problems in production.
    How to answer

    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.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me