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

📚 Interview question

Build a small API gateway with YARP in .NET 10. Explain routes, clusters and destinations, transforms, load balancing policies, and active and passive health checks, and how you would add authentication and rate limiting at the gateway.

Covers building a gateway with YARP (Yarp.ReverseProxy): configuration-based routes and clusters, path transforms, load balancing policies, active and passive health checks, timeouts, and applying ASP.NET Core authorisation and rate limiting per route.

Mid-Level Coding Intermediate api-gateway aspnet-core devops load-balancing reverse-proxy yarp

🎯 Key points

  • AddReverseProxy().LoadFromConfig() and MapReverseProxy(); YARP (Yarp.ReverseProxy 2.x) is ASP.NET Core middleware
  • Route = match (path, host, headers) + ClusterId; cluster = destinations + policies
  • Transforms: PathRemovePrefix, request headers, X-Forwarded-* added by default
  • Load balancing: PowerOfTwoChoices is the default; RoundRobin, LeastRequests, Random, FirstAlphabetical
  • Active health checks probe a readiness path (e.g. /health/ready mapped with MapHealthChecks); passive checks eject on transport failures
  • Per-route AuthorizationPolicy, RateLimiterPolicy, CorsPolicy and TimeoutPolicy reuse normal ASP.NET Core middleware
  • Cluster HttpRequest.ActivityTimeout (100 s default) set to the backend's real latency budget
  • Gateway stays thin: cross-cutting concerns only, no business logic

⏱ 30-second answer

YARP is Microsoft's reverse proxy toolkit, shipped as the Yarp.ReverseProxy NuGet package and run as ASP.NET Core middleware. You define routes (what to match: path, host, headers) that point at clusters (a set of destinations plus policies). Transforms rewrite the request on the way through, such as stripping /api or adding headers. Each cluster picks a destination with a load balancing policy (PowerOfTwoChoices by default) and keeps the list healthy with active probes and passive failure detection.

Because it is ASP.NET Core, the gateway reuses normal authentication, authorisation, rate limiting and CORS middleware, attached per route by policy name. The trade-off: you get full C# control and one stack for the team, but you now run, scale and patch the gateway yourself, which a managed service like API Management would do for you.

🗣 Full answer (senior)

How I would answer this in an interview

"YARP is a reverse proxy library from Microsoft that runs inside an ASP.NET Core app. I call AddReverseProxy().LoadFromConfig(...) and MapReverseProxy(), and the proxy becomes an endpoint in the normal pipeline. Configuration has two parts. Routes say what to match, for example /api/orders/{**catch-all} on a given host, and which cluster to send it to. Clusters hold the destinations, the backend addresses, plus policies: load balancing, health checks, session affinity and HTTP client settings like timeouts.

On the way through I use transforms. Typical ones are PathRemovePrefix so the backend doesn't need to know about the gateway's /api prefix, adding a correlation header, and YARP already adds X-Forwarded-For, -Proto, -Host and -Prefix by default. For load balancing the default is power of two choices: pick two destinations at random and send to the one with fewer in-flight requests, which beats round robin when instances are uneven. Active health checks call each destination's /health/ready on an interval; passive health checks watch real traffic and take a destination out after transport failures, then bring it back after a reactivation period.

The nice part is that cross-cutting concerns are just ASP.NET Core. I validate JWTs once at the gateway with AddAuthentication().AddJwtBearer(), then put AuthorizationPolicy and RateLimiterPolicy on each route. The mistake I see is gateways growing business logic: calling three services and merging the responses in a transform. That turns the gateway into a fragile monolith that every team has to release through. I keep it to routing, auth, limits and headers."


YARP's model

Concept What it holds Example
Route Match rules + ClusterId + per-route policies + transforms /api/orders/{**catch-all} → orders
Cluster Destinations + load balancing + health checks + HttpClient config orders with 3 destinations
Destination One backend address http://orders-1:8080/
Transform Request or response rewrite PathRemovePrefix: /api

Load balancing policies

