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

📚 Interview question

Your gRPC calls work locally but fail in production: behind the load balancer or on Azure App Service some calls return Unavailable or 'protocol error', one pod gets all the traffic, and under load you see a lot of DeadlineExceeded. How do you diagnose and fix these HTTP/2 and timeout problems?

Diagnosing gRPC failures in production: HTTP/2 not supported end to end, TLS and ALPN, proxies dropping trailers, layer 4 load balancing pinning connections, keep-alive and idle timeouts, the HTTP/2 stream limit, deadline budgets and propagation, with the tools to find each.

Mid-Level Debugging Intermediate aspnet-core debugging grpc http2 load-balancing timeouts

🎯 Key points

  • gRPC needs HTTP/2 end to end; a proxy that downgrades to HTTP/1.1 or drops trailers causes protocol errors and missing grpc-status
  • With TLS, HTTP/2 is negotiated by ALPN on an Http1AndHttp2 endpoint; without TLS (h2c) there is no negotiation, so Kestrel's docs require the endpoint's Protocols to be Http2
  • Layer 4 load balancers pin each long-lived HTTP/2 connection to one pod: use L7 balancing, a mesh, or client-side round robin with a headless service
  • Idle and keep-alive timeouts on load balancers kill quiet connections: set KeepAlivePingDelay/Timeout on SocketsHttpHandler
  • Default limit of 100 concurrent streams per connection: EnableMultipleHttp2Connections avoids queuing that looks like DeadlineExceeded
  • Deadline budgets: one deadline set at the edge and propagated (EnableCallContextPropagation), not fixed, inconsistent timeouts per hop
  • Diagnose with client and server gRPC logging (Grpc category at Debug), grpcurl per hop, Kestrel connection logs, client-vs-server span duration and the gRPC EventCounters
  • Retry only Unavailable (and idempotent DeadlineExceeded) with a service config retry policy and jitter; check mTLS certificates and health probes when calls fail on only some pods

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I split the symptoms, because they have different causes. First, the protocol errors. gRPC requires HTTP/2 all the way, and it needs trailers, because that is where grpc-status lives. So I check every hop. Is the load balancer or ingress speaking HTTP/2 to the backend, or is it terminating TLS and forwarding HTTP/1.1? Is Kestrel listening with Protocols = Http2 if the hop to it is plain text? Without TLS there is no ALPN to negotiate HTTP/2, so the endpoint must be HTTP/2-only. I reproduce with grpcurl from inside the cluster, pod to pod, then through the ingress, and the hop where it breaks is the culprit. On Azure, App Service supports gRPC on Linux with HTTP/2 enabled and the HTTP/2 proxy setting turned on, and Container Apps needs the ingress transport set to http2.

Second, one pod gets everything. That is the classic layer 4 problem: a Kubernetes ClusterIP service balances TCP connections, and a gRPC client opens one HTTP/2 connection and multiplexes every call on it. So whichever pod it connected to gets 100% of that client's traffic, and new pods added by the autoscaler get nothing. The fixes are an HTTP/2-aware proxy (ingress-nginx with backend-protocol: GRPC, Envoy, a mesh like Linkerd or Istio), or client-side balancing. For client-side balancing, Grpc.Net.Client resolves a headless service with dns:/// and uses RoundRobinConfig.

Third, DeadlineExceeded under load. For example, at [company] our [pricing] service showed DeadlineExceeded at [only 400 calls per second], although server-side handler time was under [10 ms]. The gap was queueing: the client multiplexed everything on one connection, and the server allowed 100 concurrent streams, so calls waited for a free stream. EnableMultipleHttp2Connections = true fixed most of it. We also found every hop had its own fixed 2-second timeout, so a three-hop chain could take 6 seconds while the caller had given up after 2. Propagating the deadline with EnableCallContextPropagation fixed that. [Result: DeadlineExceeded fell from X% to Y%.]"


Symptom to cause

