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

📚 Interview question

What does an API gateway do, and how do you decide what belongs in it? Compare Azure API Management and YARP, explain the cross-cutting concerns a gateway should own, where a backend-for-frontend (BFF) fits, and the signs that too much logic has moved into the gateway.

API gateways in .NET and Azure: Azure API Management vs YARP, the cross-cutting concerns a gateway should own, the BFF pattern, and the anti-pattern of business logic in the gateway.

Mid-Level Theory Intermediate api-gateway architecture azure-api-management bff web-api yarp

🎯 Key points

  • A gateway is a single entry point that routes requests to backends and applies cross-cutting policies
  • Core gateway concerns: TLS, routing, token validation, rate limits and quotas, request ids, IP filtering, monitoring and analytics
  • Request-level transforms (path rewrite, adding trace headers) are fine; domain logic is not
  • Azure API Management: managed, policies in XML, developer portal, subscriptions and products, analytics
  • YARP: a .NET reverse proxy library you host and extend in C#, config-driven routes and clusters
  • BFF: a gateway per client type that shapes and aggregates data for one front end, owned by that team
  • Anti-pattern: business rules, orchestration or heavy transformation in gateway policies
  • Gateway is a single point of failure and an extra hop; services still authorise requests themselves

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"A gateway gives clients one front door. It terminates TLS, routes /orders to the orders service and /catalogue to the catalogue service, and applies the things every API needs but no service should reimplement: validating JWTs, rate limits and quotas per client, request ids for tracing, IP allow-lists, and header normalisation. Behind it, services can change, split or move without clients noticing.

On Azure I'd choose between API Management and YARP. API Management is the right fit when I need partner-facing features: subscriptions and keys, products with quotas, a developer portal, versioning, analytics and policies like validate-jwt and rate-limit-by-key without writing code. YARP fits when the gateway is internal, performance-sensitive, or needs custom logic in C#: it's a library, so I host it in an ASP.NET Core app, configure routes and clusters, and add middleware for anything special. A BFF is a different idea: a small service per front end, often built on YARP, that aggregates three calls into one for the mobile app and handles cookie-based auth for the SPA.

The mistake I see is the gateway slowly becoming the place where business logic lives. Someone adds a policy that blocks orders over $10,000, another that reshapes responses for one client, another that calls two services and merges the results. Now there's untested logic in XML that no service team owns, and every change needs the platform team. My rule is: the gateway decides who may call and where the request goes; the services decide what happens."


What belongs where

Concern Gateway Service
TLS termination, routing, path rewriting Yes
Token validation (signature, expiry, audience) Yes Also (defence in depth)
Fine-grained authorisation (may this user see order 7?) Yes
Rate limits and quotas per client Yes Instance protection too
Request id / traceparent Yes Propagate
Response caching of shared data Sometimes Output caching
Business rules, validation of domain data Yes
Aggregating several services for one screen BFF, not the shared gateway

API Management vs YARP

Azure API Management YARP
Model Managed service (Consumption, Developer, Basic/Standard/Premium and v2 tiers) Library in your ASP.NET Core app
Extensibility XML policies with C# expressions Full C# middleware and transforms
Partner features Developer portal, subscriptions, products, analytics Build yourself
Cost Per tier or per call Your hosting
Best for External and partner APIs, governance Internal routing, BFFs, high throughput, custom logic

Production example

At a [retail company], an API Management instance had grown [40] policies including discount rules and response merging for the mobile app. Moving the merging into a YARP-based mobile BFF and the discount rules back into the pricing service cut gateway p95 overhead from about 120 ms to 15 ms and let teams deploy changes without a platform-team ticket.

🔍 What the interviewer is checking

Checks whether the candidate knows what gateways are for, can choose between API Management and YARP, and recognises the smart-gateway anti-pattern.

Green flags

  • Lists cross-cutting concerns and keeps business logic in services
  • Compares API Management and YARP on features, cost and extensibility
  • Explains BFF and who owns it
  • Mentions defence in depth, single point of failure and retry duplication

Red flags

  • Treats the gateway as the only security layer
  • Happy to put business rules or orchestration in gateway policies
  • Can't name a reason not to use a gateway

📚 Learn in depth

1. Where the gateway sits

          internet
             |
   Azure Front Door (global edge, WAF, CDN)
             |
   API Management (external API gateway: keys, quotas, JWT)
        /         \
  web BFF (YARP)   mobile BFF (YARP)
        \         /
   internal services (orders, catalogue, payments) on AKS / Container Apps

Not every system needs every layer. A single team with one API may need nothing beyond App Service and Front Door.

2. What a gateway does per request

  1. Terminates TLS and picks a route by host and path.
  2. Authenticates the caller (subscription key, JWT validation against Entra ID).
  3. Applies rate limits and quotas per key.
  4. Transforms: strip or add headers, rewrite the path, add traceparent.
  5. Forwards to a healthy backend (load balancing, retries on idempotent requests, circuit breaking).
  6. Logs and emits metrics.

Every step costs latency; a well-configured gateway adds a few milliseconds, a policy-heavy one tens to hundreds.

3. API Management specifics

