IntegrationC# · TypeScript

API Gateway

Put a single entry point in front of many services to route requests and handle cross-cutting concerns such as auth, rate limits and TLS.

On this page
  1. Problem
  2. Context
  3. Solution
  4. Implementation
  5. Trade-offs
  6. Alternatives
  7. Anti-patterns
  8. Related lessons
  9. Interview questions

Problem

Once a system is split into many services, clients face a moving target. A mobile app would need to know the address of every service, call several of them to render one screen, and keep working as services are renamed, split or moved. Every service exposed to the internet also needs its own TLS, authentication, rate limiting, CORS handling and request logging, implemented consistently in different languages by different teams.

Exposing internal services directly also leaks the internal architecture into public contracts. Refactoring a service boundary becomes a breaking change for every client.

Context

Use this pattern when:

  • Several backend services serve external clients (web, mobile, partners).
  • Cross-cutting concerns such as authentication, rate limiting and observability must be applied consistently.
  • Internal service boundaries should be free to change without breaking clients.
  • Clients are often on high-latency networks, so many round trips per screen are expensive.

Solution

Place a gateway at the edge. Clients talk only to it; it routes each request to the right internal service based on path, host or headers. Internal topology, service discovery and versions stay hidden behind stable public routes.

The gateway enforces policies once for everyone: TLS termination, token validation, rate limiting and quotas, request size limits, CORS, header normalisation, correlation ids and access logs. Services behind it can trust that requests were authenticated and receive the caller's identity as claims or headers, although they still authorise what the caller may do.

Optionally, the gateway aggregates: one client call fans out to several services and returns a combined response. When different clients need very different aggregations, a separate gateway per client type (Backend for Frontend) keeps each one focused. Keep business logic out of the gateway; it should stay a thin, highly available routing and policy layer.

How it works, step by step

  1. 1Client sends a request to the gateway's public endpoint over TLS.
  2. 2The gateway terminates TLS, validates the access token and applies rate limits.
  3. 3It matches the route and resolves a healthy instance of the target service.
  4. 4It forwards the request with identity and correlation headers, with a timeout.
  5. 5It returns the response (or aggregates several), logging and recording metrics.

Implementation

In .NET, YARP (Yet Another Reverse Proxy) turns an ASP.NET Core app into a gateway with configuration-driven routing, so authentication and rate limiting reuse the standard middleware. The TypeScript example is a compact Node gateway showing routing, auth and timeouts by hand.

C#YARP gateway with JWT auth and rate limiting
// Program.cs (packages: Yarp.ReverseProxy, Microsoft.AspNetCore.Authentication.JwtBearer)
using System.Threading.RateLimiting;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication().AddJwtBearer(options =>
{
    options.Authority = "https://login.example.com";
    options.Audience = "shop-api";
});
builder.Services.AddAuthorization(options =>
    options.AddPolicy("authenticated", policy => policy.RequireAuthenticatedUser()));

builder.Services.AddRateLimiter(options =>
{
    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
    options.AddFixedWindowLimiter("standard", limiter =>
    {
        limiter.PermitLimit = 100;
        limiter.Window = TimeSpan.FromSeconds(10);
        limiter.QueueLimit = 0;
    });
});

// Routes and clusters come from the "ReverseProxy" section of appsettings.json.
builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapReverseProxy();
app.Run();

/* appsettings.json
"ReverseProxy": {
  "Routes": {
    "orders": {
      "ClusterId": "orders", "AuthorizationPolicy": "authenticated", "RateLimiterPolicy": "standard",
      "Match": { "Path": "/api/orders/{**rest}" }
    }
  },
  "Clusters": {
    "orders": {
      "LoadBalancingPolicy": "LeastRequests",
      "HealthCheck": { "Active": { "Enabled": true, "Path": "/health" } },
      "Destinations": { "a": { "Address": "http://orders-1:8080" }, "b": { "Address": "http://orders-2:8080" } }
    }
  }
} */

YARP routes accept AuthorizationPolicy and RateLimiterPolicy names, so edge policies are declared per route in configuration and enforced by standard ASP.NET Core middleware.

TypeScriptMinimal Node gateway: routing, auth and timeouts
import { createServer } from 'node:http';
import { createRemoteJWKSet, jwtVerify } from 'jose';

const routes: { prefix: string; target: string; auth: boolean }[] = [
  { prefix: '/api/orders', target: 'http://orders.internal:8080', auth: true },
  { prefix: '/api/catalog', target: 'http://catalog.internal:8080', auth: false },
];

const jwks = createRemoteJWKSet(new URL('https://login.example.com/.well-known/jwks.json'));

