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

📚 Interview question

Your mobile app makes 25 API calls to render one screen, and some of your services call each other dozens of times per request. How do you fix chatty APIs? Compare batching, aggregate endpoints, a backend for frontend and gRPC streaming, and explain how you decide.

Covers diagnosing chatty client and service-to-service communication and reducing round trips with aggregate endpoints, batch APIs, BFFs, gRPC streaming, data ownership changes and caching, with the trade-offs of each.

Senior Architecture Advanced api-performance architecture bff chatty-apis grpc performance

🎯 Key points

  • Latency ≈ sequential round trips × RTT: 25 calls × 80 ms mobile RTT dwarfs server time
  • Find it with Application Insights end-to-end transactions / distributed traces: count calls per operation and their critical path
  • First remove unnecessary calls and question the boundary: services designed around business capabilities rarely need to chat
  • Aggregate endpoint or BFF shapes data per screen; parallel fan-out server-side over low-RTT links
  • Batch endpoints (GetByIds, POST /batch) remove N+1 calls to downstream APIs
  • gRPC (HTTP/2, Protobuf) and streaming lower per-call cost but don't reduce the number of calls
  • Resilience in fan-out: per-dependency timeouts, retries with jitter only for idempotent calls, circuit breakers, partial responses
  • Prove and keep it: calls per request/screen and client p95 dashboards with alerts on regressions

⏱ 30-second answer

Chattiness turns latency into round trips × RTT: 25 sequential calls over an 80 ms mobile link is two seconds before any server work. I first measure it with distributed traces (Application Insights end-to-end transactions) to count calls per operation and find the critical path. Then:

  • Client to server: an aggregate endpoint or a backend for frontend (BFF) that returns what one screen needs, fanning out server-side where RTT is sub-millisecond.
  • Service to service: batch APIs instead of N+1 calls, gRPC with streaming for high-volume links, and caching or replicating read data via events.

If two services always call each other, the real fix may be the boundary. The trade-off: fewer round trips cost coupling, ownership and more complex failure handling.

🗣 Full answer (senior)

How I would answer this in an interview

"Chatty APIs are a latency multiplier. Each call pays a network round trip, and on mobile that's 50 to 150 ms, so 25 calls, even partly parallel, cost seconds while each endpoint looks fast in isolation. Between services the RTT is usually lower, around a millisecond inside one Azure region, but that's not a given: calls that cross regions, go through gateways, sidecars or private endpoints, or hit a congested or throttled dependency can cost tens of milliseconds each. N+1 call patterns multiply that by the size of the data, and every extra hop adds a failure point, serialisation cost and a dependency that can slow everyone down.

I start by measuring: in Application Insights I open end-to-end transactions for the slow screen or request, count the calls and see which are sequential. For example, at [company] our [mobile home screen] made [25] calls, and the order service called the catalogue service once per order line, [up to 200] times a request. First we removed calls that weren't needed at all. For the client side, we introduced a BFF owned by the mobile team: one endpoint per screen that fans out in parallel inside Azure, with per-dependency timeouts, a circuit breaker and partial responses. For the service side, we added a GetProductsByIds batch endpoint and cached product data with HybridCache, then later moved to consuming product-changed events so the order service kept its own read model. [Screen p95 went from 2.8 s to 700 ms and downstream calls per order request from about 200 to 1.]

The mistake I see is reaching for gRPC as if a faster protocol fixes too many calls. gRPC shrinks each call, but 200 small calls are still 200 round trips. The other mistake is batching as a band-aid when the real problem is that two services split one business capability between them. The question I ask is: should these services be talking this much at all, and who owns the composition? Fix the number of calls first, then the cost of each."


Order of attack

  1. Remove calls nobody needs (duplicate fetches, data the screen doesn't show).
  2. Question the boundary: if two services always call each other, align them to one business capability, replicate read data, or merge them.
  3. Compose close to the data: aggregate endpoint or BFF.
  4. Batch the remaining N+1 calls.
  5. Make each call cheaper: gRPC, caching, edge/CDN for cacheable reads.

Options

Option What it is Fits Watch out for
Aggregate endpoint One endpoint returning a screen's data Single client, few screens Couples API to UI
BFF A backend per client type, owned by that client team Several client types with different needs Duplication, another deployable
Batch API GET /products?ids=1,2,3 or POST /batch N+1 service calls Payload limits, partial failures
gRPC (+ streaming) Protobuf over HTTP/2 High-volume internal traffic Browser support (gRPC-Web), L4 load balancing
GraphQL Client picks fields and joins Many clients, varied queries Query cost control, caching
Edge/CDN caching Cache public, cacheable GETs near users Reference data, catalogues Personalised data, invalidation
Replicate data Local read model fed by events Data read far more than changed Eventual consistency
Merge services One service where boundaries were wrong Services that always change together Organisational change

Resilience in composition

  • Per-dependency timeouts shorter than the caller's budget; optional sections degrade to empty.
  • Retries with exponential backoff and jitter only for idempotent calls; circuit breakers so a failing dependency is skipped quickly (AddStandardResilienceHandler).
  • Propagate the CancellationToken so abandoned requests stop downstream work.

Production example

After the BFF and the batch endpoint, the mobile home screen went from 25 calls to 3, p95 on 4G fell from 2.8 s to 700 ms, and catalogue service traffic dropped 85%, which also let us scale it down from [8] to [3] instances.

🔍 What the interviewer is checking

Checks whether the candidate can diagnose chatty communication, choose between composition patterns with clear trade-offs, and recognise when chattiness signals a boundary problem.

Green flags

  • Quantifies round trips × RTT and uses traces to count calls
  • Distinguishes client-to-server from service-to-service chattiness
  • Mentions timeouts, partial responses and ownership for BFFs
  • Considers data replication or boundary changes, not only protocols

Red flags

  • "Use gRPC" as the whole answer
  • A single aggregation layer for all clients with business logic in it
  • No mention of measuring before and after

📚 Learn in depth

1. Why chattiness hurts

sequential:   [call1 80ms][call2 80ms][call3 80ms] ... x25  = ~2,000 ms
parallel(6):  [6 calls][6 calls][6 calls][6 calls][1]        = ~400 ms + queueing
BFF:          client --80ms--> BFF --(25 calls, ~1-5 ms each, parallel)--> services
              total ~ 80 ms + slowest dependency

The network cost is paid where RTT is high. Moving fan-out from the phone to a BFF inside Azure Australia East replaces 25 × 80 ms with 1 × 80 ms + in-region calls. In-region calls are not free: a service mesh sidecar, an API gateway, TLS, a cross-region hop or a dependency under load can each add milliseconds to tens of milliseconds.

2. Finding it

  • Application Insights: end-to-end transaction view and the application map show dependency counts per request; a KQL query over dependencies grouped by operation_Id gives calls per request.
  • OpenTelemetry traces: spans per trace; look for repeated spans with the same name in a loop (the service-to-service N+1).
  • Client telemetry: calls per screen from the mobile SDK or browser RUM.
dependencies
| where timestamp > ago(1h) and cloud_RoleName == "orders-api"
| summarize calls = count() by operation_Id, target
| summarize p50 = percentile(calls, 50), p95 = percentile(calls, 95) by target

3. Keeping it fixed in production

Chattiness creeps back one feature at a time, so make it a monitored number:

  • Instrument every service with OpenTelemetry (AddOpenTelemetry().WithTracing(...) exporting to Azure Monitor) so HTTP, gRPC and SQL dependencies become spans automatically.
  • Turn the KQL above into a scheduled log alert or workbook: alert when p95 dependency calls per request for a key operation rises above a threshold (e.g. > 5) or client p95 for a key screen breaches its SLO.
  • Add a custom metric for calls per screen from the BFF or mobile SDK, and show it next to latency on the team dashboard.
  • Log structured events with operation names and correlation IDs so traces, logs and metrics join up during an incident.
  • Review the application map after each release; a new edge between services is a design conversation.

4. Aggregate endpoints and BFFs

A BFF is a thin service per client type (mobile, web, partner) that composes downstream calls into screen-shaped responses. Rules that keep it healthy:

  • Owned by the client team; no business rules, only composition and shaping.
  • Parallel fan-out with Task.WhenAll, per-dependency timeouts, and partial responses (show the screen without recommendations if that service is slow).
  • Resilience via AddStandardResilienceHandler (timeouts, retries with jitter, circuit breaker).

5. Batch APIs

Replace foreach (line) await catalogue.GetProduct(id) with one GetProductsByIds(ids) call. Design points: maximum batch size, deduplicated IDs, result keyed by ID, and explicit handling of missing items. Server side, the batch maps to a single WHERE Id IN (...) or a TVP, not a loop.

6. gRPC and streaming

Protobuf is compact and gRPC multiplexes on HTTP/2, so per-call overhead drops. Server streaming sends many results over one call; client and bidirectional streaming suit telemetry and chat-like flows. Constraints: browsers need gRPC-Web, L4 load balancers pin HTTP/2 connections to one pod (use L7 or client-side balancing), and contracts need versioning discipline.

7. Fixing the boundary

If order processing needs product data on every request, either cache it (HybridCache with tags), or have the order service own a read model fed by ProductChanged events through Azure Service Bus. If two services must update together synchronously all the time, they probably split one business capability and belong in one service or one module of a modular monolith.

Try it yourself

  1. Run the KQL above against an Application Insights resource and find the request type with the most dependency calls.
  2. Build a small BFF endpoint that fans out to three stub services with Task.WhenAll and a 300 ms timeout each.
  3. Replace a per-item downstream call loop with a batch endpoint and compare dependency counts and p95 in a k6 test.
  4. Inject 80 ms latency with tc netem and compare 25 sequential calls with one aggregate call.
  5. Create a log alert on dependency calls per request for one operation and trigger it with a deliberately chatty build.

💻 Code

A BFF endpoint that composes a screen with parallel fan-out, timeouts and a partial response:

// Program.cs in Mobile.Bff
using Microsoft.Extensions.Http.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<OrdersClient>(c => c.BaseAddress = new Uri("https://orders.internal"))
    .AddStandardResilienceHandler();
builder.Services.AddHttpClient<CatalogueClient>(c => c.BaseAddress = new Uri("https://catalogue.internal"))
    .AddStandardResilienceHandler();
builder.Services.AddHttpClient<RecommendationsClient>(c => c.BaseAddress = new Uri("https://recs.internal"))
    .AddStandardResilienceHandler();

var app = builder.Build();

app.MapGet("/screens/home/{customerId:int}", async (
    int customerId, OrdersClient orders, CatalogueClient catalogue,
    RecommendationsClient recs, CancellationToken ct) =>
{
    var ordersTask = orders.GetRecentAsync(customerId, ct);
    var recsTask = WithTimeout(recs.GetForAsync(customerId, ct), TimeSpan.FromMilliseconds(300), []);

    var recent = await ordersTask;
    // One batch call instead of one call per order line (avoids N+1 across services).
    var productIds = recent.SelectMany(o => o.ProductIds).Distinct().ToArray();
    var products = await catalogue.GetByIdsAsync(productIds, ct);

    return Results.Ok(new HomeScreen(recent, products, await recsTask)); // recs may be empty: partial response
});

app.Run();

static async Task<T> WithTimeout<T>(Task<T> task, TimeSpan timeout, T fallback)
{
    var finished = await Task.WhenAny(task, Task.Delay(timeout));
    return finished == task ? await task : fallback; // optional data must not hold up the screen
}

public sealed record OrderSummary(int Id, IReadOnlyList<int> ProductIds);
public sealed record Product(int Id, string Name, decimal Price);
public sealed record HomeScreen(IReadOnlyList<OrderSummary> RecentOrders,
    IReadOnlyList<Product> Products, IReadOnlyList<Product> Recommended);

public sealed class OrdersClient(HttpClient http)
{
    public async Task<IReadOnlyList<OrderSummary>> GetRecentAsync(int customerId, CancellationToken ct) =>
        await http.GetFromJsonAsync<List<OrderSummary>>($"/customers/{customerId}/orders?pageSize=5", ct) ?? [];
}

public sealed class CatalogueClient(HttpClient http)
{
    public async Task<IReadOnlyList<Product>> GetByIdsAsync(int[] ids, CancellationToken ct) =>
        ids.Length == 0 ? [] :
        await http.GetFromJsonAsync<List<Product>>($"/products?ids={string.Join(',', ids)}", ct) ?? [];
}

public sealed class RecommendationsClient(HttpClient http)
{
    public async Task<IReadOnlyList<Product>> GetForAsync(int customerId, CancellationToken ct) =>
        await http.GetFromJsonAsync<List<Product>>($"/customers/{customerId}/recommendations", ct) ?? [];
}

⚠ Common mistakes

  • Mistake: Optimising without measuring, e.g. building a BFF because "mobile is slow". Why it is wrong: the slowness may be one slow query, not call count. Instead: count calls per screen and per request in traces first.
  • Mistake: Micro-optimising per-call overhead (serialiser, protocol) on a cold flow. Why it is wrong: it saves microseconds on something rarely used. Instead: target the hottest, most chatty operations.
  • Mistake: Switching to gRPC to fix 200 calls per request. Why it is wrong: faster calls are still 200 round trips and 200 failure points. Instead: first ask why the calls exist and whether the service boundaries are right, remove or redesign the interaction, batch what remains, and only then optimise per-call cost.
  • Mistake: Batching as a band-aid over a wrong boundary. Why it is wrong: two services that split one business capability keep needing each other, so the chattiness returns in new forms. Instead: align services to business capabilities, replicate read data via events, or merge them.
  • Mistake: A single generic aggregation service for every client. Why it is wrong: it becomes a shared bottleneck and coupling point. Instead: a BFF per client type, owned by that team.
  • Mistake: Fan-out with no timeouts or partial responses. Why it is wrong: the slowest dependency sets the screen's latency and failures cascade. Instead: per-dependency timeouts, optional sections, circuit breakers and resilience handlers.
  • Mistake: Putting business rules in the BFF. Why it is wrong: logic gets duplicated across BFFs and drifts. Instead: BFFs compose and shape; domain services decide.
  • Mistake: Assuming service-to-service calls are free because they are "inside the data centre". Why it is wrong: gateways, sidecars, cross-region hops and throttled dependencies add real latency. Instead: measure dependency durations per hop.

🏛 Senior insight: trade-offs

Chattiness is usually a symptom of either a UI that grew one call at a time or service boundaries drawn around nouns instead of business capabilities. A senior fixes the immediate latency with composition close to the data (BFF, batch endpoints) but also asks whether the boundary is right, because every remote call is a latency, failure and versioning cost forever.

Option When it fits Cost When not to
BFF Distinct client types and teams Another service to run One client, a few screens: an aggregate endpoint is enough
Batch endpoint N+1 service calls API design work Calls that are rare or already single
gRPC streaming High-volume internal flows Tooling, L7 balancing Public browser APIs
Event-fed read model Read-heavy, slowly changing data Eventual consistency, infrastructure Data that must be strongly consistent
Merge services Always change and call together Org and deployment change Truly independent scaling or ownership needs

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions RTT or latency vs bandwidth Why: Checks their grasp of how round trips and chatty communication affect latency.
    How to answer
    • Latency: how long one thing takes, such as one round trip or one request (ms). Bounded by distance (light in fibre travels roughly 200 km per ms) plus queuing and processing.
    • Bandwidth: the maximum data rate of a link (Mbit/s, Gbit/s). The width of the pipe.
    • Throughput: what you actually achieve (requests/s or MB/s). Limited by bandwidth, latency, windows, concurrency and the slowest component.

    For most APIs, latency × number of round trips dominates, not bandwidth. A request that makes 50 sequential database calls at 2 ms RTT spends 100 ms on the network; move the database to another region at 30 ms RTT and it spends 1.5 s. Fix it by reducing round trips (batching, joins, fewer chatty calls), moving compute near data, caching, and parallelising independent calls.

  2. When: Candidate suggests putting aggregation in an API gateway Why: Checks they know what belongs in a gateway versus a BFF and the risks of logic in the gateway.
    How to answer

    An API gateway is a single entry point in front of your services that routes requests and applies cross-cutting concerns: TLS termination, token validation, rate limiting and quotas, request ids, IP filtering, header rewriting and sometimes caching. Azure API Management is a managed gateway with XML policies, products and subscriptions, a developer portal and analytics; YARP is a .NET reverse-proxy library you host yourself and extend in C#. A backend-for-frontend (BFF) is a gateway per client (web, mobile) that aggregates and shapes data for that client. The danger is a smart gateway: business rules and orchestration in policies become untested, hard-to-version logic owned by nobody. Keep the gateway thin and services authoritative.

  3. When: Candidate proposes a BFF for the mobile app Why: Checks their judgement on when a BFF is worth its operational cost.
    How to answer

    Maybe. A mobile BFF owned by the app team lets the app's contract evolve with the app and isolates it from changes the web needs, which removes a lot of coordination. It can also aggregate several backend calls into one mobile-shaped response, cutting round trips and payload on slow mobile networks.

    But it is another service to host, secure, monitor and be on call for, it adds a hop and a second contract to version, and it moves rather than removes compatibility: the BFF still has to serve every supported app version. I would introduce one when web and mobile needs genuinely diverge or the app team wants to own its API, not just to dodge one incident.

🛠 Real-world problems: how you handle them

Mobile home screen and order service drowning in round trips
Situation
A [retail] platform with a mobile app and [6] microservices on Azure Container Apps in Australia East. The home screen made [25] API calls; the order service called the catalogue service once per order line.
Signals
App-side home screen p95 of [2.8 s] on 4G; catalogue service CPU at 70% and scaled to [8] replicas; Application Insights showing order requests with up to [200] dependency calls; occasional cascading timeouts when catalogue slowed.
Investigation
Mobile telemetry showed calls per screen and that many were sequential because of data dependencies. Application Insights end-to-end transactions and a KQL query over `dependencies` grouped by `operation_Id` showed the per-line catalogue calls. A k6 test with injected 80 ms RTT reproduced the client-side latency.
Resolution
Immediate: a `GetProductsByIds` batch endpoint and HybridCache in the order service cut catalogue calls per request to one or zero. Next: a mobile BFF with screen-shaped endpoints, parallel fan-out, 300 ms timeouts on optional sections and partial responses. Later: the order service consumed `ProductChanged` events to keep its own product read model.
Prevention
Dashboards for dependency calls per request and calls per screen; an architecture review checklist item 'no per-item remote calls in loops'; k6 tests with latency injection in CI for key screens; an ADR describing BFF ownership.

How to tell it (STAR)

**S:** At [company], our mobile home screen took nearly three seconds on 4G and the catalogue service needed eight replicas, although each endpoint looked fast on its own. **T:** As [senior engineer on the platform team], I was asked to make the screen fast and cut the infrastructure cost. **A:** I used Application Insights traces and mobile telemetry to show the screen made 25 calls, and the order service called catalogue once per line, up to 200 times. I proposed a batch endpoint with caching for the service-side N+1, and a mobile-owned BFF with parallel fan-out, timeouts and partial responses for the screen. Later we replaced the cache with an event-fed read model. **R:** Home screen p95 fell to [700 ms], catalogue calls per order went from about 200 to [1], and we scaled catalogue from [8] to [3] replicas.

↩ Usually asked after

More in API Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me