# Microservices with Spring Cloud: Service Discovery and API Gateway

> In a Spring Cloud microservices setup, what are service discovery and an API gateway, and what problem does each solve?

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-cloud-discovery-gateway
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

In a Spring Cloud microservices setup, what are service discovery and an API gateway, and what problem does each solve?

## Answer

Once you split a monolith into microservices, new problems appear that never existed before. Services now talk over the network, instances start and stop dynamically, and IP addresses change every deployment. How does the order service find the payment service if its address changes daily? And how does a mobile app talk to twenty services without knowing all of them? Service discovery and the API gateway are the standard answers.

Service discovery is like a phone directory that updates itself. Each service instance registers with a registry on startup, sending its name and address, and keeps sending heartbeats. If heartbeats stop, the registry removes the instance. Other services ask the registry for where payment-service is running and receive a list of live instances. In the Spring Cloud Netflix world, the registry is Eureka Server, enabled with @EnableEurekaServer, and clients use spring-cloud-starter-netflix-eureka-client with a spring.application.name. Alternatives include Consul, Zookeeper, or Kubernetes' own DNS-based discovery, which many teams prefer today because the platform already provides it.

Calling other services by name is made easy with client-side load balancing. Spring Cloud LoadBalancer picks an instance from the discovery list, and you use it through a @LoadBalanced RestTemplate or WebClient, or declaratively with OpenFeign, where you write an interface annotated @FeignClient(name = "payment-service") and Spring generates the HTTP client. The URL contains the logical service name, not a host and port.

The API gateway is the single front door. Clients call one address, and the gateway routes requests to the right service, for example /api/orders to order-service and /api/users to user-service. Spring Cloud Gateway, built on Spring WebFlux and Netty, defines routes with predicates such as path or header matches, and filters that modify requests and responses. Because every request passes through it, the gateway is the natural place for cross-cutting concerns: authentication and JWT validation, rate limiting, CORS, request logging, correlation ids, and TLS termination. This keeps the individual services simpler and hides the internal topology from the outside world, so you can refactor services without changing client URLs.

Related pieces to name briefly: Spring Cloud Config centralises configuration in a Git repository so services fetch their settings at startup, and refresh without redeploy is possible. Distributed tracing with Micrometer Tracing and Zipkin follows a request across services. Circuit breakers protect against failing dependencies, which is the next topic.

Be honest about trade-offs too, since seniors value that. Microservices bring operational complexity: distributed transactions, network failures, eventual consistency, debugging across services, and more infrastructure. A well-structured monolith is often the right start. If you say that in an interview, it signals judgement, not just tool knowledge. Also note that Netflix components like Ribbon and Hystrix are retired; the modern equivalents are Spring Cloud LoadBalancer and Resilience4j.

## Code examples

### Gateway routes and a Feign client

```
# gateway application.yml
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: order-service
          uri: lb://order-service            # resolved through discovery + load balancer
          predicates:
            - Path=/api/orders/**
          filters:
            - StripPrefix=1
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

// order-service calling payment-service by logical name
@FeignClient(name = "payment-service")
public interface PaymentClient {
    @PostMapping("/payments")
    PaymentResponse charge(@RequestBody PaymentRequest request);
}

@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication { }
```

lb:// tells the gateway to look up instances from the registry and balance across them; Feign builds the HTTP client from the interface.

## Key points

- Discovery removes hard-coded hosts; instances register and send heartbeats.
- Gateway centralises routing, auth, rate limiting and CORS.
- Ribbon and Hystrix are retired; use Spring Cloud LoadBalancer and Resilience4j.
- On Kubernetes, native service DNS can replace Eureka.

## Common follow-up questions

- Client-side versus server-side load balancing?
- How would you secure service-to-service calls?
- When should you not use microservices?

## Interview tips

- Explain the problem each component solves before naming tools.
- Mention that a monolith can be the better choice, it shows judgement.

## Concepts covered

Microservices, Eureka, API Gateway, Spring Cloud

Previous: [Spring AOP: Aspects, Advice and Proxies](https://www.internhack.in/learn/interview/spring-boot-interview/spring-aop-basics) · Next: [Circuit Breaker and Resilience4j](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circuit-breaker-resilience4j) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Testing: @SpringBootTest vs @WebMvcTest vs @DataJpaTest](https://www.internhack.in/learn/interview/spring-boot-interview/spring-testing-slices)
- [Testing Controllers with MockMvc and Mockito](https://www.internhack.in/learn/interview/spring-boot-interview/spring-mockito-mockmvc-testing)
- [Circular Dependencies in Spring and How to Fix Them](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circular-dependencies)
- [Spring vs Spring Boot: What Problem Does Boot Solve?](https://www.internhack.in/learn/interview/spring-boot-interview/spring-vs-spring-boot)
- [Inversion of Control and Dependency Injection Explained](https://www.internhack.in/learn/interview/spring-boot-interview/spring-ioc-dependency-injection)
- [Constructor vs Setter vs Field Injection](https://www.internhack.in/learn/interview/spring-boot-interview/spring-injection-types-constructor-preferred)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