async function authenticate(header: string | undefined): Promise<string | null> {
  if (!header?.startsWith('Bearer ')) return null;
  try {
    const { payload } = await jwtVerify(header.slice(7), jwks, {
      issuer: 'https://login.example.com',
      audience: 'shop-api',
    });
    return payload.sub ?? null;
  } catch {
    return null; // bad signature, wrong audience or expired
  }
}

createServer(async (req, res) => {
  const route = routes.find((r) => req.url?.startsWith(r.prefix));
  if (!route) return void res.writeHead(404).end();

  const userId = route.auth ? await authenticate(req.headers.authorization) : null;
  if (route.auth && !userId) return void res.writeHead(401).end();

  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(chunk as Buffer);

  try {
    const upstream = await fetch(route.target + req.url, {
      method: req.method,
      headers: {
        'content-type': req.headers['content-type'] ?? 'application/json',
        'x-user-id': userId ?? '',
        'x-correlation-id': String(req.headers['x-correlation-id'] ?? crypto.randomUUID()),
      },
      body: chunks.length > 0 ? Buffer.concat(chunks) : undefined,
      signal: AbortSignal.timeout(3_000),
    });
    res.writeHead(upstream.status, { 'content-type': upstream.headers.get('content-type') ?? 'application/json' });
    res.end(Buffer.from(await upstream.arrayBuffer()));
  } catch {
    res.writeHead(504).end(); // upstream timed out or was unreachable
  }
}).listen(8080);

This shows the responsibilities, not a production gateway: real deployments use Envoy, Kong, NGINX, YARP or a managed cloud gateway, which add connection pooling, streaming, retries and health checks.

In production

  • Run the gateway as several stateless instances behind a load balancer; it is on every request path, so its availability caps the system's.
  • Keep it thin: routing, auth, limits and observability. Business rules in the gateway create a distributed monolith owned by nobody.
  • Set timeouts per route and propagate correlation ids so traces start at the edge.
  • Services must still authorise requests; the gateway authenticates, but a compromised internal caller should not bypass permission checks.
  • Version public routes at the gateway so internal services can evolve independently.

Trade-offs

Benefits

  • One stable public surface; internal services can move, split and scale freely.
  • Cross-cutting concerns are implemented once and consistently.
  • Fewer client round trips when the gateway aggregates calls.
  • A single place for edge observability, security controls and traffic shaping.

Costs

  • An extra network hop adds latency to every request.
  • A critical shared component: misconfiguration or overload affects every service.
  • Can become a bottleneck for teams if every route change needs a central team.
  • Risk of accumulating business logic and turning into a monolith at the edge.

Alternatives

Backend for Frontend
One gateway per client type (web, mobile, partner), each owned by the team building that client and shaped to its screens.
Service mesh
Handles service-to-service concerns such as mTLS, retries and traffic splitting inside the cluster; often used together with a gateway for north-south traffic.
Plain reverse proxy or load balancer
Enough when there are only a few services and cross-cutting concerns live in the services themselves.

Anti-patterns

Business logic in the gateway
Pricing rules or order workflows in gateway code couple every team to one deployable and blur service ownership.
Single gateway instance
A gateway without redundancy is a single point of failure for the entire product.
Trusting the gateway for authorisation
Services that skip their own permission checks because "the gateway checked" are exposed to any internal caller or misrouted request.
One gateway for every client and team
A shared gateway with hundreds of client-specific aggregations becomes a bottleneck for change; split into BFFs.

Interview questions

What is the difference between an API gateway and a load balancer?

A load balancer distributes traffic for one service across its instances, usually at layer 4 or simple layer 7. A gateway is an application-level entry point for many services: it routes by API, authenticates, rate limits and can transform or aggregate requests. In practice a gateway often sits behind a load balancer and load balances to services itself.

When would you choose Backend for Frontend over a single gateway?

When clients need substantially different data shapes or aggregation, for example a mobile app needing compact payloads and a web dashboard needing rich ones. A BFF per client lets each client team change its edge independently instead of queuing changes on one shared gateway.

How do you prevent the gateway from becoming a single point of failure?

Run multiple stateless instances across availability zones behind a load balancer, keep state such as rate limit counters in a replicated store, and deploy configuration changes gradually with automatic rollback. Keeping the gateway thin also reduces how often it changes.

Should services trust identity headers set by the gateway?

Only if the network guarantees that requests reach services through the gateway, for example with mTLS or network policies, and the gateway strips any client-supplied copies of those headers. Many teams forward the validated token itself so services can verify it and make their own authorisation decisions.