Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

API Gateways for Microservices

By Kokil Thapa | Last reviewed: September 2026

Your mobile app should not call twelve internal URLs to place one order. API gateways for microservices sit at the edge and give clients a single front door. They route traffic, enforce auth, apply rate limits, and hide service topology. I've used this pattern on production Laravel and Symfony systems where booking, payments, and document APIs grew faster than the team could manage direct client-to-service wiring.

Without a gateway, every new microservice becomes a public integration point. That spreads security rules, CORS config, and versioning logic across codebases. A gateway concentrates cross-cutting concerns where they belong—before requests hit your domain services. This guide covers architecture, gateway selection, real configuration patterns, and the production mistakes I see most often.

What is an API gateway and why do microservices need one?

An API gateway is a reverse proxy with policy. It terminates HTTPS, validates tokens, maps public URLs to internal routes, and returns consistent error shapes. In a monolith, your framework middleware does this work. In microservices, someone must do it at the boundary.

Think of the gateway as your application's front desk. Clients check in once. The gateway knows which internal team handles the request. Services stay private on internal networks or VPC subnets. Only the gateway needs a public IP or load balancer listener.

Microservices Edge ArchitectureClientsWeb & mobileAPI GatewayAuth, limits, routingAuth svcOrdersPaymentsDocumentsInternal networkServices not public
API gateways for microservices expose one public endpoint while backend services stay on a private network.

Gateways solve problems that multiply with service count. Without one, you duplicate JWT validation in five Laravel apps. You expose internal hostnames in mobile builds. You cannot throttle abusive clients globally because each service tracks limits independently.

Core responsibilities at the edge

  • Routing: Map /v1/orders/{id} to the order service upstream.
  • Authentication: Validate OAuth2, JWT, or API keys before forwarding.
  • Rate limiting: Protect backends from traffic spikes and abuse.
  • TLS termination: Handle certificates once at the edge.
  • Request/response transformation: Strip internal headers, normalise error JSON.
  • Observability: Central access logs, trace IDs, and metrics export.

On legal-tech portals I've shipped, document upload and payment callbacks both need stable public URLs. The gateway keeps those endpoints constant even when internal services move or scale. That stability matters for third-party webhooks and mobile app store review cycles.

How does an API gateway handle traffic in a microservices architecture?

Every request follows a predictable pipeline. The gateway receives HTTP traffic, runs a chain of plugins or middleware, selects an upstream, and proxies the call. Responses flow back through the same path. Distributed tracing headers attach at step one so downstream services join one trace.

Gateway Request PipelineClientTLSterminateAuthJWT checkRate limitRedis counterRoutepick upstreamMicroserviceBusiness logic onlyResponse pathTransform + log + return
Each client request passes through TLS, authentication, rate limiting, and routing before reaching a microservice.

Routing patterns that scale

