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

📚 Interview question

How should cloud-native .NET services talk to each other? Compare synchronous HTTP/JSON, gRPC and asynchronous messaging, explain how you secure the call with service identity and mTLS, and how you decide which style to use for a given interaction.

Covers service-to-service communication for .NET services: HTTP/JSON with IHttpClientFactory and the standard resilience handler, gRPC over HTTP/2, messaging with Azure Service Bus, temporal coupling, service identity with Entra ID tokens and managed identity, mTLS from a service mesh or platform, and how to choose per interaction.

Mid-Level Theory Intermediate cloud-native grpc managed-identity messaging mtls service-to-service

🎯 Key points

  • Synchronous calls create temporal coupling: caller availability = product of dependencies' availability
  • HTTP/JSON: handle transient faults (5xx, 408, 429, network errors) with IHttpClientFactory + AddStandardResilienceHandler
  • gRPC: Protobuf contracts, HTTP/2 multiplexing, deadlines, client/server/bidirectional streaming; needs L7 or client-side balancing
  • Messaging (Service Bus): decouples in time, absorbs bursts; at-least-once, so de-duplicate (MessageId duplicate detection + idempotent consumers) and use an outbox
  • Choose by interaction: query needing an answer now = sync; command or event that can complete later = async
  • Authenticate the caller: Entra ID tokens via managed identity (client credentials), validate audience and app roles
  • mTLS encrypts and authenticates at the transport (mesh or platform); still authorise at the application
  • Propagate W3C trace context across HTTP, gRPC and message headers so one trace spans every style

⏱ 30-second answer

There are three styles. HTTP/JSON is universal and easy to debug; in .NET use IHttpClientFactory with AddStandardResilienceHandler for timeouts, retries and a circuit breaker. gRPC gives strict Protobuf contracts, smaller payloads, streaming and deadlines over HTTP/2, which suits high-volume internal calls, but needs layer 7 load balancing. Messaging (Azure Service Bus) removes temporal coupling: the receiver can be down or slow and the work still completes, at the cost of eventual consistency and idempotent consumers.

I choose per interaction: if the caller needs an answer to continue, call synchronously; if it is a command or an event that can finish later, send a message. For security, each service authenticates with managed identity to get an Entra ID token the callee validates, and mTLS from a mesh or platform encrypts the hop. The trade-off: every synchronous hop multiplies latency and failure.

🗣 Full answer (senior)

How I would answer this in an interview

"I start from the interaction, not the technology. If the caller cannot continue without the answer, say checkout needs a price, that is a synchronous request. If the caller just needs the work to happen eventually, say send a receipt or update a search index, that should be a message. The reason is temporal coupling: with synchronous calls, my availability is roughly the product of my dependencies'. Three services at 99.9% each give me about 99.7%, and their latency adds up on my critical path.

For synchronous calls I default to HTTP/JSON with a typed HttpClient from IHttpClientFactory and AddStandardResilienceHandler, which gives a total timeout, retries with jitter, a circuit breaker and an attempt timeout. I move to gRPC for chatty internal calls or streaming, where Protobuf and HTTP/2 multiplexing cut payloads and connections; the catch is that a long-lived HTTP/2 connection pins to one pod behind a layer 4 balancer, so I need an L7 proxy, a mesh or client-side balancing. For async I use Service Bus queues for commands and topics for events, with the outbox pattern so the database write and the publish cannot diverge, and idempotent consumers because delivery is at least once.

Security is separate from style. Each service has a managed identity; the caller gets an Entra ID token for the callee's app ID URI and the callee validates the audience and an app role such as Orders.Read. Where we run a mesh or Container Apps with mTLS between apps, the hop is encrypted and authenticated too, but I still authorise in the app. The mistake I see is building a chain of five synchronous HTTP calls and then adding retries at every layer, which multiplies load during an outage. Prefer fewer, coarser calls, and make the rest asynchronous."


The three styles