Policies run in sections: inbound, backend, outbound, on-error. Common ones: validate-jwt, rate-limit-by-key, quota-by-key, set-header, rewrite-uri, cache-lookup / cache-store, mock-response. Products group APIs with quotas and terms; subscriptions issue keys. The self-hosted gateway runs the policy engine in your own containers for hybrid scenarios.

4. YARP specifics

YARP (Yet Another Reverse Proxy) is a Microsoft open-source library. Routes match requests; clusters list destinations with load balancing, active and passive health checks and session affinity. Transforms modify requests and responses. Because it runs inside ASP.NET Core, you can add authentication, the rate limiting middleware and output caching with the usual APIs.

5. The BFF pattern

A BFF is owned by the front-end team and shaped for one client: it aggregates calls, trims payloads for mobile bandwidth, and handles session cookies so tokens never reach browser JavaScript. It differs from a general gateway because it may contain presentation logic, but it still shouldn't contain business rules.

6. Failure modes

  • Single point of failure: run multiple units across availability zones (API Management Premium supports zones and multi-region).
  • Bottleneck team: every change goes through one platform team.
  • Hidden logic: policies without tests, versioning or code review.
  • Double retries: gateway retries plus client retries amplify load.
  • Security by gateway only: services trusting any request that reaches them; one misrouted path exposes them.

Try it yourself

  1. Create a YARP app with AddReverseProxy().LoadFromConfig(...) routing /api/orders/{**rest} to a sample API; add the rate limiter and test it.
  2. Add a transform that adds X-Forwarded-Prefix and check what the backend sees.
  3. In an API Management Developer tier, import an OpenAPI document and add validate-jwt and rate-limit-by-key; call it with and without a token.
  4. Measure the latency added by each gateway with Application Insights dependency timings or curl -w "%{time_total}".

💻 Code

A minimal YARP gateway with JWT validation and per-client rate limiting, kept thin on purpose:

using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.Authority = builder.Configuration["Auth:Authority"]; // e.g. Entra ID tenant
        o.Audience = builder.Configuration["Auth:Audience"];
    });
builder.Services.AddAuthorization(o =>
    o.AddPolicy("authenticated", p => p.RequireAuthenticatedUser()));

builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    o.AddPolicy("per-client", ctx => RateLimitPartition.GetTokenBucketLimiter(
        ctx.User.FindFirst("azp")?.Value ?? "anonymous",
        _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 100, TokensPerPeriod = 20,
            ReplenishmentPeriod = TimeSpan.FromSeconds(1), QueueLimit = 0
        }));
});

// Routes and clusters come from configuration: no business logic here.
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapReverseProxy();
app.Run();
{
  "ReverseProxy": {
    "Routes": {
      "orders": {
        "ClusterId": "orders",
        "AuthorizationPolicy": "authenticated",
        "RateLimiterPolicy": "per-client",
        "Match": { "Path": "/api/orders/{**rest}" },
        "Transforms": [ { "PathPattern": "/orders/{**rest}" } ]
      }
    },
    "Clusters": {
      "orders": {
        "HealthCheck": { "Active": { "Enabled": true, "Path": "/health" } },
        "Destinations": {
          "a": { "Address": "http://orders-a:8080" },
          "b": { "Address": "http://orders-b:8080" }
        }
      }
    }
  }
}

⚠ Common mistakes

  • Mistake: Putting business rules in gateway policies. Why it is wrong: policy XML usually lacks the unit tests, code review and versioning that service code gets, it is owned by a platform team that doesn't own the domain, and internal callers that skip the gateway also skip the rule. Instead: keep rules in the owning service; when something must live in the gateway, keep policies in source control (APIOps), review and test them like code.
  • Mistake: Relying on the gateway as the only security check. Why it is wrong: any path that reaches a service directly (a misconfigured network rule, an internal caller) bypasses it. Instead: services validate tokens and authorise every request too.
  • Mistake: One shared gateway combining responses from several services for every client (for example calling orders, stock and loyalty and merging them into one mobile screen payload). Why it is wrong: every front end's needs pile into one component, so it couples all clients and becomes a bottleneck. Instead: a BFF per client type, owned by that front-end team; the shared gateway only routes.
  • Mistake: Retrying in the gateway and in the client. Why it is wrong: retries multiply under failure. Instead: decide which layer retries; gateways should retry only idempotent requests, if at all.
  • Mistake: Running a single gateway instance or not monitoring it. Why it is wrong: it is a single point of failure for every API, and without its own metrics you can't tell gateway latency from backend latency. Instead: zone-redundant or multi-instance deployment with health probes, and dashboards for gateway overhead, error rate and capacity.
  • Mistake: Adopting API Management for one internal API. Why it is wrong: cost and an extra hop without partner features to justify them. Instead: YARP, Front Door or no gateway at all.
  • Mistake: Heavy response transformation in the gateway to hide a bad contract. Why it is wrong: it adds latency and hides design problems. Instead: fix the service contract and version it.

🏛 Senior insight: trade-offs

