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

📚 Interview question

How do you choose between REST, gRPC, GraphQL and asynchronous messaging for an API? Compare them on contract, performance, browser and tooling support, caching, coupling and failure handling, and give examples of where each fits in a .NET system on Azure.

Choosing an API style: REST over HTTP, gRPC, GraphQL and asynchronous messaging compared on contracts, performance, client support, caching, coupling and failure semantics, with typical placements in a .NET 10 system on Azure.

Mid-Level Theory Intermediate architecture graphql grpc messaging rest web-api

🎯 Key points

  • REST: resources over HTTP/JSON, universal client support, HTTP caching, best default for public and partner APIs
  • gRPC: protobuf contract, HTTP/2, binary and streaming, strong codegen; great service-to-service, poor browser support (needs gRPC-Web or JSON transcoding)
  • GraphQL: client-shaped queries over one endpoint, solves over/under-fetching for varied UIs; costs: HTTP caching, N+1 resolvers, query cost limits (Hot Chocolate in .NET)
  • Messaging (Azure Service Bus, Event Grid, Event Hubs): temporal decoupling, load levelling, at-least-once delivery requiring idempotent consumers
  • .NET messaging tooling: Azure.Messaging.ServiceBus / EventGrid / EventHubs SDKs, MassTransit or NServiceBus for sagas, retries and outbox, Aspire for local emulators
  • Synchronous styles couple availability; messaging couples on message schema and needs eventual consistency in the UX
  • Mix them: REST/GraphQL at the edge (BFF), gRPC or REST between services, messaging for events and long work
  • Decide on client types, latency/throughput needs, team skills, operability and long-term maintenance rather than fashion

⏱ 30-second answer

REST is the default for public and partner APIs: universal client support, HTTP caching and simple tooling. gRPC suits internal service-to-service calls: protobuf contracts, HTTP/2, binary payloads and streaming, but weak browser support. GraphQL fits varied front ends that need different shapes of the same data, at the cost of HTTP caching, resolver N+1 problems and query cost limits. Asynchronous messaging (Azure Service Bus, Event Grid) is for decoupling in time: events, long-running work and load levelling, with at-least-once delivery and eventual consistency.

Most real systems mix them: REST or GraphQL at the edge, gRPC or REST between services, messaging for events. The trade-off is always coupling and simplicity vs efficiency and flexibility.

🗣 Full answer (senior)

How I would answer this in an interview

"I choose by who the client is and what kind of coupling I can accept. REST over HTTP and JSON is my default for anything public or partner-facing: every language and tool speaks it, it works through every proxy and CDN, GET responses can be cached, and OpenAPI gives us docs and SDKs. gRPC is what I reach for between internal services when calls are chatty or latency-sensitive: the protobuf contract generates strongly typed clients in .NET, payloads are compact, HTTP/2 multiplexes calls, and it supports streaming and deadlines natively. The catch is browsers, which need gRPC-Web or JSON transcoding, and load balancers that must understand HTTP/2.

GraphQL solves a different problem: many front ends that each want a different shape of data. The client asks for exactly the fields it needs in one round trip. In .NET that's usually Hot Chocolate. The costs are real: everything is a POST to one endpoint so HTTP caching mostly goes away, naive resolvers cause N+1 queries unless you use DataLoaders, and you need depth and cost limits so a client can't send a query that brings down the database. Messaging, with Azure Service Bus for commands or Event Grid for events, is different again: the sender doesn't wait and doesn't need the receiver to be up. That gives resilience and load levelling, but delivery is at least once, so consumers must be idempotent, and the UI has to cope with eventual consistency.

The mistake I see is picking one style for everything, like gRPC for a public API because it's faster, or synchronous HTTP chains across five services where an event would remove the coupling. In a typical Azure system I'd put REST, or GraphQL behind a BFF, at the edge, use gRPC or REST between services, and publish events through Service Bus. I choose the style per boundary, not per company."


Comparison

REST gRPC GraphQL Messaging
Contract OpenAPI (optional) .proto (required) Schema (required) Message schema (often informal)
Transport HTTP/1.1, 2, 3 HTTP/2 (HTTP/3 possible) HTTP, usually POST AMQP, HTTPS to broker
Payload JSON Protobuf binary JSON Any (JSON, Avro)
Browser support Native gRPC-Web / transcoding Native Via backend only
HTTP caching Yes (GET) No Hard (persisted queries help) N/A
Streaming SSE, chunked Native, bidirectional Subscriptions Native (streams of messages)
Coupling Synchronous, availability Synchronous, contract Synchronous, schema Temporal decoupling
Failure model Status codes, retries Status codes, deadlines Partial errors in 200 Retries, dead-letter queues
.NET tooling ASP.NET Core, OpenAPI Grpc.AspNetCore Hot Chocolate Azure.Messaging.ServiceBus, MassTransit