HTTP/JSON gRPC Messaging (Service Bus)
Coupling Temporal + contract Temporal + strict contract Contract only
Contract OpenAPI (optional) .proto (required, code-generated) Message schema (versioned)
Payload JSON text Protobuf binary, typically several times smaller Any, usually JSON
Transport HTTP/1.1 or 2 HTTP/2 (HTTP/3 optional) AMQP 1.0
Streaming SSE / chunked Client, server, bidirectional Natural (continuous flow)
Browser-friendly Yes Only via gRPC-Web or JSON transcoding No
Failure handling Retries, circuit breaker Deadlines, retries Redelivery, dead-letter queue
Best for Public and partner APIs, simple internal queries High-volume internal calls, streaming Commands and events that can complete later

Securing the call

Layer Mechanism What it gives you
Network Internal-only ingress, VNet, private endpoints, network policies Limits who can reach the service at all
Transport TLS; mTLS from Istio/Linkerd or the platform Encryption and workload identity per hop
Application Entra ID token from managed identity, [Authorize(Roles = "Orders.Read")] Which service is calling, and what it may do

Production example

An order flow made five synchronous calls (stock, pricing, payment, email, loyalty) and had p99 of 1.8 s with failures whenever loyalty was slow. Keeping stock, pricing and payment synchronous and publishing an OrderPlaced event for email and loyalty cut p99 to 650 ms, and loyalty outages stopped failing orders altogether.

🔍 What the interviewer is checking

Checks whether the candidate chooses communication style from the interaction's needs and can secure and harden each call in .NET.

Green flags

  • Explains temporal coupling and compounding availability with numbers
  • Knows IHttpClientFactory, the standard resilience handler and when retries are unsafe
  • Knows gRPC's HTTP/2 load-balancing issue and deadlines
  • Uses managed identity and app roles, and treats mTLS as transport identity, not authorisation

Red flags

  • "gRPC is faster so use it everywhere"
  • No idea about idempotency or the outbox with messaging
  • Trusts the internal network as the only security

📚 Learn in depth

1. Why synchronous chains are fragile

client -> gateway -> orders -> pricing -> tax -> rates
          99.95%     99.9%     99.9%    99.9%   99.9%

combined availability ~ 0.9995 * 0.999^4 = 99.55%   (~3.3 hours of failure a month)
latency p99            ~ sum of hops + retries

Each hop also needs a timeout shorter than its caller's, or the caller gives up while work continues downstream (wasted work and duplicate effects). A message breaks the chain: the producer only needs the broker, which is usually the most available component you have.

2. HTTP in .NET: IHttpClientFactory and resilience

IHttpClientFactory pools HttpMessageHandlers (rotated every 2 minutes by default) so you avoid socket exhaustion and stale DNS. Microsoft.Extensions.Http.Resilience's AddStandardResilienceHandler builds a Polly v8 pipeline with: a total request timeout (30 s), retries (3, exponential back-off with jitter, only on transient failures such as 5xx, 408, 429 and network errors), a circuit breaker, and a per-attempt timeout (10 s). With Aspire service defaults this is applied to every client automatically.

Retries are safe only for idempotent operations. For POSTs that create things, send an Idempotency-Key header and have the callee de-duplicate.

3. gRPC in .NET

Grpc.AspNetCore hosts services in Kestrel; Grpc.Net.ClientFactory's AddGrpcClient<T> integrates with IHttpClientFactory. Key mechanics:

  • Deadlines propagate: a client sets deadline, the server sees context.Deadline and context.CancellationToken, and EnableCallContextPropagation passes them to downstream gRPC calls.
  • Load balancing: HTTP/2 multiplexes many calls over one TCP connection, so a layer 4 balancer (a Kubernetes ClusterIP Service) sends all of one client's calls to one pod. Fixes: a headless Service with client-side balancing (dns:/// address and LoadBalancingConfig), an L7 proxy (Envoy, YARP), or a mesh.
  • JSON transcoding (Microsoft.AspNetCore.Grpc.JsonTranscoding) exposes the same service as REST for browsers and partners.

