Microservices with Spring Cloud
Build cloud microservices. Understand service discovery (Eureka), API gateways, configuration services, and resilience patterns.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is a microservices architecture and how does Spring Boot support it?
Microservices architecture structures an application as a collection of small, independently deployable services, each owning a single business capability and its own data store, communicating over the network via REST, messaging, or gRPC instead of in-process method calls the way a monolith would.
Spring Boot is well suited to microservices because each service can be an independently runnable, self-contained JAR with an embedded server, and the broader Spring Cloud ecosystem adds the cross-cutting concerns microservices need — service discovery (Eureka), centralized configuration (Config Server), routing (Gateway), resilience (Resilience4j), and distributed tracing — without which independent services would be hard to operate reliably at scale.
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
Q2. What is Service Discovery and how does Eureka work in Spring Cloud?
In a microservices system, service instances scale up/down and their network locations change dynamically, so hardcoding IP addresses and ports doesn't work. Service Discovery solves this: each service registers itself with a central registry on startup, and other services query the registry to find available instances at runtime instead of using a fixed address.
Netflix Eureka, integrated via Spring Cloud Netflix, provides this registry. A Eureka Server is run as its own Spring Boot app with @EnableEurekaServer; each microservice becomes a Eureka Client with @EnableEurekaClient (or auto-detected via the client dependency), sending periodic heartbeats to stay registered, and load-balanced calls between services are resolved by service name rather than a hardcoded host.
@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServerApplication { ... }
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
Q3. What is an API Gateway and how does Spring Cloud Gateway work?
An API Gateway is a single entry point that sits in front of all microservices, routing incoming requests to the correct downstream service and centralizing cross-cutting concerns like authentication, rate limiting, request/response logging, and CORS, so individual services don't need to reimplement them.
Spring Cloud Gateway, built on Project Reactor for non-blocking, reactive routing, matches requests to routes based on predicates (path, header, method) and applies filters (add headers, rewrite paths, apply a circuit breaker) before forwarding the request, often resolving the destination service dynamically through Eureka rather than a hardcoded URL.
spring:
cloud:
gateway:
routes:
- id: order-service
uri: lb://ORDER-SERVICE
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1
Q4. What is Spring Cloud Config Server and why is centralized configuration important?
In a microservices system with dozens of services, each with its own environment-specific properties, managing configuration per-service becomes unmanageable and makes rotating a shared value (like a database URL) require redeploying every service individually.
Spring Cloud Config Server centralizes configuration in one place — typically a Git repository — and serves it to every microservice at startup over HTTP. Each service, acting as a Config Client, fetches its configuration from the Config Server based on its application name and active profile, and combined with Spring Cloud Bus, configuration changes can even be broadcast to running services without a restart.
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication { ... }
spring:
config:
import: "configserver:http://localhost:8888"
Q5. What is a Circuit Breaker pattern and how does Resilience4j implement it in Spring Boot?
The Circuit Breaker pattern prevents a failing downstream service from cascading failure across the whole system: when calls to a dependency fail repeatedly past a threshold, the circuit "opens" and further calls fail fast (or fall back to a default) without even attempting the network call, giving the failing service time to recover instead of piling up more load and threads on it.
Resilience4j is the modern standard for this in Spring Boot (replacing the now-deprecated Netflix Hystrix), used via @CircuitBreaker with a configured failure-rate threshold, wait duration in the open state, and a fallback method that's invoked when the circuit is open or the call fails.
@CircuitBreaker(name = "inventoryService", fallbackMethod = "fallback")
public Inventory checkStock(String productId) {
return inventoryClient.getStock(productId);
}
public Inventory fallback(String productId, Throwable t) {
return new Inventory(productId, 0, "Service unavailable, showing default");
}
Q6. What is Feign Client and how does it simplify inter-service communication?
OpenFeign is a declarative HTTP client: instead of manually building HTTP requests with RestTemplate or WebClient, you define a Java interface annotated with the target service's endpoints, and Spring generates the implementation at runtime — calling another microservice looks like calling a local method.
Feign integrates with Eureka for service discovery (using the service's registered name instead of a hardcoded URL) and with Resilience4j or Hystrix for automatic circuit breaking, and supports custom encoders, decoders, and interceptors for things like propagating an auth header on every outgoing call.
@FeignClient(name = "inventory-service")
public interface InventoryClient {
@GetMapping("/api/inventory/{productId}")
Inventory getStock(@PathVariable String productId);
}
@Service
public class OrderService {
private final InventoryClient inventoryClient;
}
Q7. How does distributed tracing work in Spring Cloud microservices (Sleuth, Micrometer Tracing, Zipkin)?
A single user request in a microservices system often flows through multiple services, making it hard to debug latency or failures using each service's isolated logs alone. Distributed tracing solves this by tagging a request with a unique trace ID when it enters the system, propagating that ID across every downstream service call, and recording a span (with timing) for each hop.
Micrometer Tracing (the modern replacement for Spring Cloud Sleuth) instruments requests automatically, injecting trace and span IDs into logs and outgoing headers so they carry through Feign calls, RestTemplate, and messaging. The collected spans are typically exported to Zipkin or Jaeger, which visualize the full request path across services as a single timeline, making it possible to pinpoint exactly which service introduced latency or an error.
management:
tracing:
sampling:
probability: 1.0
zipkin:
tracing:
endpoint: http://localhost:9411/api/v2/spans
Q8. What is Load Balancing in Spring Cloud and how does Spring Cloud LoadBalancer work?
When a service has multiple running instances for scalability and fault tolerance, calls to it need to be distributed across those instances rather than always hitting one. Client-side load balancing resolves the service name (from Eureka) to a specific instance address at call time, choosing among healthy instances using a strategy like round-robin.
Spring Cloud LoadBalancer is the current standard (replacing the deprecated Netflix Ribbon), integrated transparently with RestTemplate (via @LoadBalanced), WebClient, and Feign — application code calls the logical service name, and the load balancer picks and routes to a healthy instance behind the scenes.
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
restTemplate.getForObject("http://ORDER-SERVICE/api/orders/1", Order.class);
Q9. How do microservices handle distributed transactions (Saga pattern)?
Because each microservice owns its own database, a traditional ACID transaction spanning multiple services isn't possible — there's no single database to commit or roll back atomically. The Saga pattern solves this by breaking a business transaction into a sequence of local transactions, each executed by a different service, with each step publishing an event or message that triggers the next step.
If a step fails partway through, previously completed steps are undone using compensating transactions (e.g. if payment succeeds but shipping fails, a compensating "refund payment" transaction runs) rather than a database-level rollback. Sagas are commonly implemented as either choreography (services react to each other's events independently, no central coordinator) or orchestration (a central saga orchestrator explicitly directs each step), with orchestration being easier to reason about as complexity grows.
// Choreography: OrderCreated -> InventoryReserved -> PaymentProcessed
// If PaymentFailed, a compensating InventoryReleased event follows
Q10. What is the difference between orchestration and choreography in microservices communication?
Choreography is a decentralized communication style where each service publishes events about what happened, and other services subscribe and react independently, with no single service directing the overall flow — similar to dancers each following their own cues. It scales well and keeps services loosely coupled, but the overall business process becomes harder to see and debug since it's implicit across many services.
Orchestration is centralized: a dedicated orchestrator service explicitly calls each participating service in sequence and manages the overall workflow state, similar to a conductor directing an orchestra. This makes the process easy to understand, monitor, and modify in one place, at the cost of introducing a central component that can become a bottleneck or single point of coordination failure if not designed carefully.
// Choreography: services react to events, no central control
// Orchestration: a central saga orchestrator calls each service explicitly
orderSagaOrchestrator.reserveInventory(orderId);
orderSagaOrchestrator.processPayment(orderId);
orderSagaOrchestrator.confirmShipping(orderId);
Microservices with Spring Cloud
Build cloud microservices. Understand service discovery (Eureka), API gateways, configuration services, and resilience patterns.
What is a microservices architecture and how does Spring Boot support it?
Microservices architecture structures an application as a collection of small, independently deployable servic...
What is Service Discovery and how does Eureka work in Spring Cloud?
In a microservices system, service instances scale up/down and their network locations change dynamically, so...
What is an API Gateway and how does Spring Cloud Gateway work?
An API Gateway is a single entry point that sits in front of all microservices, routing incoming requests to t...
What is Spring Cloud Config Server and why is centralized configuration important?
In a microservices system with dozens of services, each with its own environment-specific properties, managing...
What is a Circuit Breaker pattern and how does Resilience4j implement it in Spring Boot?
The Circuit Breaker pattern prevents a failing downstream service from cascading failure across the whole syst...
What is Feign Client and how does it simplify inter-service communication?
OpenFeign is a declarative HTTP client: instead of manually building HTTP requests with RestTemplate or WebCli...
How does distributed tracing work in Spring Cloud microservices (Sleuth, Micrometer Tracing, Zipkin)?
A single user request in a microservices system often flows through multiple services, making it hard to debug...
What is Load Balancing in Spring Cloud and how does Spring Cloud LoadBalancer work?
When a service has multiple running instances for scalability and fault tolerance, calls to it need to be dist...
How do microservices handle distributed transactions (Saga pattern)?
Because each microservice owns its own database, a traditional ACID transaction spanning multiple services isn...
What is the difference between orchestration and choreography in microservices communication?
Choreography is a decentralized communication style where each service publishes events about what happened, a...