Symptom Likely cause How to confirm Fix
StatusCode.Internal: "protocol error", HTTP_1_1_REQUIRED Hop downgrades to HTTP/1.1 grpcurl per hop; proxy logs show HTTP/1.1 upstream HTTP/2 to backend (backend-protocol: GRPC, Container Apps transport: http2)
Unavailable, "Bad gRPC response. Response did not have a grpc-status" Trailers dropped or a proxy error page returned Client Debug logs show a 502 or HTML body Configure the proxy for gRPC; check health of the backend
Works over TLS, fails in plain text No ALPN, endpoint not HTTP/2-only Kestrel logs show HTTP/1.1 ListenAnyIP(5001, o => o.Protocols = HttpProtocols.Http2)
One pod hot, others idle L4 balancing of long-lived connections Per-pod request rate in metrics L7 proxy, mesh, or client-side round robin
Calls fail after idle periods LB idle timeout closes the connection silently Failures after quiet minutes KeepAlivePingDelay and KeepAlivePingTimeout
DeadlineExceeded under load, fast handlers Stream limit queuing, ThreadPool starvation Client vs server duration gap, current-calls counter EnableMultipleHttp2Connections, fix blocking code
DeadlineExceeded deep in a call chain Fixed per-hop timeouts Distributed trace shows work continuing after caller gave up Propagate deadlines

Production example

In a [three-service checkout chain] on [AKS], moving from a ClusterIP service to client-side round robin over a headless service spread load across all [six] pods instead of [one], and fixing the stream limit plus deadline propagation reduced DeadlineExceeded from [3.1%] to [under 0.1%] at peak.

🔍 What the interviewer is checking

Checks whether the candidate can systematically diagnose gRPC failures in real infrastructure: HTTP/2 end to end, load balancing of long-lived connections, stream limits and deadline budgets.

Green flags

  • Separates protocol errors, load imbalance and timeouts into different causes
  • Knows h2c needs an HTTP/2-only endpoint and that trailers matter
  • Explains why L4 balancing pins gRPC connections and gives three fixes
  • Mentions the stream limit, EnableMultipleHttp2Connections and deadline propagation
  • Uses grpcurl, gRPC Debug logs, counters and traces

Red flags

  • "Increase the timeout" as the main fix
  • Doesn't know gRPC requires HTTP/2
  • Retries everything blindly

📚 Learn in depth

1. Where HTTP/2 can break

caller (Grpc.Net.Client)
   │  h2 over TLS (ALPN "h2")
   ▼
load balancer / ingress / App Service front end
   │  must be h2 to the backend too, and must forward trailers
   ▼
Kestrel  (Protocols: Http2 or Http1AndHttp2 with TLS)
   ▼
gRPC service

If any hop terminates TLS and talks HTTP/1.1 upstream, gRPC fails. Plain-text HTTP/2 ("h2c") has no negotiation, so both sides must assume HTTP/2 ("prior knowledge"): in Kestrel that means an Http2-only endpoint, and in .NET clients http:// addresses work with Grpc.Net.Client because it uses prior knowledge.

2. Why layer 4 balancing pins traffic

client ── one TCP+TLS connection, 1,000 multiplexed calls/s ──▶ kube-proxy (L4) ──▶ pod A
                                                                             pod B (idle)
                                                                             pod C (idle)

kube-proxy picks a pod per connection, not per request. HTTP/1.1 clients open many connections, so load spreads; gRPC opens one. Options:

  • L7 proxy: ingress-nginx (nginx.ingress.kubernetes.io/backend-protocol: "GRPC"), Envoy, Azure Application Gateway for Containers.
  • Service mesh: Linkerd or Istio balance per request transparently.
  • Client-side: headless service (clusterIP: None), dns:///orders.default.svc.cluster.local:5001, LoadBalancingConfigs = { new RoundRobinConfig() }, with re-resolution so new pods are found.

3. Stream limits and queuing

Kestrel's Http2.MaxStreamsPerConnection defaults to 100. When a client has 100 calls in flight on one connection, call 101 waits in the client until a stream frees up. That wait counts against the deadline, so the client reports DeadlineExceeded while the server's handler timings look perfect. SocketsHttpHandler.EnableMultipleHttp2Connections = true lets the client open more connections when the limit is reached.

4. Deadline budgets

without propagation:   A (2 s) ──▶ B (2 s) ──▶ C (2 s)    caller gave up at 2 s, B and C keep working until 6 s
with propagation:      A (2 s) ──▶ B (remaining 1.9 s) ──▶ C (remaining 1.7 s)    everyone stops at 2 s