4. Messaging mechanics

  • Queues for commands (one handler), topics and subscriptions for events (many independent subscribers).
  • At-least-once delivery with peek-lock: a crash before CompleteMessageAsync means redelivery. Consumers must be idempotent (store processed message ids, or make the operation naturally idempotent).
  • Outbox: write the business change and an outbox row in one SQL transaction; a relay publishes it. Without it, "save then publish" loses or duplicates messages when one side fails.
  • Ordering: only within a session (SessionId), so design for out-of-order arrival elsewhere.

5. Identity between services

orders-api (managed identity)                     pricing-api (app registration)
   |  ManagedIdentityCredential.GetToken(            |
   |    scope = api://pricing/.default)              |
   |---------------- Bearer eyJ... ----------------->| validate issuer, audience = api://pricing,
                                                     | roles contains "Prices.Read"

The callee exposes app roles; an admin grants the caller's managed identity the role. No shared secrets exist. mTLS (Istio, Linkerd, or Container Apps' optional peer-to-peer encryption) proves which workload opened the connection, but it does not express business permissions, so keep authorisation in the app.

6. Trace context

HttpClient and Grpc.Net.Client propagate W3C traceparent automatically through System.Diagnostics.Activity. Azure Service Bus SDK adds Diagnostic-Id/traceparent to message application properties, so one trace spans the producer, broker and consumer in Application Insights or the Aspire dashboard.

Try it yourself

  1. Call a deliberately flaky endpoint (fails 30% of the time) with and without AddStandardResilienceHandler and compare success rates and p99 latency.
  2. Host a gRPC service with two replicas behind a ClusterIP Service in kind; watch all calls land on one pod, then switch to a headless Service with client-side round-robin.
  3. Measure payload size of the same object as JSON and Protobuf.
  4. Kill a Service Bus consumer mid-message and watch redelivery and DeliveryCount increase.
  5. Get a token with az account get-access-token --resource api://<app-id> and decode it at jwt.ms to see aud and roles.

💻 Code

Three clients side by side: a resilient typed HTTP client that sends a managed-identity token, a gRPC client with a deadline, and an event published to Service Bus.

// Program.cs (.NET 10)
using Azure.Core;
using Azure.Identity;
using Azure.Messaging.ServiceBus;
using System.Net.Http.Headers;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
TokenCredential credential = new DefaultAzureCredential(); // ManagedIdentityCredential in production
builder.Services.AddSingleton(credential);

// 1. Synchronous HTTP: typed client, resilience, and an Entra ID token for the callee.
builder.Services.AddTransient<PricingTokenHandler>();
builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new("https+http://pricing")) // Aspire service discovery name
    .AddHttpMessageHandler<PricingTokenHandler>()
    .AddStandardResilienceHandler(); // total timeout, retries with jitter, circuit breaker, attempt timeout

// 2. Asynchronous: one ServiceBusClient per app (it is thread-safe and holds the AMQP connection).
builder.Services.AddSingleton(_ => new ServiceBusClient(
    builder.Configuration["ServiceBus:Namespace"], credential));

var app = builder.Build();

app.MapPost("/orders", async (CreateOrder cmd, PricingClient pricing, ServiceBusClient bus, CancellationToken ct) =>
{
    // Needs the answer now: synchronous call.
    var price = await pricing.GetPriceAsync(cmd.Sku, ct);

    // Can happen later: publish an event (use an outbox in real code so save + publish cannot diverge).
    await using var sender = bus.CreateSender("order-events");
    var evt = new OrderPlaced(Guid.NewGuid(), cmd.Sku, price);
    await sender.SendMessageAsync(new ServiceBusMessage(JsonSerializer.SerializeToUtf8Bytes(evt))
    {
        MessageId = evt.OrderId.ToString(), // enables duplicate detection on the queue/topic
        Subject = nameof(OrderPlaced)
    }, ct);

    return Results.Accepted($"/orders/{evt.OrderId}", evt);
});

app.Run();

public sealed record CreateOrder(string Sku);
public sealed record OrderPlaced(Guid OrderId, string Sku, decimal Price);

public sealed class PricingClient(HttpClient http)
{
    public async Task<decimal> GetPriceAsync(string sku, CancellationToken ct) =>
        await http.GetFromJsonAsync<decimal>($"/prices/{Uri.EscapeDataString(sku)}", ct);
}

// Adds a bearer token for the pricing API's app ID URI; Azure.Identity caches tokens.
public sealed class PricingTokenHandler(TokenCredential credential, IConfiguration config) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        var token = await credential.GetTokenAsync(new TokenRequestContext([config["Pricing:Scope"]!]), ct);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
        return await base.SendAsync(request, ct);
    }
}
// gRPC client with a deadline (Grpc.Net.ClientFactory); Inventory.InventoryClient is generated from inventory.proto.
builder.Services.AddGrpcClient<Inventory.InventoryClient>(o => o.Address = new("https://inventory"))
    .AddStandardResilienceHandler();

// usage
var reply = await inventory.ReserveAsync(new ReserveRequest { Sku = sku, Quantity = 1 },
    deadline: DateTime.UtcNow.AddSeconds(2), cancellationToken: ct);

⚠ Common mistakes

  • Mistake: Making every interaction a synchronous HTTP call. Why it is wrong: Availability multiplies down the chain and latency adds up, so one slow service fails the whole flow. Instead: Keep only calls whose answer you need now synchronous; send commands and events as messages.
  • Mistake: Retrying at every layer of a call chain. Why it is wrong: Three layers of three retries can send 27 requests to a struggling service. Instead: Retry transient faults at one layer, use a circuit breaker, and set timeouts that shrink down the chain.
  • Mistake: Putting gRPC behind a plain Kubernetes ClusterIP Service. Why it is wrong: HTTP/2 connections are long-lived, so all calls from one client land on one pod. Instead: Use client-side balancing with a headless Service, an L7 proxy or a mesh.
  • Mistake: Saving to the database and then publishing a message without an outbox. Why it is wrong: A crash between the two loses or duplicates the event. Instead: Use the transactional outbox, set a stable MessageId for broker duplicate detection, and make consumers idempotent because duplicate detection only covers a time window.
  • Mistake: Trusting any caller inside the network. Why it is wrong: A compromised pod can then call everything; this is the opposite of zero trust. Instead: Authenticate callers with Entra ID tokens from managed identity and authorise with app roles.
  • Mistake: Assuming mTLS replaces authorisation. Why it is wrong: mTLS proves which workload connected, not whether it may perform this operation on this data. Instead: Use mTLS for transport identity and app roles or policies in the service.
  • Mistake: Losing trace context at the message boundary or in hand-built HTTP calls. Why it is wrong: Traces stop at the broker, so you cannot follow an order from the API through to the consumer that failed. Instead: Use instrumented clients (HttpClient, Grpc.Net.Client, the Service Bus SDK) that carry traceparent, and start consumer activities from the message's trace context.
  • Mistake: Creating a new HttpClient or ServiceBusClient per request. Why it is wrong: It exhausts sockets or opens a new AMQP connection each time. Instead: Use IHttpClientFactory and a singleton ServiceBusClient.

🏛 Senior insight: trade-offs

The question is not "REST or gRPC?" but "where must this flow be synchronous at all?" A senior engineer draws the call graph, marks the critical path, and pushes everything else onto a broker. Then the technology choice is mostly about contracts and tooling: gRPC when both ends are yours and volume is high, HTTP/JSON when partners, browsers or simplicity matter.

Option When it fits Cost When not to
HTTP/JSON Public/partner APIs, low-volume internal queries Larger payloads, looser contracts High-volume chatty internal calls
gRPC Internal, high-volume, streaming, polyglot with codegen L7 balancing, harder debugging, browser support via gRPC-Web Public APIs, simple CRUD
Messaging Commands/events that can finish later, burst absorption Eventual consistency, idempotency, outbox, DLQ operations The user is waiting for the result
Identity option When it fits Cost
Managed identity + app roles Azure-hosted services App registrations to govern
Mesh mTLS (Istio, Linkerd) Many services on AKS, need uniform encryption Mesh to operate
Shared API keys Never between your own services Rotation, leaks

Measure with distributed traces: count synchronous hops on the critical path, and alert on dependency failure rate and p99 per edge.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions gRPC in production Why: Checks they can diagnose HTTP/2, load-balancing and deadline problems with gRPC.
    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.

  2. When: Candidate mentions calling another service by name Why: Checks they understand service discovery with DNS, Kubernetes and Microsoft.Extensions.ServiceDiscovery.
    How to answer

    Instances move, scale and restart, so callers use a logical name and a discovery mechanism maps it to healthy addresses. In server-side discovery the caller hits a stable address, such as a Kubernetes Service (cluster DNS → virtual IP → kube-proxy picks a ready pod) or a load balancer. In client-side discovery the client gets the list of endpoints and balances itself, as gRPC and Microsoft.Extensions.ServiceDiscovery (used by Aspire, URIs like https+http://catalog) can. Common failures: stale DNS in pooled connections, readiness probes that lie, and HTTP/2 or gRPC connections pinned to one pod. The trade-off: server-side is simpler for clients; client-side gives smarter balancing at the cost of logic in every client.

  3. When: Candidate mentions publishing events after saving to the database Why: Checks they can apply the outbox and inbox patterns to avoid lost and duplicate messages.
    How to answer

    These are two bugs with different causes, so I quantify each with reconciliation queries first.

    • Lost messages: usually a dual write. The order is saved, then the publish fails or is never awaited (a fire-and-forget Task.Run killed on deploy, or a swallowed ServiceBusException).
    • Duplicates: usually publisher retries that create a new MessageId each time, which defeats duplicate detection, plus peek-lock redelivery after lock expiry on a consumer that isn't idempotent.

    Fix: an outbox. A SaveChanges interceptor writes domain events to OutboxMessages in the same transaction, and a relay publishes with MessageId = outbox id. Add an inbox on each consumer: (MessageId, Consumer) PK, insert first, treat 2627/2601 as done.

    Roll out the inbox first, because the outbox makes delivery at-least-once. Then backfill missing events, refund double charges, and keep daily reconciliation. The trade-off is extra tables and a relay against guaranteed, deduplicated delivery.

🛠 Real-world problems: how you handle them

Loyalty service outages failing checkouts
Situation
A retail checkout service in .NET on Azure Container Apps called [5] downstream services synchronously per order, handling [40] orders a second at peak during a sale.
Signals
Checkout failure rate jumped to [6%] whenever the loyalty service deployed or slowed; p99 checkout latency reached 1.8 s; the Application Insights application map showed loyalty as the slowest dependency.
Investigation
Used end-to-end transaction traces in Application Insights to list the hops on the critical path and their p99s. Found loyalty points and the confirmation email were called synchronously although the customer never waited for them, and each layer had its own retries, tripling load on loyalty during incidents.
Resolution
Immediate: reduced retries to a single layer with the standard resilience handler and a circuit breaker, so loyalty failures no longer failed checkout. Real fix: checkout writes an `OrderPlaced` event through an outbox to a Service Bus topic; loyalty and email subscribe with idempotent handlers. Stock, pricing and payment stayed synchronous.
Prevention
An architecture rule (ADR) that non-critical side effects are asynchronous, a trace-based dashboard counting synchronous hops on checkout, dead-letter queue alerts, and contract tests for the event schema.

How to tell it (STAR)

**S:** Our checkout called [5] services synchronously, and every time loyalty slowed, checkouts failed: up to [6%] during a sale. **T:** I owned making checkout resilient without a rewrite. **A:** I traced the critical path in Application Insights and showed that two of the five calls were side effects the customer never waited for, and that retries at every layer were tripling load on loyalty. I collapsed retries into one resilience handler with a circuit breaker, then moved loyalty and email onto a Service Bus topic fed by an outbox, with idempotent consumers. **R:** Checkout p99 dropped from 1.8 s to [650 ms], and the next two loyalty outages caused [zero] failed orders.

↩ Usually asked after

More in Cloud-Native Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me