Where each fits

Boundary Typical choice Why
Public / partner API REST Reach, caching, docs
Mobile and web BFF with varied screens REST BFF or GraphQL Fewer round trips, client-shaped data
Internal high-volume service calls gRPC Latency, contracts, streaming
"Something happened" notifications Event Grid / Service Bus topics Many subscribers, decoupled
Long-running or bursty work Service Bus queue Load levelling, retries, DLQ

Production example

An [order platform] made a synchronous REST call chain (orders -> stock -> pricing -> notifications) for every checkout. When notifications slowed down, checkout p99 rose to [~4 s]. Publishing an OrderPlaced event to Service Bus for notifications, and moving stock and pricing to gRPC, cut checkout p99 to [~600 ms] and made notification outages invisible to customers.

🔍 What the interviewer is checking

Checks that the candidate can compare API styles on real trade-offs (performance, but also coupling, maintainability, operability and fit with the team's skills) and place each at the right boundary instead of following fashion.

Green flags

  • Chooses per boundary (edge vs internal vs async)
  • Names concrete costs: gRPC browser and load-balancer issues, GraphQL caching and N+1, messaging at-least-once
  • Talks about coupling and availability, not just speed
  • Weighs long-term maintenance and what the team can operate and debug
  • Mentions .NET tooling (Grpc.AspNetCore, Hot Chocolate, Azure.Messaging.ServiceBus, MassTransit)

Red flags

  • "gRPC is always better because it's faster"
  • Can't explain what GraphQL costs
  • Treats messaging as exactly-once or as a drop-in for request/response

📚 Learn in depth

1. Coupling is the real axis

Synchronous (REST, gRPC, GraphQL)
  Caller ---request---> Callee     caller blocks; callee must be up
         <--response---

Asynchronous (messaging)
  Producer --msg--> [Broker] --msg--> Consumer   consumer can be down; work happens later

Synchronous chains multiply availability: five services at 99.9% each give roughly 99.5% for the chain. Messaging breaks that chain but introduces eventual consistency and at-least-once delivery.

2. Why gRPC is fast

  • Protobuf encodes fields as tagged varints: typically several times smaller than JSON and cheaper to parse.
  • HTTP/2 multiplexes many calls over one connection, with header compression (HPACK).
  • Generated clients avoid reflection-based serialisation.

Trade-offs: binary payloads are hard to inspect with curl; L4 load balancers pin long-lived HTTP/2 connections to one backend, so you need L7 balancing or client-side load balancing; browsers can't use raw gRPC.

3. GraphQL's execution model

query { order(id: 42) { id total customer { name } lines { sku product { name } } } }
  -> resolver order(42)
     -> resolver customer      (1 query)
     -> resolver lines         (1 query)
        -> resolver product x N  (N queries unless batched by a DataLoader)

Hot Chocolate provides DataLoaders, projections onto EF Core IQueryable, cost analysis and depth limits. Persisted queries (allow-listed query hashes) restore some cacheability and stop arbitrary queries in production.

4. Messaging semantics

  • Queues (Service Bus): competing consumers, one handler per message; good for commands and work.
  • Topics/subscriptions: publish once, many subscribers; good for domain events.
  • Event Grid: push-based event routing with filtering; Event Hubs: high-throughput streams with partitions and replay.
  • Delivery is at least once: use the inbox pattern or natural idempotency; failures go to dead-letter queues after max delivery count.

5. A decision checklist

  1. Who are the clients (browsers, partners, internal services)?
  2. Must the caller wait for the result?
  3. Latency and throughput targets per call?
  4. How varied are the data shapes clients need?
  5. Team skills and operational tooling (tracing, debugging, gateways)?

Try it yourself

  1. Implement the same "get order" as a REST endpoint and a gRPC service; benchmark payload size and latency with BenchmarkDotNet or ghz.
  2. Add Hot Chocolate to a sample, write a nested query, and watch the SQL with EF Core logging before and after adding a DataLoader.
  3. Publish an event to a Service Bus queue with the consumer stopped, then start it and observe delivery; throw in the handler to see retries and dead-lettering.
  4. Call a gRPC service from a browser and see it fail, then enable gRPC JSON transcoding.

💻 Code

The same capability exposed three ways in one .NET 10 service: REST for partners, gRPC for internal callers, and an event for asynchronous consumers.

// Program.cs (.NET 10)
// Packages: Grpc.AspNetCore, Azure.Messaging.ServiceBus, Azure.Identity
using Azure.Identity;
using Azure.Messaging.ServiceBus;
using Grpc.Core;
using OrdersApi.Grpc;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGrpc();
builder.Services.AddSingleton(_ => new ServiceBusClient(builder.Configuration["ServiceBus:Namespace"], new DefaultAzureCredential()));
builder.Services.AddSingleton(sp => sp.GetRequiredService<ServiceBusClient>().CreateSender("order-events"));
var app = builder.Build();

// REST: public and partner clients, cacheable reads.
app.MapGet("/orders/{id:int}", (int id, HttpResponse res) =>
{
    res.Headers.CacheControl = "private, max-age=15";
    return Results.Ok(new OrderDto(id, "Pending", 120.50m));
});

// Command over REST that also publishes an event for async consumers (email, analytics).
app.MapPost("/orders/{id:int}/submission", async (int id, ServiceBusSender sender, CancellationToken ct) =>
{
    // In production write this to an outbox in the same transaction as the state change.
    var msg = new ServiceBusMessage(BinaryData.FromObjectAsJson(new OrderSubmitted(id, DateTimeOffset.UtcNow)))
    {
        MessageId = $"order-submitted-{id}",   // stable id: duplicate detection can drop resends
        Subject = nameof(OrderSubmitted)
    };
    await sender.SendMessageAsync(msg, ct);
    return Results.Accepted($"/orders/{id}");
});

// gRPC: internal, typed, low-latency calls (base class generated from orders.proto).
app.MapGrpcService<OrdersGrpcService>();

app.Run();

public sealed record OrderDto(int Id, string Status, decimal Total);
public sealed record OrderSubmitted(int OrderId, DateTimeOffset At);

public sealed class OrdersGrpcService : Orders.OrdersBase
{
    public override Task<OrderReply> GetOrder(GetOrderRequest request, ServerCallContext context) =>
        Task.FromResult(new OrderReply { Id = request.Id, Status = "Pending" });
}
// Protos/orders.proto  (in the .csproj: <Protobuf Include="Protos\orders.proto" GrpcServices="Server" />)
syntax = "proto3";
option csharp_namespace = "OrdersApi.Grpc";
service Orders { rpc GetOrder (GetOrderRequest) returns (OrderReply); }
message GetOrderRequest { int32 id = 1; }
message OrderReply { int32 id = 1; string status = 2; }

⚠ Common mistakes

  • Mistake: Using gRPC for a public or browser-facing API because it's faster. Why it is wrong: Browsers can't call it directly and partners expect HTTP/JSON. Instead: REST at the edge; gRPC internally, or JSON transcoding if you need both.
  • Mistake: Adopting GraphQL without DataLoaders or cost limits. Why it is wrong: Nested queries cause N+1 database calls and a single query can overload the system. Instead: Use DataLoaders, depth and cost limits, and persisted queries in production.
  • Mistake: Long synchronous call chains across services. Why it is wrong: Latency adds up and availability multiplies down. Instead: Use events for work that doesn't need to finish before responding.
  • Mistake: Treating messaging as exactly-once. Why it is wrong: Brokers deliver at least once: a consumer that crashes after doing the work but before completing the message gets it again when the lock expires, and producers that retry a send create copies. Service Bus duplicate detection only drops identical MessageIds sent within its window, and only on the send side. Instead: Make consumers idempotent: record processed message ids in an inbox table in the same transaction as the business change (unique key on message id + consumer), design handlers as upserts or state checks ("if already shipped, do nothing"), set stable MessageIds on send, and route poison messages to the dead-letter queue after max delivery count.
  • Mistake: Returning errors inside 200 responses in GraphQL and assuming monitoring will see them. Why it is wrong: HTTP-level dashboards show 100% success. Instead: Instrument GraphQL errors separately (Hot Chocolate diagnostics, OpenTelemetry).
  • Mistake: Choosing one style for the whole company. Why it is wrong: Each boundary has different clients and coupling needs. Instead: Decide per boundary and record it in an ADR.

🏛 Senior insight: trade-offs

The style matters less than the boundary it sits on. I choose based on who the clients are, whether the caller needs the answer now, and what the team can operate: gRPC with poor HTTP/2 load balancing, or GraphQL without cost limits, are worse than plain REST. I also keep the domain logic independent of the transport so a capability can be exposed as REST and gRPC (or later as an event) without rewriting it.

How I'd measure: per-boundary p95/p99 latency and payload sizes, the depth of synchronous call chains in distributed traces, dead-letter counts for messaging, and GraphQL query cost distributions.

Style When it fits Cost When not
REST Public, partner, CRUD-ish, cacheable reads Over/under-fetching, chattiness Very high-volume internal calls
gRPC Internal calls, streaming, polyglot typed contracts HTTP/2 infra, debugging binary Browsers and third parties
GraphQL Many front ends with varied data needs Caching, N+1, query governance Simple APIs with one client
Messaging Events, long work, load levelling, decoupling Eventual consistency, idempotency, ops Caller needs an immediate answer

🔗 Follow-ups the interviewer may ask

  1. When: Candidate recommends gRPC between services Why: Checks gRPC internals: protobuf, HTTP/2, call types, deadlines
    How to 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.

  2. When: Candidate mentions eventual consistency with messaging Why: Checks how they handle eventual consistency and separate read models
    How to answer

    CQRS splits the model that changes state (commands) from the model that reads it (queries). It grows out of Meyer's CQS (a method either changes state or returns data), applied to whole models.

    • Write side: aggregates with invariants, loaded through repositories, committed by the unit of work.
    • Read side: flat DTOs shaped per screen, projected with Select/AsNoTracking or Dapper.

    There are levels. Separate handlers on one database is cheap and often enough. Denormalised read tables updated in the same transaction stay consistent. A separate read store fed by events scales reads but is eventually consistent, so the UI needs read-your-writes or "processing" states.

    CQRS doesn't need MediatR or event sourcing. It's overkill for CRUD where reads and writes have the same shape. The trade-off is optimised, simple models on each side against more moving parts and, at the top level, stale reads.

  3. When: Candidate mentions publishing events after saving data Why: Checks reliable event publishing alongside a database write
    How to answer

    The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.

    The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.

    A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.

🛠 Real-world problems: how you handle them

Synchronous checkout chain slowed by a notification service
Situation
An [order platform] on Azure handled [~50k] checkouts a day. Checkout made sequential REST calls to stock, pricing and notifications before responding. A peak sale was [two weeks] away.
Signals
Checkout p99 rose from [~700 ms to ~4 s] whenever the email provider slowed; Application Insights showed the notifications dependency dominating the end-to-end transaction; timeouts in notifications produced 500s at checkout.
Investigation
Application Insights end-to-end transaction view and the application map showed the call chain and per-dependency durations. Distributed traces confirmed that notifications didn't need to complete before the customer saw the confirmation. Load tests with Azure Load Testing reproduced the p99 spike by slowing a stub email provider.
Resolution
Immediate: a 2 s timeout and fallback on the notification call. Real fix: checkout writes an `OrderPlaced` event to an outbox in the same transaction, a relay publishes it to a Service Bus topic, and notifications consume it with an idempotent handler. Stock and pricing moved to gRPC with deadlines for lower internal latency.
Prevention
An ADR listing which boundaries are synchronous and why; a trace-based alert when synchronous chain depth exceeds 3; dead-letter queue alerts; load tests in the release pipeline with dependency slowdowns injected.

How to tell it (STAR)

**S:** At [company], checkout called stock, pricing and notifications synchronously, and every time the email provider slowed down, checkout p99 jumped to about four seconds. **T:** With a big sale [two weeks] away, I had to make checkout independent of non-critical services. **A:** I used the Application Insights application map to show notifications didn't need to finish before we responded, added a short timeout as a stop-gap, then moved notifications to an `OrderPlaced` event on a Service Bus topic via an outbox, with an idempotent consumer. I also moved stock and pricing to gRPC with deadlines. **R:** Checkout p99 dropped to [~600 ms], an email provider outage during the sale had no customer impact, and [no] duplicate emails were sent thanks to the idempotent consumer.

↩ Usually asked after

More in REST

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me