EnableCallContextPropagation() on AddGrpcClient copies the incoming deadline and cancellation token to outgoing calls made within the same request.

5. Tools

Tool What it shows
Logging:LogLevel:Grpc = Debug (client and server) Status codes, deadlines, protocol errors, retries
grpcurl with reflection Whether each hop speaks gRPC
dotnet-counters monitor Grpc.AspNetCore.Server Grpc.Net.Client current-calls, calls-failed, calls-deadline-exceeded
Application Insights / OpenTelemetry traces Client vs server duration, the hop where time goes
Kestrel connection logs (Microsoft.AspNetCore.Server.Kestrel.Connections) Protocol negotiated, resets

Try it yourself

  1. Run a gRPC service in kind or minikube with three replicas behind a ClusterIP service, generate load from one client, and graph per-pod request counts. Switch to a headless service with client-side round robin and compare.
  2. Configure Kestrel with an Http1-only endpoint and call it from Grpc.Net.Client to see the protocol error.
  3. Set MaxStreamsPerConnection = 10 on the server, fire 200 concurrent calls with a 200 ms deadline, and watch DeadlineExceeded; then enable multiple connections.
  4. Build a three-hop chain with and without EnableCallContextPropagation and look at the trace in Jaeger or Application Insights.
  5. Watch dotnet-counters while you run each experiment.

💻 Code

Client and server settings that fix the common production problems.

// Server: Program.cs (.NET 10). Plain-text HTTP/2 behind a mesh or ingress that terminates TLS.
using Microsoft.AspNetCore.Server.Kestrel.Core;

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(k =>
{
    // h2c has no ALPN, so the endpoint must be HTTP/2-only ("prior knowledge").
    k.ListenAnyIP(5001, o => o.Protocols = HttpProtocols.Http2);
    k.ListenAnyIP(8080, o => o.Protocols = HttpProtocols.Http1); // health probes stay on HTTP/1.1
    k.Limits.Http2.MaxStreamsPerConnection = 100;                // default; know it when you see queuing
});

builder.Services.AddGrpc(o => o.EnableDetailedErrors = builder.Environment.IsDevelopment());
builder.Services.AddGrpcReflection(); // lets grpcurl list services (restrict to internal networks)
builder.Services.AddHealthChecks();

var app = builder.Build();
app.MapGrpcService<OrdersService>();
app.MapGrpcReflectionService();
app.MapHealthChecks("/healthz");
app.Run();
// Client: resilient channel settings (.NET 10)
using Grpc.Core;
using Grpc.Net.Client.Balancer;
using Grpc.Net.Client.Configuration;

builder.Services.AddSingleton<ResolverFactory>(sp => new DnsResolverFactory(refreshInterval: TimeSpan.FromSeconds(30)));

builder.Services
    .AddGrpcClient<Orders.OrdersClient>(o =>
        // Headless Kubernetes service: DNS returns every pod IP, so the client can balance per call.
        o.Address = new Uri("dns:///orders-headless.shop.svc.cluster.local:5001"))
    .ConfigureChannel(c =>
    {
        c.Credentials = ChannelCredentials.Insecure; // TLS is handled by the mesh in this example
        c.ServiceConfig = new ServiceConfig
        {
            LoadBalancingConfigs = { new RoundRobinConfig() },
            MethodConfigs =
            {
                new MethodConfig
                {
                    Names = { MethodName.Default },
                    RetryPolicy = new RetryPolicy
                    {
                        MaxAttempts = 3,
                        InitialBackoff = TimeSpan.FromMilliseconds(100),
                        MaxBackoff = TimeSpan.FromSeconds(1),
                        BackoffMultiplier = 2,
                        RetryableStatusCodes = { StatusCode.Unavailable } // never retry InvalidArgument etc.
                    }
                }
            }
        };
    })
    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
    {
        EnableMultipleHttp2Connections = true,           // avoid queuing at the 100-stream limit
        KeepAlivePingDelay = TimeSpan.FromSeconds(60),    // keep idle connections alive through LBs
        KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
        PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan
    })
    .EnableCallContextPropagation(); // pass the caller's remaining deadline downstream
# ingress-nginx: speak gRPC (HTTP/2) to the backend instead of HTTP/1.1
metadata:
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: "GRPC"

