# API Gateway Pattern with NestJS: Routing, Auth, and Rate Limiting in Production

> How to implement an API gateway in NestJS microservices — covering request routing, authentication aggregation, rate limiting, and the trade-offs of building vs buying.

URL: https://www.matthewswong.com/en/blog/api-gateway-pattern-nestjs-guide/

- Author: Matthews Wong (https://www.matthewswong.com/en/about/)
- Published: 2025-06-10
- Updated: 2026-10-17
- Category: DevOps

An API gateway is the single entry point for all client requests to your microservices backend. Instead of clients knowing about ten different service endpoints, they talk to one gateway that routes requests, enforces authentication, applies rate limits, and aggregates responses. In a NestJS microservices architecture, the gateway pattern is essential for maintaining clean service boundaries while presenting a unified API to front-end clients. I've implemented this pattern for projects where a React front-end needs to call multiple backend services without managing their individual endpoints.

## What an API Gateway Actually Does

The API gateway serves as a reverse proxy with intelligence. Its responsibilities: (1) Request routing — match incoming HTTP paths to the appropriate downstream microservice; (2) Authentication and authorization — validate JWTs or API keys before requests reach services; (3) Rate limiting — enforce per-client or per-endpoint quotas; (4) Request/response transformation — adapt payload formats between client and service contracts; (5) Circuit breaking — stop sending requests to failing services; (6) Response aggregation — combine responses from multiple services into one payload for the client.

### Building a Gateway with NestJS

In NestJS, the gateway can be a dedicated application that acts as an HTTP proxy. Use @nestjs/axios to forward requests to downstream services, implement Guards for authentication at the gateway level, and use Interceptors for rate limiting and response transformation. The gateway communicates with services via gRPC or HTTP — gRPC gives you typed contracts and better performance for internal traffic. For the external API surface, the gateway exposes REST (or GraphQL) regardless of what protocol the services use internally.

> A tip from front-end work on ERP-style applications: implement request tracing at the gateway layer by injecting an X-Request-ID header into every forwarded request. Log this ID at both the gateway and each downstream service. When debugging a production issue, you can reconstruct the full request journey across all services by searching your logs for that single ID. Without this, distributed debugging is nearly impossible.

## Authentication at the Gateway

Centralizing authentication at the gateway is one of the biggest benefits of the pattern. Instead of every microservice implementing JWT validation independently, the gateway validates the token and passes the decoded claims downstream as headers (X-User-Id, X-User-Roles). Downstream services trust these headers without re-validating the JWT — they only need to verify the request came from the gateway (use mTLS or a shared internal secret for this). This separation means adding a new microservice doesn't require duplicating auth logic.

### Rate Limiting Strategies

Rate limiting protects your services from abuse and ensures fair usage. Implement rate limiting at the gateway using a token bucket or sliding window algorithm backed by Redis — so limits are shared across multiple gateway instances. Common strategies: per-IP rate limiting for unauthenticated endpoints, per-user rate limiting for authenticated API calls, and per-endpoint burst limits for expensive operations. In NestJS, the @nestjs/throttler package handles this with Redis support via ThrottlerStorageRedisService.

> **The gateway becomes a single point of failure**

> Centralizing all traffic through the gateway means it must be your most reliable component. A gateway that goes down takes your entire API surface with it. Run multiple gateway instances behind a load balancer. Implement health checks on the gateway and circuit breakers on downstream service calls. The gateway should fail gracefully — return cached responses or meaningful error messages rather than hanging. Monitor gateway latency and error rates as your primary SLO: if your gateway's P99 latency spikes, every user feels it.

## Build vs Buy: NestJS vs Kong vs AWS API Gateway

For teams already invested in NestJS, building a gateway in NestJS gives full control and reuses existing patterns. But purpose-built gateway products like Kong, Traefik, or AWS API Gateway handle rate limiting, auth, routing, caching, and analytics out of the box. Use a purpose-built gateway when: you're in a polyglot environment; you need enterprise features like OAuth2 flows, API key management, or analytics dashboards without building them. Build in NestJS when: your team is NestJS-native, your requirements are well-defined and unlikely to grow complex, and you want to avoid licensing costs.

## Response Aggregation (BFF Pattern)

The Backend-for-Frontend (BFF) pattern extends the gateway by adding response aggregation — the gateway calls multiple services in parallel and merges the results into a single response for the client. For example, a dashboard page that needs user profile, recent orders, and notification count can get all three in one API call, with the gateway making three parallel calls internally. This reduces client-side waterfall requests and simplifies front-end code. In NestJS, implement this with Promise.all() for parallel service calls and merge the results before returning.

## Production Checklist for API Gateways

Before going live: implement health check endpoints on all downstream services and configure the gateway to check them; set timeout limits on all proxied requests (never let a slow service block a gateway thread indefinitely); add circuit breakers with a defined fallback response; enable distributed tracing with request ID propagation; monitor gateway memory and CPU — high-traffic gateways can be CPU-intensive due to JWT verification on every request; deploy multiple gateway instances and test failover. These aren't optional — they're the difference between a gateway that improves reliability and one that becomes a fragility point.

## Sources & Further Reading

- NestJS Docs — Microservices Overview
- NestJS Docs — Throttler / Rate Limiting
- Microsoft — API Gateway Pattern

## Source links

- https://docs.nestjs.com/microservices/basics
- https://docs.nestjs.com/security/rate-limiting
- https://learn.microsoft.com/en-us/azure/architecture/microservices/design/gateway

## FAQ

### Why centralize authentication at the API gateway instead of each microservice?

Centralizing authentication at the gateway means only one service validates JWTs or API keys — it then passes decoded claims downstream as trusted headers like X-User-Id and X-User-Roles. Downstream services skip re-validating the token and only verify the request originated from the gateway, using mTLS or a shared internal secret. This eliminates duplicated auth logic every time a new microservice is added.

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

Run multiple gateway instances behind a load balancer so no single instance going down takes the whole API surface with it. Implement health checks on the gateway itself and circuit breakers on downstream service calls, ensuring the gateway fails gracefully with cached responses or meaningful error messages rather than hanging. Monitoring gateway P99 latency and error rate as your primary SLO catches problems before they cascade.

### What rate-limiting approach does NestJS support for a multi-instance gateway?

Rate limits must be shared across all gateway instances to be effective, so the implementation should be backed by Redis rather than in-process memory. In NestJS, the @nestjs/throttler package supports this via ThrottlerStorageRedisService, using algorithms like token bucket or sliding window. Common strategies include per-IP limits for unauthenticated endpoints and per-user limits for authenticated API calls.

### When should you build a gateway in NestJS versus using Kong, Traefik, or AWS API Gateway?

Build in NestJS when your team is already NestJS-native, requirements are well-defined and unlikely to grow complex, and you want to avoid licensing costs. Choose a purpose-built gateway like Kong, Traefik, or AWS API Gateway in polyglot environments or when you need enterprise features such as OAuth2 flows, API key management, or analytics dashboards without building them yourself.

### What is the BFF pattern and how does it reduce front-end complexity?

The Backend-for-Frontend (BFF) pattern extends the gateway with response aggregation — the gateway calls multiple downstream services in parallel and merges the results into a single response. For example, a dashboard needing user profile, recent orders, and notification count receives all three in one API call instead of three sequential client-side requests. In NestJS this is implemented with Promise.all() for the parallel service calls before merging and returning the combined payload.

---

- HTML version: https://www.matthewswong.com/en/blog/api-gateway-pattern-nestjs-guide/
- Bahasa Indonesia: https://www.matthewswong.com/id/blog/api-gateway-pattern-nestjs-guide/
- Site index for agents: https://www.matthewswong.com/llms.txt
- Sitemap: https://www.matthewswong.com/sitemap.xml
- API description (OpenAPI): https://www.matthewswong.com/openapi.json