A gateway is infrastructure, and infrastructure should be boring. I want it to answer two questions, who is calling and where does this go, and to do so in a few milliseconds. As soon as it starts answering what should happen, it becomes a distributed monolith's hidden brain. I enforce that with ownership: platform teams own the gateway; product teams own anything with domain meaning, including BFFs.

I measure gateway overhead as its own metric (API Management reports backend vs total time; for YARP, compare gateway request duration with the forwarded call's duration). If overhead creeps past 10-20 ms, look at the policies.

Option When it fits Cost When not to
Azure API Management Partner or public APIs needing keys, quotas, portal, analytics Tier cost, policy latency, XML Single internal API
YARP gateway Internal routing, custom C# logic, high throughput You host, scale and patch it When you need a developer portal out of the box
BFF per front end Several clients with different needs One more service per client One client, simple API
No gateway Single service behind Front Door or App Service None Many services or external partners

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares a gateway with a reverse proxy or load balancer Why: Checks reverse proxy and load balancer fundamentals
    How to answer
    • A forward proxy sits in front of clients (corporate egress proxy): clients send requests through it to the internet. For HTTPS it tunnels with CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.
    • A reverse proxy sits in front of servers (nginx, Envoy, YARP, App Gateway, ingress): it terminates TLS, routes, load balances, caches and adds headers.

    Behind a reverse proxy, the app sees the proxy's IP and often plain http. The proxy passes the originals in X-Forwarded-For and X-Forwarded-Proto, but ASP.NET Core only applies them via the ForwardedHeaders middleware, and by default only trusts proxies on loopback. So UseHttpsRedirection sees http, redirects to https, the proxy forwards as http again: a loop.

    Fix: UseForwardedHeaders first, configured with the proxy's IPs or network in KnownProxies/known networks. Do not trust all sources, or clients can spoof their IP and scheme.

  2. When: Candidate mentions rate limiting in the gateway and in services Why: Checks per-instance vs gateway-level rate limiting
    How to answer

    Register limiters with builder.Services.AddRateLimiter, add app.UseRateLimiter() after routing and authentication, then attach named policies to endpoints with RequireRateLimiting("name") or [EnableRateLimiting]. For fairness use RateLimitPartition.GetTokenBucketLimiter (or fixed/sliding window) keyed by the API key, user id or tenant so one client can't exhaust another's quota. Set RejectionStatusCode = 429 (the default is 503) and use OnRejected to copy the lease's RetryAfter metadata into the Retry-After header with a ProblemDetails body. The catch: the middleware keeps state in memory per process, so with several instances the effective limit multiplies; contractual limits belong in a shared store or the gateway.

  3. When: Candidate mentions partner APIs and a developer portal Why: Checks public API design beyond the gateway
    How to answer

    I start from partner use cases and the domain, modelling resources around stable business concepts rather than tables. I adopt a published baseline (the Azure or Microsoft Graph REST API guidelines, which replaced Microsoft's original general guidelines; Google AIP or Zalando are good alternatives) and write a short house style: naming, JSON conventions, dates with offsets, money as decimal plus currency, opaque ids, one error shape (RFC 9457 ProblemDetails with error codes) and one paging shape (cursor plus nextLink).

    Then I design for evolution: additive changes only, tolerant readers, a written deprecation policy with Sunset headers, and rare major versions. Security is OAuth 2.0 client credentials with scopes, rate limits and idempotency keys. Partners experience the API through OpenAPI, examples, a sandbox, SDKs and a changelog. The trade-off is upfront design and governance effort versus years of breaking partner integrations.

🛠 Real-world problems: how you handle them

Business logic in API Management policies slows every release
Situation
A [retail platform] with [12] services behind one Azure API Management instance; over [3 years] the gateway accumulated [40] policies, including discount rules and response merging for the mobile app.
Signals
Gateway p95 overhead around [120 ms], releases waiting days for platform-team policy changes, an incident where a policy change broke [mobile checkout] with no test catching it, and policy XML hundreds of lines long.
Investigation
Used API Management analytics and Application Insights to split gateway time from backend time per operation, inventoried policies by purpose (cross-cutting vs domain), and traced the checkout incident to an untested `send-request` merge policy.
Resolution
Froze new domain policies, moved response merging into a YARP-based mobile BFF owned by the mobile team, moved discount rules into the pricing service with unit tests, and left API Management with JWT validation, quotas, routing and request ids.
Prevention
A gateway policy guideline in the architecture handbook (cross-cutting only), policies in source control with review via APIOps, latency budget alerts for gateway overhead, and contract tests on the BFF.

How to tell it (STAR)

**S:** At [company], our API Management instance had become the place where [40] policies lived, including discounts and response merging, and a policy change broke [mobile checkout]. **T:** I was asked to make the gateway safe to change and faster. **A:** I split gateway time from backend time in analytics, classified every policy as cross-cutting or domain, and proposed moving domain logic out: response merging into a YARP mobile BFF owned by the mobile team, discount rules into the pricing service with tests. API Management kept auth, quotas and routing, managed through source control. **R:** Gateway overhead dropped from about [120 ms] to [15 ms] at p95, and teams shipped without waiting on platform tickets.

↩ Usually asked after

More in API Reliability

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me