Path-based routing is the default. /api/v1/users/* goes to the user service. /api/v1/payments/* goes to payments. Host-based routing helps when partners need branded subdomains. Header-based routing supports canary releases—send 5% of traffic with header X-Canary: true to the new version.

Aggregation is where gateways earn their keep. A mobile home screen might need user profile, recent orders, and notifications. Instead of three round trips from the phone, a gateway route calls three upstreams and merges JSON. BFF (Backend for Frontend) layers often live behind or inside the gateway tier.

Example Kong route definition

Kong remains a common self-hosted choice. This declarative snippet routes order traffic and applies a rate limit plugin. For deeper Kong setup, see the Kong API gateway guide.

# kong.yml (declarative config excerpt)
_format_version: "3.0"

services:
  - name: order-service
    url: http://order-svc.internal:8080
    routes:
      - name: orders-v1
        paths:
          - /api/v1/orders
        strip_path: false
    plugins:
      - name: rate-limiting
        config:
          minute: 120
          policy: redis
          redis_host: redis.internal
      - name: jwt
        config:
          claims_to_verify:
            - exp

Laravel Sanctum or Passport still issue tokens. The gateway validates them at the edge. Services can trust an internal header like X-User-Id set only by the gateway. Never trust that header on a publicly reachable service. For token patterns in Laravel, read Laravel API best practices and Passport vs Sanctum comparison.

Observability hooks

Generate or forward a X-Request-Id at the gateway. Pass it to every upstream. Correlate gateway access logs with application logs and microservices observability stacks. Prometheus metrics at the gateway—request rate, 4xx/5xx ratio, upstream latency—catch problems before individual services alert. Pair this with API monitoring using Prometheus and Grafana for dashboards that ops teams actually watch.

Which API gateway should you choose for your stack?

No single gateway wins every scenario. Managed cloud gateways reduce ops burden. Self-hosted options give control and avoid per-request billing. Lightweight reverse proxies work when you need routing only—not a full plugin ecosystem.

GatewayBest forTrade-offsTypical cost
KongPlugin-rich self-hosted setups, hybrid cloudNeeds Postgres or DB-less mode; steeper learning curveFree OSS; enterprise licensing for advanced features
TraefikKubernetes and Docker-native teamsFewer enterprise plugins than KongOpen source; Pro for advanced dashboard
AWS API GatewayServerless Lambdas, AWS-native stacksVendor lock-in; cold-start latency on LambdaPay per request (~USD 3.50/million, Rs ~470/million at typical rates)
KrakenDHigh-throughput aggregation, stateless configNo admin UI in OSS; config-file drivenFree OSS; enterprise support optional
Nginx / OpenRestyTeams already running Nginx at scaleCustom Lua for advanced logicFree; commercial support available

For a full three-way breakdown, read Kong vs Traefik vs AWS API Gateway. Traefik fits container-heavy deployments—see Traefik as an API gateway. KrakenD suits aggregation-heavy mobile backends—see KrakenD stateless gateway patterns.

Edge Pattern ComparisonDirect accessMany public URLsDuplicated authHard to throttleLeaky internalsAvoid at scaleAPI GatewaySingle public URLCentral authGlobal rate limitsBFF aggregationBest for clientsService meshEast-west mTLSRetry + circuitInternal trafficSidecar overheadPair with gatewayGateway handles north-south; mesh handles east-west
API gateways for microservices manage north-south client traffic; service meshes secure internal east-west calls between services.

Decision criteria for small teams

  1. Team size: Under five engineers? Prefer managed AWS API Gateway or a single Traefik instance over running Kong with HA Postgres.
  2. Hosting: Bare Ubuntu VPS with Apache? Nginx or OpenResty at the edge matches what you already operate. See Linux system administration patterns for PHP-FPM stacks.
  3. Traffic shape: Spiky mobile traffic needs Redis-backed rate limits. Steady B2B API usage may tolerate in-memory counters.
  4. Aggregation needs: Heavy response merging favours KrakenD or a thin Node/BFF behind the gateway.
  5. Migration stage: Still splitting a Laravel monolith? Start with path routing to extracted modules before full microservices. Read monolith to microservices migration for Laravel.

On Quick And Easy Nepalese Grocery, a Laravel eCommerce platform with delivery zones, a gateway-style edge was not day-one infrastructure. As checkout, inventory, and notification concerns split, consolidating auth and webhook URLs at one edge reduced deployment coordination. Start simple. Add gateway features when pain appears—not before.

How do you configure authentication and rate limiting at the gateway?

Authentication belongs at the gateway for external clients. Internal service-to-service calls should use mTLS or signed internal tokens—not the same public JWT the mobile app carries. Mixing those trust zones causes privilege escalation when a compromised service replays user tokens.

JWT validation at the edge

Most Laravel APIs issue JWTs via Passport or use Sanctum SPA tokens. Configure the gateway to validate signature, expiry, and issuer against your JWKS endpoint. Reject expired tokens with 401 before the request touches PHP-FPM workers.

# Traefik middleware excerpt (forwardAuth to Laravel)
http:
  middlewares:
    api-auth:
      forwardAuth:
        address: "http://auth-svc.internal/api/gateway/verify"
        authResponseHeaders:
          - X-User-Id
          - X-User-Roles
  routers:
    orders:
      rule: "PathPrefix(`/api/v1/orders`)"
      middlewares:
        - api-auth
      service: order-svc

Your Laravel verification endpoint returns 200 with identity headers on success. Keep it fast—cache JWKS keys in Redis. Full security coverage belongs in your API security checklist, including header trust boundaries and webhook signature validation.

Rate limiting strategies

Apply limits at three levels: global (protect infrastructure), per-client API key (fair usage tiers), and per-route (expensive endpoints like PDF generation). Redis 8.10 as a shared counter store works across multiple gateway instances. Laravel also offers route-level throttling—useful inside services but not a substitute for edge limits. See rate limiting and throttling in Laravel for app-layer patterns that complement the gateway.

# Kong rate-limiting with consumer tiers
consumers:
  - username: partner-acme
    keyauth_credentials:
      - key: acme-live-key-xxx

plugins:
  - name: rate-limiting
    consumer: partner-acme
    config:
      minute: 1000
      hour: 20000
      policy: redis

Return standard headers: X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After on 429 responses. Mobile clients and partner SDKs depend on predictable shapes. Test limit boundaries with JSON formatter tools when debugging aggregated error payloads.

Idempotency and versioning at the boundary

Payment and booking APIs should accept Idempotency-Key headers at the gateway and forward them unchanged. The gateway should not deduplicate—it lacks business context. Forward the header and let the payment service enforce semantics. Read idempotency key implementation for the full pattern. Version paths (/v1, /v2) route to different upstream groups during migration. See Laravel API versioning strategy and versioning strategies compared.

What are common API gateway mistakes in production?

Gateways fail in predictable ways. I've debugged these during production deployments on shared EC2 infrastructure where multiple Laravel sites run behind the same edge layer.

Production GotchasFat gatewayBusiness logic at edge = deploy bottleneckNo HASingle gateway node kills all APIsTimeout mismatch60s gateway vs 30s service = 502sStale routesDeploy new svc, forget gateway ruleFix: GitOps config + health checksGateway config in CI, active upstream probes
Common API gateway failures include business logic at the edge, missing high availability, and timeout mismatches with upstream services.

Fat gateway anti-pattern

Do not implement pricing rules, inventory checks, or legal document validation in gateway plugins. The gateway orchestrates and protects. Business rules stay in domain services written in Laravel 13.x or Symfony 8.1 where you have tests, migrations, and audit trails. A gateway Lua script that calculates VAT for Nepal IRD compliance will become unmaintainable within one fiscal year.

High availability and config drift

Run at least two gateway instances behind a load balancer. Store declarative config in Git. Apply it through CI—the same GitLab CI pipeline that deploys your Laravel app should validate and push gateway YAML. I've seen manual Kong admin API edits lost during server rebuilds. Treat gateway config like application code.

Timeout and body-size alignment

If your document upload service allows 50 MB payloads, the gateway must match. Default 1 MB limits cause silent failures on legal-tech portals where clients upload scanned affidavits. Align timeouts: gateway read timeout must exceed upstream processing time for slow report generation.

Testing the edge layer

Contract tests between gateway routes and upstream OpenAPI specs catch drift early. Include gateway routes in your Postman or Newman collections. Run smoke tests after every deploy. For broader QA workflow, see testing and optimization services and API testing with Postman and Newman.

When building new REST surfaces in Laravel, pair gateway rollout with building RESTful APIs with Laravel. Document public contracts with OpenAPI so the gateway team and service team share one source of truth—see API documentation with Redoc and Swagger UI.

For enterprise programmes needing dedicated gateway design, enterprise application development covers multi-service architectures from planning through production hardening. Client portals like Mijar Law Associates benefit from stable webhook and OAuth callback URLs managed at the gateway regardless of which internal service handles the workflow.

Official references worth bookmarking: the AWS API Gateway developer guide for managed patterns, and the Kong Gateway documentation for self-hosted plugin configuration. The Microservices.io API Gateway pattern page gives a concise architectural summary from Chris Richardson's catalog.

Key Takeaways

  • Place API gateways for microservices at the public edge so clients use one URL while internal services stay private.
  • Handle auth, rate limits, TLS, and routing at the gateway; keep business logic in Laravel or Symfony services.
  • Choose Kong, Traefik, AWS API Gateway, or KrakenD based on hosting, team size, and aggregation needs—not hype.
  • Store gateway config in Git, run multiple instances, and align timeouts and body limits with upstream services.
  • Pair the gateway with observability—request IDs, access logs, and Prometheus metrics—from day one.
  • Start with path routing during monolith extraction; add plugins as cross-cutting pain appears.

People Also Ask

Is an API gateway the same as a load balancer?

No. A load balancer distributes traffic across identical instances of one service. An API gateway routes different paths to different services, validates tokens, transforms requests, and applies per-client policies. Many setups use both—a cloud load balancer in front of gateway instances, then path-based routing to microservices.

Do I need an API gateway for three microservices?

Three services can work without a dedicated gateway if you accept duplicated auth middleware and multiple public endpoints. Once you add mobile clients, partner API keys, or webhook stability requirements, a gateway pays for itself. A single Traefik or Nginx instance on your existing VPS is enough to start.

Can Laravel be an API gateway?

Laravel can proxy requests via HTTP client middleware, but it is a poor dedicated gateway. PHP-FPM workers are heavier per connection than Nginx, Kong, or Traefik. Use Laravel to issue and verify tokens; use a reverse proxy at the edge for routing and rate limiting. Laravel 13.x excels at domain APIs behind the gateway, not as the gateway itself.

How does an API gateway differ from a service mesh?

The gateway manages north-south traffic from external clients into the cluster. A service mesh manages east-west traffic between internal services with sidecars, mTLS, and retries. Production systems often use both—the gateway for clients, Istio or Linkerd for internal calls.

Ship a gateway layer your microservices can grow into

API gateways for microservices are not optional complexity—they are how you keep client integrations stable while backend teams deploy independently. Start with routing and TLS, add auth and rate limits when traffic justifies them, and keep business rules out of the edge. Whether you are extracting modules from a Laravel monolith or wiring payment webhooks for a Nepal eCommerce launch, the gateway is the contract your clients depend on.

Need help designing the edge layer, public API surface, or migration path for your services? Contact us to plan gateway architecture, API development, and production deployment together—or browse the portfolio for platforms already running on these patterns.

Frequently Asked Questions

An edge reverse proxy that gives clients one public URL, routes requests to internal services, and handles auth, rate limits, TLS, and observability centrally.

Without a gateway, every new microservice becomes a public integration point. JWT validation, CORS rules, and versioning logic get duplicated across Laravel or Symfony apps, and mobile builds may expose internal hostnames. A gateway concentrates cross-cutting concerns at the boundary—authentication, rate limiting, TLS termination, request transformation, and consistent error shapes—before traffic reaches domain services on private networks. Clients check in once at a single front door while backend pods stay off the public internet.

No. A load balancer spreads traffic across identical instances of one service. A gateway routes different paths to different microservices, validates tokens, and applies per-client policies. Many production setups use both.

Each request passes through a predictable pipeline: TLS termination, authentication, rate limiting, then upstream selection and proxying. Path-based routing is the default—/api/v1/orders/ to the order service, /api/v1/payments/ to payments. Host-based routing supports partner-branded subdomains. Header-based routing enables canary releases, sending traffic with X-Canary: true to new versions. For mobile home screens needing profile, orders, and notifications, aggregation routes call multiple upstreams and merge JSON, reducing round trips from the client.

No single gateway wins every scenario. Kong suits plugin-rich self-hosted setups with JWT and Redis-backed rate limiting but needs Postgres or DB-less mode. Traefik fits Kubernetes and Docker-native teams with simpler plugin depth. AWS API Gateway reduces ops for serverless AWS stacks at roughly USD 3.50 per million requests (Rs ~470/million). KrakenD excels at high-throughput response aggregation with stateless config files. Nginx or OpenResty works when you already operate Nginx at scale on bare Ubuntu VPS infrastructure.

AWS API Gateway charges per request, roughly USD 3.50 per million requests (about Rs 470 per million at typical exchange rates).

Not necessarily on day one. Three services may still tolerate direct wiring if cross-cutting pain is low. The article recommends starting simple and adding gateway features when duplication appears—repeated JWT validation across apps, unstable public URLs for webhooks, or inability to throttle abusive clients globally. As checkout, inventory, and notification concerns split—as seen on Laravel eCommerce platforms—consolidating auth and webhook URLs at one edge reduces deployment coordination even before service count grows large.

Configure the gateway to validate JWT signature, expiry, and issuer against your JWKS endpoint, rejecting expired tokens with 401 before requests reach PHP-FPM workers. Laravel APIs issuing tokens via Passport or Sanctum can pair with Traefik forwardAuth pointing to an internal Laravel verification endpoint that returns 200 with X-User-Id and X-User-Roles headers on success. Cache JWKS keys in Redis for speed. Services behind the gateway may trust identity headers set only by the gateway—never trust X-User-Id on any publicly reachable service.

Apply limits at three levels: global infrastructure protection, per-client API key for fair usage tiers, and per-route limits on expensive endpoints like PDF generation. Kong rate-limiting plugins with Redis 8.10 as a shared counter store work across multiple gateway instances. Return standard X-RateLimit-Limit, X-RateLimit-Remaining, and Retry-After headers on 429 responses so mobile clients and partner SDKs behave predictably. Laravel route throttling inside services complements but does not replace edge limits.

API gateways manage north-south traffic—client requests entering from outside your network and responses returning. Service meshes secure east-west internal calls between microservices running inside your VPC or cluster. They solve different problems and often coexist: the gateway handles public auth, routing, and rate limits at the edge, while a mesh manages mTLS and observability between internal services. Choosing a gateway does not eliminate the need for internal service-to-service trust boundaries.

Implementing pricing rules, inventory checks, or legal document validation in gateway plugins or Lua scripts. The gateway should orchestrate and protect traffic, not host domain logic. Business rules belong in Laravel 13.x or Symfony 8.1 services where you have tests, migrations, and audit trails. A gateway script calculating VAT for Nepal IRD compliance becomes unmaintainable within one fiscal year. Payment idempotency is another example—the gateway should forward Idempotency-Key headers unchanged and let the payment service enforce semantics.

Run at least two gateway instances behind a load balancer so one failure does not take down your public API. Store declarative config in Git and apply it through CI—the same GitLab CI pipeline that deploys your Laravel app should validate and push gateway YAML. Manual Kong admin API edits get lost during server rebuilds, a pattern seen on shared EC2 infrastructure. Treat gateway config like application code with contract tests between gateway routes and upstream OpenAPI specs, plus Postman or Newman smoke tests after every deploy.

In microservices. The gateway handles routing, auth, rate limits, TLS, and observability—not domain rules.

Start with path routing to extracted Laravel modules before full microservices decomposition. On projects where gateway-style edge infrastructure was not day-one, consolidating auth and stable webhook URLs became valuable as checkout, inventory, and notification concerns split. Add gateway plugins as cross-cutting pain appears—duplicated JWT validation, exposed internal hostnames in mobile builds, or per-service rate limits that cannot throttle abusive clients globally—not before the team feels that friction.

Default 1 MB body limits cause silent failures when document upload services allow 50 MB payloads—a common problem on legal-tech portals where clients upload scanned affidavits. Gateway read timeouts must exceed upstream processing time for slow report generation. Misaligned limits between edge and backend produce confusing partial failures that look like application bugs. Audit gateway body-size and timeout settings whenever upstream services change their upload or generation thresholds, and include edge-layer routes in your deployment smoke tests.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: