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.
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.
"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
HttpClientfromIHttpClientFactoryandAddStandardResilienceHandler, 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."
| 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 |
| 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 |
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.
Checks whether the candidate chooses communication style from the interaction's needs and can secure and harden each call in .NET.
Green flags
IHttpClientFactory, the standard resilience handler and when retries are unsafeRed flags
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.
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.
Grpc.AspNetCore hosts services in Kestrel; Grpc.Net.ClientFactory's AddGrpcClient<T> integrates with IHttpClientFactory. Key mechanics:
deadline, the server sees context.Deadline and context.CancellationToken, and EnableCallContextPropagation passes them to downstream gRPC calls.dns:/// address and LoadBalancingConfig), an L7 proxy (Envoy, YARP), or a mesh.Microsoft.AspNetCore.Grpc.JsonTranscoding) exposes the same service as REST for browsers and partners.CompleteMessageAsync means redelivery. Consumers must be idempotent (store processed message ids, or make the operation naturally idempotent).SessionId), so design for out-of-order arrival elsewhere.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.
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.
AddStandardResilienceHandler and compare success rates and p99 latency.DeliveryCount increase.az account get-access-token --resource api://<app-id> and decode it at jwt.ms to see aud and roles.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);
MessageId for broker duplicate detection, and make consumers idempotent because duplicate detection only covers a time window.HttpClient, Grpc.Net.Client, the Service Bus SDK) that carry traceparent, and start consumer activities from the message's trace context.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.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.
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.
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.
These are two bugs with different causes, so I quantify each with reconciliation queries first.
Task.Run killed on deploy, or a swallowed ServiceBusException).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.
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.
Last updated 23 Nov 2026.