Policy Behaviour Use when
PowerOfTwoChoices (default) Two random picks, fewer active requests wins General purpose
LeastRequests Scans all, fewest active requests Small clusters, uneven request cost
RoundRobin In order Identical instances, cheap requests
Random Uniform random Rarely; testing
FirstAlphabetical Always first healthy Active/passive failover

Active vs passive health checks

Active Passive
How Periodic probe to a health path Observes real proxied requests
Detects Down or not-ready instances before traffic hits them Failures under real load
Cost Extra requests every interval None
Recovery Next successful probe After ReactivationPeriod

Production example

A gateway in front of [six] internal services on Container Apps replaced a hand-written forwarding controller. With passive health checks on, a replica that started returning connection resets during a bad deploy was ejected within seconds; gateway 5xx stayed under [0.1%] while the bad revision was rolled back, compared with about [8%] errors in the previous incident without the gateway.

🔍 What the interviewer is checking

Checks hands-on YARP knowledge: the route and cluster model, health and load balancing behaviour, and keeping the gateway thin by reusing ASP.NET Core middleware.

Green flags

  • Describes routes, clusters, destinations and transforms correctly
  • Knows the default load balancing policy and the difference between active and passive health checks
  • Applies auth and rate limiting per route using normal ASP.NET Core policies
  • Warns against business logic in the gateway

Red flags

  • Writes a controller that forwards requests with HttpClient by hand
  • No health checks, single instance, no timeouts
  • Rate limits by IP without considering an upstream proxy

📚 Learn in depth

1. Where YARP sits in the pipeline

Kestrel → UseRouting → UseAuthentication → UseAuthorization → UseRateLimiter
        → MapReverseProxy endpoint
              └─ proxy pipeline: session affinity → load balancing → passive health
                    └─ IHttpForwarder → SocketsHttpHandler → destination

Each YARP route becomes a real ASP.NET Core endpoint with metadata, which is why AuthorizationPolicy or RateLimiterPolicy on a route works with the normal middleware. The default MapReverseProxy() adds the session affinity, load balancing and passive health check steps; you can pass a lambda to insert your own middleware into the proxy pipeline.

2. Forwarding internals

IHttpForwarder copies the request to an outgoing HttpRequestMessage, streams the body without buffering, and streams the response back. It uses one shared HttpMessageInvoker per cluster over SocketsHttpHandler, so connection pooling, HTTP/2 multiplexing and keep-alive work across requests. WebSockets and gRPC (HTTP/2) are proxied too. Request activity timeout defaults to 100 seconds.

3. Transforms

Built-in transforms cover paths (PathPrefix, PathRemovePrefix, PathPattern), query strings, headers, X-Forwarded-* and Forwarded. By default YARP does not copy the client's Host header (the destination's host is used) unless you set RequestHeaderOriginalHost. Custom transforms are C# via AddTransforms.

4. Configuration sources

  • LoadFromConfig(IConfiguration): appsettings or Azure App Configuration; reloads on change.
  • LoadFromMemory(routes, clusters): build in code, update via InMemoryConfigProvider.Update.
  • Custom IProxyConfigProvider: for example, read destinations from Kubernetes or a database.
  • Service discovery: Microsoft.Extensions.ServiceDiscovery.Yarp resolves logical names (as .NET Aspire does).

5. Health check mechanics

Active: a timer per cluster sends GET to destination + Path every Interval; the ConsecutiveFailures policy marks it unhealthy after a threshold (default 2). Passive: the TransportFailureRate policy tracks failed proxied requests over a window and marks the destination unhealthy, then restores it after ReactivationPeriod. Load balancing only picks from healthy destinations; if none are healthy, YARP falls back to all of them rather than failing every request.

Try it yourself

  1. Run two copies of a tiny API on ports 5001 and 5002 and put the gateway in front; hit it 100 times and count responses per instance.
  2. Kill one instance and watch passive health checks remove it; check the gateway logs.
  3. Add a RateLimiterPolicy of 10 requests per 10 seconds on one route and confirm 429.
  4. Change a route path in appsettings.json while running and confirm it reloads without restart.
  5. Load test with bombardier or k6 and compare p99 latency direct vs through the gateway.

💻 Code

A small gateway: config-driven routes, JWT validation, per-route rate limiting and a custom header transform.

// Program.cs (.NET 10, package Yarp.ReverseProxy 2.x)
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Yarp.ReverseProxy.Transforms;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o => builder.Configuration.Bind("Jwt", o));
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("authenticated", p => p.RequireAuthenticatedUser());

builder.Services.AddRateLimiter(o =>
{
    o.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    // Partition by user so one client cannot starve the rest.
    o.AddPolicy("per-client", ctx => RateLimitPartition.GetTokenBucketLimiter(
        ctx.User.Identity?.Name ?? ctx.Connection.RemoteIpAddress?.ToString() ?? "anon",
        _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = 100,
            TokensPerPeriod = 100,
            ReplenishmentPeriod = TimeSpan.FromSeconds(10),
            QueueLimit = 0
        }));
});

builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddTransforms(ctx =>
    {
        // Pass a correlation id so backend logs line up with gateway logs.
        ctx.AddRequestTransform(t =>
        {
            t.ProxyRequest.Headers.TryAddWithoutValidation(
                "X-Correlation-Id", t.HttpContext.TraceIdentifier);
            return ValueTask.CompletedTask;
        });
    });

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();

app.MapReverseProxy(); // default pipeline: affinity, load balancing, passive health checks

app.Run();

The routes and clusters live in configuration, so they can change without a redeploy:

{
  "ReverseProxy": {
    "Routes": {
      "orders": {
        "ClusterId": "orders",
        "AuthorizationPolicy": "authenticated",
        "RateLimiterPolicy": "per-client",
        "Match": { "Path": "/api/orders/{**catch-all}" },
        "Transforms": [ { "PathRemovePrefix": "/api" } ]
      }
    },
    "Clusters": {
      "orders": {
        "LoadBalancingPolicy": "PowerOfTwoChoices",
        "HealthCheck": {
          "Active": { "Enabled": true, "Interval": "00:00:10", "Timeout": "00:00:05",
                      "Policy": "ConsecutiveFailures", "Path": "/health/ready" },
          "Passive": { "Enabled": true, "Policy": "TransportFailureRate",
                       "ReactivationPeriod": "00:01:00" }
        },
        "HttpRequest": { "ActivityTimeout": "00:00:30" },
        "Destinations": {
          "orders-1": { "Address": "http://orders-1:8080/" },
          "orders-2": { "Address": "http://orders-2:8080/" }
        }
      }
    }
  }
}

⚠ Common mistakes

  • Mistake: Putting business logic (aggregation, data mapping) in transforms. Why it is wrong: The gateway becomes a shared monolith every team must release through. Instead: Keep the gateway to routing and cross-cutting concerns; aggregate in a BFF service if needed.
  • Mistake: Enabling active health checks against /health that checks the database. Why it is wrong: A database blip marks every instance unhealthy at once. Instead: Probe a readiness endpoint that reflects the instance's own ability to serve.
  • Mistake: Forgetting UseAuthentication / UseAuthorization before MapReverseProxy. Why it is wrong: The route's AuthorizationPolicy has nothing to evaluate and requests are rejected or, worse, policies are misread. Instead: Order middleware as in any ASP.NET Core app.
  • Mistake: Rate limiting by RemoteIpAddress when the gateway is itself behind Front Door. Why it is wrong: Every request shares the edge's IP, so one limit applies to everyone. Instead: Configure forwarded headers first or partition by user or API key.
  • Mistake: Leaving the 100-second default activity timeout for all routes. Why it is wrong: A hung backend holds gateway connections and sockets for over a minute. Instead: Set ActivityTimeout per cluster based on the backend's real latency.
  • Mistake: Running a single gateway instance. Why it is wrong: It is now a single point of failure for every service. Instead: Run at least two replicas across zones.
  • Mistake: Forwarding the client's Authorization header to every backend unchanged. Why it is wrong: Backends may accept tokens not meant for them. Instead: Validate audience at the gateway and, where needed, exchange for a downstream token.

🏛 Senior insight: trade-offs

YARP is the right choice when a .NET team needs routing logic that config files can't express, wants one language and toolchain, or needs a gateway that runs anywhere (AKS, Container Apps, on-premises). It is the wrong choice when the requirement is a developer portal, subscription keys, monetisation or policy-as-config for non-developers; that is API Management's job. I also check whether the platform ingress already does what is needed: Container Apps ingress and the Kubernetes Gateway API cover simple path routing without any code.

Two migrations come up often. YARP to API Management happens when internal APIs become partner-facing products: keys, quotas, a portal and an audit trail for non-engineers. Then API Management sits at the edge and YARP either disappears or stays as an internal router. API Management to YARP (for internal traffic) happens when latency or per-call cost hurts on chatty service-to-service calls; teams keep API Management for external consumers and route internal calls through YARP or plain service discovery. Timeouts must be layered so each hop is shorter than the one in front of it (for example Front Door 60 s > gateway 30 s > backend HttpClient 10 s), otherwise the outer layer gives up first and the inner work is wasted. CORS is owned in one place: either CorsPolicy on the YARP route or the backend, never both.

Option When it fits Cost When not to
YARP Custom C# routing, auth, transforms; .NET team Run, scale and patch yourself Only need simple path routing
Azure API Management External API products, keys, portal, policies Tier cost (higher tiers for VNet) Low-latency internal service-to-service
Ingress / Gateway API Path and host routing inside AKS Low, part of the cluster Need per-request logic in C#
Front Door Global edge, WAF, CDN Per-request and base fee Internal-only traffic

I measure the gateway's own overhead with Application Insights or OpenTelemetry: the gap between gateway request duration and backend dependency duration should be a few milliseconds at p99.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions API Management or calls YARP an API gateway Why: Checks they can decide what belongs in a gateway and when API Management fits better than YARP
    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.

  2. When: Candidate mentions X-Forwarded-* headers added by YARP Why: Checks the backend side: trusting forwarded headers only from the gateway
    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.

  3. When: Candidate adds a RateLimiterPolicy to a route Why: Checks partitioning and what changes when the gateway runs on several instances
    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.

🛠 Real-world problems: how you handle them

Gateway kept sending traffic to a dead revision
Situation
[Retail] platform with a YARP gateway on Azure Container Apps in Australia East routing to [six] internal APIs, about [1,500] requests per second at peak. Destinations were static addresses of individual replicas.
Signals
After a deploy, Application Insights showed gateway 502s at [8%] for one route; failed dependency calls to a single destination address; customers reported intermittent checkout failures.
Investigation
Filtered Application Insights failures by `cloud_RoleName` and destination; KQL on `requests` joined to `dependencies` showed all failures going to one address. The gateway config had no health checks, so YARP kept load balancing to a replica that was terminating. `az containerapp revision list` confirmed the old revision was draining.
Resolution
Immediately removed the bad destination from App Configuration (YARP reloaded without restart). Then switched destinations to the service's internal ingress name instead of replica addresses, enabled passive health checks with `TransportFailureRate` and active checks on `/health/ready`, and set a 30-second activity timeout.
Prevention
Added a gateway readiness dashboard (healthy destinations per cluster), an alert on gateway 5xx above [1%] for 5 minutes, a load test in the pipeline that kills an instance mid-run, and an ADR stating destinations must be service names, not instance addresses.

How to tell it (STAR)

**S:** At [company] our YARP gateway fronted [six] APIs on Container Apps, and after one deploy checkout errors jumped to about [8%]. **T:** I was [on call] and needed to stop the errors and make sure a single bad instance could never do that again. **A:** In Application Insights I joined gateway requests to dependency calls and saw every failure going to one destination. Our config had no health checks and pointed at replica addresses, so YARP kept choosing a dying replica. I removed it through App Configuration, which YARP reloaded live, then changed destinations to the internal service name and turned on passive and active health checks with a 30-second timeout. **R:** Errors dropped back under [0.1%] within [two minutes], and in the next [three] bad deploys the gateway ejected failing instances automatically with no customer-visible impact.

↩ Usually asked after

More in Reverse Proxy and Gateway

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me