← Spring Boot & Microservices Interview Guide
Chapter 44 min read

Spring Cloud Interview Questions

Service discovery with Eureka, API gateway design with Spring Cloud Gateway vs Zuul, and the questions that test whether you've actually run these in a multi-instance deployment.

Q12. Explain service discovery with Netflix Eureka.

1. Eureka server

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {}
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

2. Eureka client, on each microservice

@SpringBootApplication
@EnableEurekaClient
public class UserServiceApplication {}
spring.application.name=user-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
eureka.instance.prefer-ip-address=true

3. How it actually works at runtime

  1. Each service registers itself with the Eureka server on startup
  2. It sends a heartbeat roughly every 30 seconds to stay registered
  3. Other services query Eureka to discover available instances
  4. Client-side load balancing then picks an instance from that list — Eureka itself doesn't route traffic

4. Discovering instances in code

@Autowired
private DiscoveryClient discoveryClient;

public List<ServiceInstance> getInstances() {
    return discoveryClient.getInstances("user-service");
}

The production detail worth volunteering unprompted: run at least three Eureka server instances behind a load balancer for high availability — a single Eureka instance is a single point of failure for your entire service registry, which means a single point of failure for every service trying to discover every other service.

Q13. What is API Gateway? Explain Spring Cloud Gateway vs Zuul.

API Gateway Purpose:

  • Single entry point for all clients
  • Routing requests to microservices
  • Authentication & authorization
  • Rate limiting
  • Load balancing

Spring Cloud Gateway (Recommended)

@Configuration
public class GatewayConfig {
    
    @Bean
    public RouteLocator customRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("user-service", r -> r
                .path("/users/**")
                .uri("lb://user-service"))
            .route("order-service", r -> r
                .path("/orders/**")
                .filters(f -> f
                    .addRequestHeader("X-Request-Source", "Gateway")
                    .circuitBreaker(c -> c
                        .setName("orderCB")
                        .setFallbackUri("/fallback")))
                .uri("lb://order-service"))
            .build();
    }
}

Comparison:

FeatureZuulSpring Cloud Gateway
ArchitectureBlocking (Servlet)Non-blocking (WebFlux)
PerformanceGoodExcellent
StatusMaintenance modeActive development
UseLegacy systemsNew projects

Gateway is the better default for new Spring Cloud systems because it is actively developed and non-blocking, while Zuul is mainly relevant when maintaining an existing servlet-based deployment. The important design question is what belongs at the edge versus in the services themselves.

Q26. Explain Spring Cloud Config Server with Git backend

1. Config Server Setup

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApp {}
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/company/config-repo
spring.cloud.config.server.git.default-label=main
spring.cloud.config.server.git.search-paths=configs/{application}

2. Git Repository Structure

config-repo/
├── application.yml           # Common to all services
├── user-service.yml          # User service specific
├── user-service-dev.yml      # User service dev profile
├── user-service-prod.yml     # User service prod profile
└── order-service.yml

3. Client Configuration

spring.application.name=user-service
spring.profiles.active=prod
spring.cloud.config.uri=http://localhost:8888
spring.cloud.config.fail-fast=true

4. Refresh Configuration

@RefreshScope
@RestController
public class ConfigController {
    
    @Value("${app.message}")
    private String message;
    
    @GetMapping("/message")
    public String getMessage() {
        return message;  // Refreshed on /actuator/refresh POST
    }
}

5. Encrypted Properties

# In config file
database.password={cipher}AQA7grH5K...

Config Server centralizes configuration and keeps changes versioned, but it also puts availability and access control for configuration on the critical path. Treat the repository and encryption keys as production infrastructure, not as ordinary application settings.

Q27. Explain OpenFeign for declarative REST clients

1. Enable Feign

@SpringBootApplication
@EnableFeignClients
public class Application {}

2. Feign Client Interface

@FeignClient(name = "user-service", url = "http://localhost:8080")
public interface UserClient {
    
    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable("id") Long id);
    
    @PostMapping("/api/users")
    User createUser(@RequestBody User user);
    
    @DeleteMapping("/api/users/{id}")
    void deleteUser(@PathVariable("id") Long id);
}

3. With Eureka (Load Balanced)

@FeignClient(name = "user-service")  // Service name in Eureka
public interface UserClient {
    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable Long id);
}

4. Custom Configuration

@Configuration
public class FeignConfig {
    
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            template.header("Authorization", "Bearer token");
            template.header("X-Service-Name", "order-service");
        };
    }
    
    @Bean
    public ErrorDecoder errorDecoder() {
        return new CustomErrorDecoder();
    }
}

5. Fallback Support

@FeignClient(
    name = "user-service",
    fallback = UserClientFallback.class
)
public interface UserClient {
    @GetMapping("/api/users/{id}")
    User getUserById(@PathVariable Long id);
}

@Component
public class UserClientFallback implements UserClient {
    @Override
    public User getUserById(Long id) {
        return new User(id, "Default User");
    }
}

Feign removes repetitive HTTP plumbing, but it does not remove network failure modes; define timeouts, error mapping, retries, and fallback behavior deliberately rather than accepting client defaults.

Q28. What is Spring Cloud Bus and when to use it?

Spring Cloud Bus links nodes of distributed system with lightweight message broker to broadcast state changes.

Use Cases:

  • Refresh configuration across all instances
  • Broadcast events to multiple services
  • Invalidate cache across instances

Setup with RabbitMQ:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

Configuration:

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
management.endpoints.web.exposure.include=bus-refresh

Refresh All Instances:

POST /actuator/bus-refresh
# Refreshes all connected microservice instances

Custom Events:

@Component
public class CustomEventPublisher {
    
    @Autowired
    private ApplicationEventPublisher publisher;
    
    public void publishEvent() {
        publisher.publishEvent(new RemoteApplicationEvent(
            this, "originService", "destinationService"));
    }
}

@Component
public class CustomEventListener {
    
    @EventListener
    public void handleEvent(RemoteApplicationEvent event) {
        // Handle event
    }
}

Bus is useful when many instances must react to the same configuration or domain event, but it adds broker dependency and delivery semantics that must be monitored. Use it when broadcast coordination is worth that operational complexity, not merely because a refresh endpoint exists.

Krishna Kumar Yadav

Krishna Kumar Yadav

Senior Software Engineer building distributed systems at scale. 9+ years across fintech, airline tech, and startups.