Module 1 · Boundaries and Communication · Lesson 2 of 15
REST vs gRPC vs Events: Choosing How Services Communicate
Choose REST/JSON or gRPC when a microservice needs an answer now. Choose messaging for work that can finish later, using commands or events.
The important question is not “Which technology is best?” It is “What must happen before this caller can continue?” You can use different answers in the same system.
This lesson builds on service boundaries and data ownership. We will compare the choices, simulate a failed dependency, and look at long-running HTTP operations, client aggregation, discovery and security.
How do microservices communicate in .NET?
For request/response communication, .NET services use HTTP/JSON clients or gRPC clients. For asynchronous messaging, they use a broker through its SDK or a messaging library. A broker is infrastructure that accepts messages and makes them available to receiving applications.
A synchronous business interaction means the caller needs another service's answer before it can finish the operation. Checkout asking Inventory whether stock is available is one example.
An asynchronous business interaction lets the caller continue before the receiving service finishes its work. An order can be accepted while its confirmation email is still waiting to be sent.
This distinction is not about whether your C# code uses await. Awaiting an HTTP call avoids blocking a thread, but checkout still needs the response. The business dependency remains synchronous.
This creates time coupling, also called temporal coupling: checkout depends on Inventory being available to provide its response.
Start with two questions:
- Does the caller need the result before it can continue?
- Who is calling: a browser, a partner, or another service whose client you control?
The mistake to avoid. Do not call an interaction asynchronous just because it uses await or a queue. If the user still waits for the other service's answer, the time dependency remains.
In an interview, say: “In .NET, I use HTTP/JSON or gRPC clients for request/response, and a broker through an SDK or messaging library for asynchronous communication. I choose per interaction, starting with whether the caller needs the result now.”
When should you choose REST/JSON or gRPC?
Both REST-style HTTP APIs and gRPC can provide an immediate answer. Choose between them using the caller's capabilities and the communication needs.
gRPC is a framework for calling operations on another service through generated clients. Its default message format is Protocol Buffers, or Protobuf, which represents messages in a compact binary format.
A contract describes the operations and messages that services agree to exchange. gRPC uses contract-first development: you define that agreement in a .proto file, then tooling generates client, server and message types.
Streaming means sending a sequence of messages within one call rather than just one request and one response. gRPC supports client streaming, server streaming and two-way streaming.
| Interaction | Good starting choice | Reason and trade-off |
|---|---|---|
| Browser reads a product | REST/JSON | Works naturally with browser HTTP tooling. |
| Partner submits an order | REST/JSON | Broad interoperability; agree on API shape and compatibility. |
| Internal service requests a price | Either | Consider existing tooling, generated contracts and measured performance needs. |
| Internal client exchanges a stream of updates | gRPC | Generated clients and first-class streaming support fit this interaction. |
Browsers cannot call native gRPC directly; browser adaptations exist, but they add integration work. REST/JSON can also have generated clients and use HTTP/2; gRPC's advantage is one consistent contract and code-generation approach. Message size limits, deadlines and HTTP/2 load balancing are in gRPC in .NET.
The mistake to avoid. Do not choose gRPC merely because services are internal. A faster message format does not remove a required service dependency or make a failing service available.
In an interview, say: “REST/JSON is a natural choice for browsers and partners. gRPC suits controlled service clients that benefit from generated contracts, efficient messages or streaming. Both can serve immediate requests; neither removes the cost of waiting for another service.”
When should you use asynchronous commands or events?
If the caller can continue without the result, decide what the message means.
A command asks one service to do something. For example, GenerateInvoice asks the invoicing service to perform work. An asynchronous command defers that work; it does not promise that the work will succeed.
An event announces something that already happened. For example, OrderPlaced tells other services about an accepted order without telling each one what to do.
A consumer is application code that receives and processes messages. A subscription expresses interest in a category of published messages. Delivering an event to several interested subscriptions is called fan-out.
flowchart TD
O["Orders"] -->|"publishes OrderPlaced"| B["Broker"]
B -->|"delivers event"| N["Notifications subscription"]
B -->|"delivers event"| R["Reporting subscription"]
A command has one logical owner, although several running instances of that owner's consumer can share the work. An event can interest zero, one or several subscribers.
Durable messaging means the broker saves accepted messages to disk or replicated storage, so they survive while the receiver is offline or the broker restarts, within the limits of its configuration.
It also supports load levelling: a queue holds a burst of work while consumers process it at a sustainable rate. The queue still needs capacity limits and monitoring.
The costs matter:
- An order may be accepted before Reporting displays it.
- Delivery and recovery can produce duplicate messages.
- Ordering guarantees depend on the broker and configuration. Do not assume all consumers see one global order.
- Debugging becomes harder because acceptance and processing happen at different times, possibly in different processes.
Continue with message contracts, commands and events, then broker choices and ordering.
The mistake to avoid. Messaging is not automatically independent communication. Waiting for a queued reply preserves time coupling, and both sides still depend on the message contract and business meaning.
In an interview, say: “If work can finish later, I send a command to one owner or publish an event for interested subscribers. A durable broker can buffer downtime and bursts, but I must handle delayed consistency, duplicates, ordering and recovery.”
Why can synchronous service chains cause cascading failures?
Consider checkout calling Orders, which calls Inventory, which calls Pricing. Each required step adds waiting time. One slow dependency can leave requests waiting throughout the chain.
A cascading failure happens when trouble in one component causes failures in others. Waiting requests can exhaust connection pools or other capacity. Blocking calls can also exhaust threads. Asynchronous I/O avoids that blocking, but it does not remove all resource limits.
Predict this program's output. It calls checkout while Inventory is offline, then queues a second order as a command and brings Inventory back. Its methods stand in for separate services; there is no network or broker.
using System;
using System.Collections.Generic;
bool inventoryAvailable = false;
var commands = new Queue<string>();
Console.WriteLine("Inventory is offline.");
try
{
Checkout("order-1");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Synchronous checkout failed: {ex.Message}");
}
commands.Enqueue("order-2");
Console.WriteLine($"Deferred order accepted; queued commands: {commands.Count}");
ProcessAvailableCommands();
Console.WriteLine($"Still queued while Inventory is offline: {commands.Count}");
inventoryAvailable = true;
Console.WriteLine("Inventory is online.");
ProcessAvailableCommands();
Console.WriteLine($"Commands remaining: {commands.Count}");
void Checkout(string orderId)
{
PlaceOrder(orderId);
Console.WriteLine($"Checkout completed: {orderId}");
}
void PlaceOrder(string orderId)
{
ReserveStock(orderId);
}
void ReserveStock(string orderId)
{
if (!inventoryAvailable)
throw new InvalidOperationException("Inventory unavailable");
Console.WriteLine($"Stock reserved: {orderId}");
}
void ProcessAvailableCommands()
{
if (!inventoryAvailable)
return;
while (commands.Count > 0)
{
ReserveStock(commands.Peek());
commands.Dequeue();
}
}Inventory is offline. Synchronous checkout failed: Inventory unavailable Deferred order accepted; queued commands: 1 Still queued while Inventory is offline: 1 Inventory is online. Stock reserved: order-2 Commands remaining: 0
Synchronous checkout fails because it needs Inventory's answer now. The queued order is accepted without claiming that stock is reserved, and it waits until Inventory returns: acceptance is separate from completion. Queue<string> is memory-only, so unlike a durable broker it loses its contents in a crash.
Long chains also compound availability risk. If four required services are independently available 99.9% of the time, their combined availability is approximately 0.999 × 0.999 × 0.999 × 0.999, or 99.6%. This simplified calculation assumes independent failures and excludes other dependencies, including the network.
Use several defences together:
- A timeout limits how long a caller waits.
- A bounded retry makes only a limited number of extra attempts for failures that may be temporary. Retrying side effects needs protection against performing them twice.
- A circuit breaker temporarily stops calls to a dependency that keeps failing, rather than spending capacity on likely failures. It starts closed, letting calls pass. After too many failures, it opens, so calls fail immediately. After a break, it becomes half-open and lets a test call through. Success closes it again; failure opens it again.
- A bulkhead isolates capacity, such as separate concurrency limits for different dependencies, so one slow dependency cannot consume everything.
Excessive retries can multiply traffic during an outage. Give the whole operation one deadline, for example 2 seconds. Each call in the chain uses only the time that is left, instead of starting its own full timeout.
In .NET, AddStandardResilienceHandler from Microsoft.Extensions.Http.Resilience adds a rate limiter, a total request timeout, retries, a circuit breaker and a per-attempt timeout to an HttpClient.
Timeouts, retries and resilience with Polly covers these defences in .NET.
The mistake to avoid. Do not retry at every hop. If each of three callers in a chain retries a failed call three times, one user request can reach the last service 64 times (4 × 4 × 4).
In an interview, say: “Slow dependencies can accumulate waiting requests and exhaust capacity. I use shared deadlines, bounded retries and bulkheads. A circuit breaker passes calls when closed, fails fast when open, and probes when half-open before closing again. In .NET, Microsoft.Extensions.Http.Resilience provides timeouts, retries and circuit breakers for HttpClient.”
How should HTTP expose long-running work?
Suppose generating an export takes several minutes. Keeping the original HTTP request open makes completion depend on that connection lasting long enough.
Instead, accept the work and return 202 Accepted with a status URL. The client can poll, meaning send periodic requests to check progress or completion.
For example:
| Step | Request or response |
|---|---|
| Submit | Client sends POST /exports. |
| Accept | API returns 202 Accepted with Location: /operations/export-42. |
| Check | Client sends GET /operations/export-42. |
| Pending | Status response says the operation is still running. |
| Finish | Status response reports success with a result URL, or failure with error information. |
Define pending, successful and failed outcomes. A Retry-After response header can tell clients how long to wait before checking again.
Before the API returns 202, it should save the job somewhere durable, such as a database table or a durable queue. Otherwise, it could say “accepted” and then lose the work. Protect the status URL so only authorized callers can inspect that operation.
The mistake to avoid. A successful status check does not mean the work has finished. The Asynchronous Request-Reply pattern returns HTTP 200 for a successful status check even while work is in progress. The client must inspect the reported operation state.
In an interview, say: “For long-running HTTP work, I return 202 Accepted with a status URL and let the client poll. I define pending, successful and failed outcomes instead of holding the original request open. Acceptance is not completion.”
What else do interviewers ask about service calls?
- BFF or gateway aggregation: one screen-shaped response instead of five mobile round trips; the intermediary adds latency and is one more dependency (see Gateway Aggregation and Backends for Frontends).
- Service discovery: call a logical name such as
inventory, resolved by Kubernetes DNS or .NET service discovery with Aspire (formerly .NET Aspire), never a hardcoded address. - Service-to-service security: a name or network location is not an identity; the receiving service authenticates the calling workload (a token or mutual TLS) and authorizes the action (see ASP.NET Core authentication and service-to-service tokens).
In an interview, say: “I use logical names resolved through platform DNS or service discovery, rather than hardcoded instance addresses. Separately, I authenticate the calling workload, commonly with tokens or mutual TLS, and authorize its actions at the receiving service.”
Check yourself
A checkout service sends a request through a durable queue, then waits for Inventory's reply before responding to the user. Which statement is correct?
Show answer
Correct answer: D
The queue can buffer a message, but checkout still needs Inventory to answer before the user's deadline. Durability is not a guarantee of timely processing or business success.
An export usually takes several minutes, and the caller does not need the result immediately. Which HTTP design is the best starting point?
Show answer
Correct answer: B
Separate acceptance from completion. The status URL lets the client check the outcome without keeping the original request open.
Going deeper
Durability is a configured guarantee, not a property of every queue-shaped API. Check what survives a broker restart, when a send is acknowledged, and what happens if a consumer fails after doing the work but before acknowledging receipt.
Updating a service's database and publishing a message are separate actions that can fail independently. This is the dual-write problem. Start with delivery guarantees and the dual-write problem before implementing the outbox.
For diagnosis, distributed tracing connects related operations across services into one view, as long as HTTP calls and messages carry the trace context. Continue with distributed tracing across HTTP and messages.
Finally, distinguish mandatory business work from optional follow-up. Deferring payment or stock reservation requires an explicit pending state and a failure outcome. Moving the work onto a queue does not make those business requirements disappear.
Sources
- Overview for gRPC on .NET: gRPC definition, Protocol Buffers, contract-first tooling, generated clients and streaming.
- Compare gRPC services with HTTP APIs: REST/JSON versus gRPC trade-offs, browser limitations, code generation, streaming and HTTP/2.
- Communication in a microservice architecture - .NET: Communication styles, distinction between asynchronous code and business interaction, synchronous chains and multiple receivers.
- Asynchronous Request-Reply Pattern: HTTP 202 acceptance, polling, status URLs and separating long-running work from the original request.
- Gateway Aggregation Pattern: Reducing client round trips, intermediary availability and capacity costs, partial responses and resilience.
- Backends for Frontends pattern: Client-specific back ends and their distinction from general gateway aggregation.
- Service discovery in .NET: Logical service names, platform DNS, configuration-based resolution and Aspire integration.
- Bulkhead pattern: Resource isolation and preventing dependency failures from consuming shared capacity.
- Build resilient HTTP apps: Key development patterns: Timeouts, bounded retries, circuit breakers and HTTP resilience implementation.
- Queue-Based Load Leveling pattern: Buffering bursts, separating producers and consumers, queue capacity and processing-rate limitations.
- Overview of ASP.NET Core authentication: Authentication of callers and the distinction between establishing identity and authorizing access.
- Configure certificate authentication in ASP.NET Core: Certificate-based service authentication and mutual TLS implementation reference.
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 1 Dec 2026 ·