⚠ Common mistakes

  • Mistake: Assuming the load balancer speaks HTTP/2 to the backend because the client uses HTTP/2. Why it is wrong: Many proxies terminate TLS and forward HTTP/1.1 upstream, which breaks gRPC. Instead: Configure HTTP/2 or gRPC as the backend protocol and test each hop with grpcurl.
  • Mistake: Exposing plain-text gRPC on an Http1AndHttp2 endpoint. Why it is wrong: Without TLS there is no ALPN to choose the protocol, and Kestrel's documentation states that an HTTP/2 endpoint without TLS must have Protocols set to Http2; on a mixed plain-text endpoint, HTTP/2 prior-knowledge clients aren't reliably served. Instead: Use an Http2-only port for h2c and a separate HTTP/1.1 port for health probes, or use TLS so ALPN can serve both on one port.
  • Mistake: Relying on a ClusterIP service for gRPC load balancing. Why it is wrong: It balances connections, and gRPC uses one long-lived connection, so one pod gets all the traffic. Instead: L7 proxy, service mesh, or client-side round robin with a headless service.
  • Mistake: Reading DeadlineExceeded as "the server is slow". Why it is wrong: The time often goes to queuing for a stream or a starved ThreadPool. Instead: Compare client and server durations in traces and check current-calls and the stream limit.
  • Mistake: Fixed, inconsistent timeouts at each hop (for example 2 s at the edge, 5 s in the middle, 30 s at the database). Why it is wrong: Downstream work keeps running after the caller has given up, wasting capacity during incidents, and inner timeouts longer than outer ones can never help. Instead: Set one deadline at the edge from the user-facing budget, propagate it with EnableCallContextPropagation, and make any local timeouts shorter than the remaining budget.
  • Mistake: Retrying every failed call, including DeadlineExceeded on non-idempotent methods. Why it is wrong: Retries amplify load in an incident and can duplicate side effects. Instead: Retry Unavailable with backoff and jitter; make writes idempotent before retrying them.
  • Mistake: No keep-alive pings. Why it is wrong: Load balancers drop idle connections silently and the next call fails. Instead: Set KeepAlivePingDelay below the idle timeout.
  • Mistake: Forgetting mTLS and certificates when only some pods fail. Why it is wrong: An expired or mismatched certificate on one replica, or a mesh sidecar not yet ready, shows up as Unavailable on a fraction of calls. Instead: Check certificate expiry and sidecar readiness, and alert on certificate expiry.

🏛 Senior insight: trade-offs

Most gRPC production incidents aren't about gRPC code; they're about the network assumptions HTTP/2 breaks. Long-lived multiplexed connections are great for latency and terrible for naive load balancers, and a binary protocol with trailers is fragile through older proxies. I make the platform decision once (mesh or L7 ingress or client-side balancing), write it down in an ADR, and give every team a shared client configuration with deadlines, keep-alives and a retry policy.

Load-balancing option When it fits Cost When not to
L7 ingress (nginx, Envoy) North-south traffic into the cluster Ingress config per service East-west calls between many services
Service mesh (Linkerd, Istio) Many internal gRPC services, mTLS wanted Mesh operations, sidecar resources Small systems with two services
Client-side round robin Few clients, headless services, no mesh Every client must be configured Polyglot clients you don't control
L4 only Only with many clients each holding their own connection None A few high-volume clients

Making it proactive, not reactive:

Practice What it catches
A shared AddPlatformGrpcClient() extension with deadlines, keep-alive, retry policy and multiple connections Teams forgetting one of the settings
A smoke test after each deployment that calls every service through the real ingress with grpcurl HTTP/2 or trailer breakage at a proxy
Per-pod request-rate panels plus an alert when one pod takes more than twice its share Connection pinning
Dashboards of the calls-deadline-exceeded rate per method and of client-minus-server duration Queuing and starvation before users notice
Load tests at 1.5x peak in staging, with an HPA scale-out during the test New pods not receiving traffic
A game day that kills a pod and expires a certificate Retry, reconnect and mTLS behaviour

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions one pod getting all the traffic. Why: Checks layer 4 versus layer 7 load balancing in depth.
    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 DeadlineExceeded with fast handler timings. Why: Checks whether they would consider ThreadPool starvation as the cause of queuing.
    How to answer

    ThreadPool starvation happens when pool threads are blocked faster than the pool can add new ones, so queued work (requests, continuations, timers) waits. Symptoms: latency rises sharply while CPU stays low, the pool queue length grows, thread count climbs slowly, health checks time out and Kestrel logs heartbeat warnings mentioning possible starvation. I confirm it with dotnet-counters (queue length and thread count), then take dotnet-stack snapshots or a dump to see what the threads are blocked on, usually .Result, .Wait(), synchronous I/O or locks. The fix is to make that code asynchronous; raising SetMinThreads only buys time.

  3. When: Candidate mentions MaxStreamsPerConnection or Kestrel HTTP/2 settings. Why: Checks Kestrel limits and tuning knowledge.
    How to answer

    Kestrel's KestrelServerLimits are mostly protective limits against resource exhaustion and denial of service, not speed settings. MaxConcurrentConnections and MaxConcurrentUpgradedConnections are unlimited (null) by default; MaxRequestBodySize defaults to about 28.6 MB (30,000,000 bytes) and should be overridden per endpoint for uploads; header limits (32 KB total, 100 headers), RequestHeadersTimeout (30 s) and MinRequestBodyDataRate (240 bytes/s) protect against slow-client attacks; KeepAliveTimeout (130 s) must outlive the proxy's idle timeout. HTTP/2 allows 100 streams per connection with flow-control windows; HTTP/3 must be enabled explicitly and needs HTTPS, UDP open on the port and libmsquic on Linux. In practice, Kestrel is rarely the bottleneck: throughput is limited by downstream I/O, ThreadPool starvation, CPU in serialisation, allocations/GC and connection pools. Tighten limits for safety, but measure with dotnet-counters before tuning for speed.

🛠 Real-world problems: how you handle them

gRPC traffic pinned to one pod and DeadlineExceeded under peak load
Situation
A [checkout] service on [AKS] called a [pricing] service over gRPC about [1,500] times per second at peak. Pricing ran [six] replicas behind a `ClusterIP` service. A [Black Friday] load test was a week away.
Signals
Grafana showed one pricing pod at 95% CPU while the other five were nearly idle. The checkout service logged `StatusCode.DeadlineExceeded` on [3%] of pricing calls, while the pricing server's own handler duration p99 was [8 ms]. HPA added pods that received no traffic.
Investigation
Compared client-side and server-side spans in Application Insights: client duration was [250 ms], server duration [8 ms], so time was lost before the handler ran. `dotnet-counters` on the checkout pods showed `current-calls` stuck near 100, matching Kestrel's default `MaxStreamsPerConnection`. `kubectl get endpoints` and per-pod metrics confirmed one HTTP/2 connection per checkout pod, each pinned to a single pricing pod by kube-proxy.
Resolution
Immediate: restarted checkout pods to re-spread connections, which bought a few hours. Real fix: switched to a headless service with Grpc.Net.Client client-side round robin and DNS re-resolution, set `EnableMultipleHttp2Connections = true` and keep-alive pings, and added `EnableCallContextPropagation` so the checkout deadline flowed down. Retries limited to `Unavailable` with backoff.
Prevention
A shared gRPC client extension method used by every service with these defaults. A load test in the pipeline that asserts per-pod request distribution within 20%. Alerts on the `calls-deadline-exceeded` rate per method and on client-minus-server latency. An ADR recording the load-balancing decision, to revisit if the team adopts a service mesh.

How to tell it (STAR)

**S:** Our checkout service called pricing over gRPC about [1,500] times a second, and a load test before [Black Friday] showed one pricing pod at 95% CPU and [3%] DeadlineExceeded, while the other pods sat idle. **T:** I had [a week] to make it handle [2x] peak. **A:** I compared client and server spans and saw [250 ms] on the client but [8 ms] in the handler, so calls were queuing. Counters showed about 100 calls in flight per connection, the HTTP/2 stream limit, and every checkout pod held one connection pinned to one pricing pod by the layer 4 service. I moved us to a headless service with client-side round robin, enabled multiple HTTP/2 connections and keep-alives, and propagated deadlines. **R:** Load spread evenly across all [six] pods, DeadlineExceeded dropped to [under 0.1%], and we ran [Black Friday] at [X] calls per second without incident.

↩ Usually asked after

More in Real-Time and Special APIs

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me