API gateway, service discovery and load balancing

Mid-level Always asked 7 min

On this page

The question

Why use an API gateway in front of microservices?

30-second answer

It gives clients one entry point and hides how the system is split, so services can be moved, split or merged without breaking clients. It also does the cross-cutting work once: routing, authentication, rate limiting, TLS (Transport Layer Security) termination, request logging and tracing, and sometimes response aggregation. Spring Cloud Gateway, Kong, NGINX or a cloud API gateway are typical choices.

Understand it

A request through gateway, registry and balancer

Step by step

Each Orders instance registers its address with the registry at startup and sends a heartbeat every few seconds. orders-3 stopped answering, so the registry dropped it.

Step 1 of 6
View as text

A client and the API gateway on top, the service registry and a load balancer in the middle, and three Orders instances at the bottom, the third one down. A marker shows where the request is.

Each Orders instance registers its address with the registry at startup and sends a heartbeat every few seconds. orders-3 stopped answering, so the registry dropped it.

The mobile app sends GET /api/orders/42 with its token to the gateway. Clients know one address, never the services behind it.

The gateway checks the token and the rate limit once, for every service, then matches the route: /api/orders/** goes to the service named orders.

The gateway asks the registry which instances of orders are up, and caches the answer for a few seconds. orders-3 is not in the list.

The load balancer inside the gateway picks orders-1, round robin, and forwards the request. This is client-side load balancing: the caller chooses the instance.

The next request goes to orders-2. No request reaches orders-3, so clients never see its failure, and a restarted instance joins by registering again.

A client and the API gateway on top, the service registry and a load balancer in the middle, and three Orders instances at the bottom, the third one down. A marker shows where the request is.

Each Orders instance registers its address with the registry at startup and sends a heartbeat every few seconds. orders-3 stopped answering, so the registry dropped it.

The mobile app sends GET /api/orders/42 with its token to the gateway. Clients know one address, never the services behind it.

The gateway checks the token and the rate limit once, for every service, then matches the route: /api/orders/** goes to the service named orders.

The gateway asks the registry which instances of orders are up, and caches the answer for a few seconds. orders-3 is not in the list.

The load balancer inside the gateway picks orders-1, round robin, and forwards the request. This is client-side load balancing: the caller chooses the instance.

The next request goes to orders-2. No request reaches orders-3, so clients never see its failure, and a restarted instance joins by registering again.

Takeaway: Clients call one gateway. Services register themselves, the gateway looks up the healthy instances by name, and a load balancer spreads the requests, so instances can come and go without clients noticing.

What belongs in an API gateway

Tap the parts

Select a part to see what it does.

Tap a job the gateway might do. The stripe on each row says whether it belongs at the edge or should stay out of the gateway.

View as text

A legend names two zones: belongs at the edge, and keep it out. Seven rows follow, each a job with a colored stripe for its zone and two short lines.

Routing, belongs at the edge: /api/orders/**, to the orders service. The gateway maps public paths to internal services by name, so services can be split, merged or moved without changing a single client..

Authentication, belongs at the edge: Checks tokens once, and relays it. The gateway validates the token on every request and rejects a bad one with 401 before it reaches any service.

Rate limiting, belongs at the edge: 100 requests a minute, 429 when exceeded. Limits per client or API key protect every service from one noisy caller.

TLS, belongs at the edge: HTTPS ends here, one set of certificates. TLS (Transport Layer Security) terminates at the gateway, so certificates are managed in one place.

Aggregation, belongs at the edge: One call, 3 services, or a BFF per client. A mobile screen that needs three services gets one response, saving round trips on a slow network.

Tracing, belongs at the edge: Starts the trace, logs every request. The gateway is the first hop, so it starts the trace context, or accepts the caller’s, and logs every request with status and latency: one place to see all traffic..

Business rules, keep it out: Discount rules, belong in services. Business logic in the gateway turns it into a shared monolith that every team must change and release together.

A legend names two zones: belongs at the edge, and keep it out. Seven rows follow, each a job with a colored stripe for its zone and two short lines.

Routing, belongs at the edge: /api/orders/**, to the orders service. The gateway maps public paths to internal services by name, so services can be split, merged or moved without changing a single client..

Authentication, belongs at the edge: Checks tokens once, and relays it. The gateway validates the token on every request and rejects a bad one with 401 before it reaches any service.

Rate limiting, belongs at the edge: 100 requests a minute, 429 when exceeded. Limits per client or API key protect every service from one noisy caller.

TLS, belongs at the edge: HTTPS ends here, one set of certificates. TLS (Transport Layer Security) terminates at the gateway, so certificates are managed in one place.

Aggregation, belongs at the edge: One call, 3 services, or a BFF per client. A mobile screen that needs three services gets one response, saving round trips on a slow network.

Tracing, belongs at the edge: Starts the trace, logs every request. The gateway is the first hop, so it starts the trace context, or accepts the caller’s, and logs every request with status and latency: one place to see all traffic..

Business rules, keep it out: Discount rules, belong in services. Business logic in the gateway turns it into a shared monolith that every team must change and release together.

Takeaway: A gateway does the cross-cutting work every request needs: routing, authentication, rate limits, TLS, aggregation and tracing. Business rules stay in the services, or the gateway becomes the new monolith.

Client-side or server-side load balancingWith client-side load balancing, the caller asks the registry for the instances and picks one itself, as Spring Cloud LoadBalancer does with Eureka. With server-side load balancing, the caller sends every request to one stable address, and a load balancer or a Kubernetes Service picks the instance.Server-sideClient-sideCallerRegistry:list of instancesPicks oneinstance itselfCallerOne stable address:Kubernetes Serviceor load balancerBalancer picksthe instance
Client-side or server-side load balancingWith client-side load balancing, the caller asks the registry for the instances and picks one itself, as Spring Cloud LoadBalancer does with Eureka. With server-side load balancing, the caller sends every request to one stable address, and a load balancer or a Kubernetes Service picks the instance.Server-sideClient-sideCallerRegistry:list of instancesPicks oneinstance itselfCallerOne stable address:Kubernetes Serviceor load balancerBalancer picksthe instance
Client-side or server-side load balancing

In code

@Bean
RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("orders", r -> r.path("/api/orders/**")
            .filters(f -> f
                .stripPrefix(1)                        // /api/orders/42 -> /orders/42
                .retry(2))                             // retry idempotent GETs on another instance
            .uri("lb://orders"))                       // lb:// = look up "orders", then balance
        .route("catalog", r -> r.path("/api/products/**")
            .filters(f -> f.stripPrefix(1))
            .uri("lb://catalog"))
        .build();
}
A Spring Cloud Gateway route to a service found by name
# orders/application.properties
spring.application.name=orders
eureka.client.service-url.defaultZone=http://registry:8761/eureka
# Heartbeat every 30 s by default; missed heartbeats evict the instance after about 90 s
eureka.instance.lease-renewal-interval-in-seconds=10
eureka.instance.lease-expiration-duration-in-seconds=30
Each service registers itself with Eureka under its name
@Bean
@LoadBalanced                                          // resolves names through the registry
RestClient.Builder balancedBuilder() { return RestClient.builder(); }

// One fixed instance: when it moves or dies, every call fails
 Wrong OrderView wrong(long id) { return plain.get().uri("http://10.0.3.17:8080/orders/{id}", id).retrieve().body(OrderView.class); }

// A logical name: each call goes to a healthy instance
 Right OrderView right(long id) { return balanced.get().uri("http://orders/orders/{id}", id).retrieve().body(OrderView.class); }
Call a service by name, not by a host that will move
On Kubernetes, the Service is the registry and the balancerA caller resolves the DNS name orders to the Service's stable virtual IP. Kubernetes keeps the list of ready pods behind it and routes each connection to one of them, so no Eureka is needed.Caller: http://ordersDNS: orders toa stable virtual IPService: readypods onlyorders pod 1orders pod 2
On Kubernetes, the Service is the registry and the balancerA caller resolves the DNS name orders to the Service's stable virtual IP. Kubernetes keeps the list of ready pods behind it and routes each connection to one of them, so no Eureka is needed.Caller: http://ordersDNS: orders toa stable virtual IPService: readypods onlyorders pod 1orders pod 2
On Kubernetes, the Service is the registry and the balancer

Solve it

A mobile screen makes seven calls and loads slowly

The order-detail screen of a mobile app calls the gateway seven times: the order, its lines, each line’s product, the shipment and the invoice. On a mobile network each round trip costs about 150 ms, and the calls run partly in sequence, so the screen takes two seconds. The web app needs a different set of fields. Propose a fix.

  1. Find the cost. The services are fast; the round trips over the mobile network are slow. Seven calls at 150 ms each, partly sequential, add up to seconds.
  2. Move the fan-out inside. Inside the data center a call costs a few milliseconds, so one request from the phone should trigger the seven calls there, in parallel.
  3. Choose where. A Backend for Frontend (BFF) per client type fits: the mobile team owns a mobile BFF that returns exactly the screen’s fields. Keep the shared gateway thin.
  4. Protect the screen. Give optional parts, such as the invoice, a timeout and a fallback, so one slow service does not block the whole screen.
  5. Check. Measure the screen’s load time on a throttled network, and count requests per screen: one instead of seven.
@GetMapping("/mobile/orders/{id}")
Mono<OrderScreen> orderScreen(@PathVariable long id) {
    Mono<Order> order = orders.get().uri("/orders/{id}", id).retrieve().bodyToMono(Order.class);
    Mono<Shipment> shipment = shipping.get().uri("/shipments?order={id}", id).retrieve().bodyToMono(Shipment.class);
    Mono<Invoice> invoice = billing.get().uri("/invoices?order={id}", id).retrieve().bodyToMono(Invoice.class)
        .timeout(Duration.ofMillis(300))
        .onErrorReturn(Invoice.pending());                 // optional: never blocks the screen
    return Mono.zip(order, shipment, invoice)
        .map(t -> OrderScreen.of(t.getT1(), t.getT2(), t.getT3()));
}
The mobile BFF fetches everything in parallel and returns one response

How to answer

  • It cuts round trips for mobile clients by aggregating calls.
  • It must stay thin and generic; business rules belong in the services.
  • Run several replicas behind a load balancer, so it is not a single point of failure.
  • Services still authorize each request; the gateway only stops bad tokens early.

Common mistakes

  • Putting business logic or data joins in the gateway, which turns it into a shared monolith every team must release.
  • Trusting every request inside the network because the gateway checked it, so one compromised service can call anything.

Follow-up questions

How do services find each other in a microservices system?

Through service discovery. Instances register their address with a registry, such as Eureka or Consul, at startup, and send heartbeats; an instance that stops is removed. Callers look up a service by name and get the healthy instances. On Kubernetes, the platform does this: a Service gets a stable DNS (Domain Name System) name and virtual IP, and routes to the ready pods behind it.

  • Hard-coded hosts break as soon as instances scale, move or restart.
  • Client-side discovery asks the registry; server-side discovery goes through a router that asks it.
  • Registries cache entries, so a dead instance can be called for a few seconds; retries cover the gap.

See it in the infographic: A request through gateway, registry and balancer

What is the difference between client-side and server-side load balancing?

With client-side load balancing, the caller gets the instance list from a registry and picks one itself, as Spring Cloud LoadBalancer does: no extra hop, and the caller can retry on another instance, but every client needs the library. With server-side load balancing, callers send to one stable address, and a load balancer, an NGINX or a Kubernetes Service, picks the instance: simple clients, one more hop to run.

  • Typical algorithms are round robin, least connections and weighted random.
  • A service mesh moves client-side balancing into a sidecar proxy, with no library in the code.
  • Health checks keep failing instances out of the pool, whichever side balances.

See it in the infographic: A request through gateway, registry and balancer

How would you implement rate limiting in an API gateway that runs as several replicas?

Count requests per client key, such as the API key or the token's subject, in a shared store such as Redis, so all replicas see the same counter. A token bucket allows short bursts while capping the average rate. When a client is over the limit, answer 429 Too Many Requests with a Retry-After header. Spring Cloud Gateway's RequestRateLimiter filter does this with Redis.

  • Counters local to each replica let a client get N times the limit.
  • Limit per client and per route, since some endpoints are far costlier than others.
  • Decide what happens if Redis is down, failing open or closed.

See it in the infographic: What belongs in an API gateway

An instance crashes. How long can callers keep sending it requests, and how do you limit the damage?

Until the registry or the balancer notices. Eureka evicts after missed heartbeats, 90 seconds by default, and clients refresh their cached list every 30 seconds, so a dead instance can get traffic for a minute or two. On Kubernetes, a failing readiness probe removes the pod in seconds. Limit the damage with short connection timeouts, retries on another instance for idempotent calls, and shorter lease settings.

  • A graceful shutdown deregisters the instance before it stops.
  • Kubernetes removes a terminating pod from its Service endpoints before killing it.
  • Retries must go to a different instance, which client-side balancing allows.

See it in the infographic: A request through gateway, registry and balancer

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

A load balancer spreads traffic across instances of one service, at layer 4 by connection or at layer 7 by HTTP request, and knows little about the request's meaning. An API gateway works at the application level for many services: it routes by path, authenticates, rate limits, transforms and aggregates. Gateways often sit behind a load balancer and use one internally to reach service instances.

  • Load balancer means many instances of one thing; gateway means one door to many things.
  • Cloud load balancers already do some layer 7 routing, which blurs the line.
  • A service mesh handles traffic between services, while the gateway handles traffic from outside.

See it in the infographic: What belongs in an API gateway See it in the infographic: A request through gateway, registry and balancer

Isn't the gateway a single point of failure and a bottleneck?

Only if it runs as one instance. Run it stateless, with several replicas behind a cloud or Kubernetes load balancer, keep shared state such as rate limit counters in Redis, and scale it like any service. Keep it thin, so it adds milliseconds, not business latency.

What is the Backend for Frontend (BFF) pattern?

One small backend per client type, such as web and mobile, owned by that client's team. It aggregates and shapes data for exactly what that client's screens need, instead of one general gateway that tries to suit everyone and grows into a bottleneck for every team.

Check yourself

1. In a Spring Cloud Gateway route, what does the URI lb://orders mean?
Show answers
  • Look up the instances of orders in the registry, then pick one: Correct. lb:// sends the request through the client-side load balancer, by service name.
  • Resolve the host name orders with public DNS: Incorrect. That is http://orders; lb:// asks the discovery client.
  • Forward to a local bean named orders: Incorrect. Routes forward over the network, not to beans.
2. A team wants to compute discounts in the API gateway, because every order passes through it. What is the main risk?
Show answers
  • The gateway becomes a shared monolith that every team must change and release: Correct. Business rules couple teams through the one component they all depend on.
  • Java is too slow for discount math: Incorrect. Speed is not the issue; ownership and coupling are.
  • Gateways cannot read request bodies: Incorrect. Most gateways can; that is not why it is a bad idea.
3. The registry lists orders-1, orders-2 and orders-3, and orders-3 stops sending heartbeats. What happens to new requests once the registry drops it?
Show answers
  • They are balanced between orders-1 and orders-2: Correct. Only registered, healthy instances receive traffic.
  • Every request to orders fails: Incorrect. Two instances are still up and registered.
  • One in three still goes to orders-3: Incorrect. That happens only until the registry, and the caller's cache, drop it.