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.
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.
"A gateway gives clients one front door. It terminates TLS, routes
/ordersto the orders service and/catalogueto 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-jwtandrate-limit-by-keywithout 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."
| 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 |
| 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 |
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.
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
Red flags
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.
traceparent.Every step costs latency; a well-configured gateway adds a few milliseconds, a policy-heavy one tens to hundreds.
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.
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.
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.
AddReverseProxy().LoadFromConfig(...) routing /api/orders/{**rest} to a sample API; add the rate limiter and test it.X-Forwarded-Prefix and check what the backend sees.validate-jwt and rate-limit-by-key; call it with and without a token.curl -w "%{time_total}".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" }
}
}
}
}
}
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 |
CONNECT. HttpClient picks it up from system settings or HTTP_PROXY/HTTPS_PROXY/NO_PROXY.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.
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.
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.
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.
Last updated 23 Nov 2026.