Spring Boot & Spring Cloud
Spring Cloud for Microservices: Config Server, Discovery, Gateway and Resilience
Advanced8 min readUpdated
You will be able to explain which distributed-system problems Spring Cloud solves and which projects solve them today: run a Config Server and refresh clients, register services with Eureka and call them by name through a load-balanced RestClient, route external traffic through Spring Cloud Gateway, and protect calls with Resilience4j circuit breakers, all on Spring Boot 3 with the 2023 and 2024 release trains.
What you will learn
- Map the recurring problems of a microservice architecture to the Spring Cloud projects that address them
- Set up Spring Cloud Config Server with a Git backend and refresh client configuration at runtime
- Register services with Eureka and call them by logical name through a load-balanced RestClient or HTTP interface
- Define routes, predicates and filters in Spring Cloud Gateway
- Wrap remote calls in Resilience4j circuit breakers, retries and time limiters and explain when each helps
- Identify retired Spring Cloud Netflix components and their current replacements
Splitting one application into a dozen services replaces a set of problems you had solved (a method call, a shared configuration file, a single log) with problems you have not: where is the other service, how does it get its configuration, what happens when it is slow, and how does traffic from outside reach the right one. Spring Cloud is the umbrella for the Spring projects that address those problems on top of Spring Boot. It has changed a great deal since the Netflix-based first generation, so this page describes the current landscape for Spring Boot 3 and shows the core of each piece: configuration, discovery, load balancing, the gateway and resilience.
Release trains and the current line-up
Spring Cloud is not one library but a coordinated set of projects released together as a release train whose version is imported as a BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2024.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Each train targets a Spring Boot minor line; mixing a train with the wrong Boot version produces obscure failures at startup. The projects you will meet most:
| Problem | Project | Notes |
|---|---|---|
| Centralised, versioned configuration | Spring Cloud Config | Git, Vault, JDBC and file backends |
| Service registry | Spring Cloud Netflix Eureka, Consul, Zookeeper, Kubernetes | Eureka is the only remaining Netflix component |
| Client-side load balancing | Spring Cloud LoadBalancer | Replaced Ribbon |
| Declarative HTTP clients | Spring Cloud OpenFeign (maintenance), Spring Framework HTTP interfaces | Both integrate with LoadBalancer |
| API gateway | Spring Cloud Gateway | Replaced Zuul; reactive core, with a servlet variant |
| Circuit breaking | Spring Cloud Circuit Breaker with Resilience4j | Replaced Hystrix |
| Event-driven messaging | Spring Cloud Stream | Binders for Kafka, RabbitMQ and others |
| Configuration broadcast | Spring Cloud Bus | Propagates refresh events over a broker |
| Consumer-driven contracts | Spring Cloud Contract | Stubs generated from contracts |
Distributed tracing left Spring Cloud when Sleuth was retired; it is now Micrometer Tracing in Boot itself, covered in the observability guide.
Centralised configuration
Twelve services with twelve application.yml files, each with the same database host and message broker address, drift apart within weeks. Spring Cloud Config Server serves configuration from a versioned backend, most often a Git repository, keyed by application name, profile and label (branch or tag):
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication { /* main */ }
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://git.example.com/platform/config.git
default-label: main
search-paths: '{application}' # one folder per service
clone-on-start: true
The repository holds application.yml (shared by all), orders.yml, orders-prod.yml and so on; GET /orders/prod/main returns the merged property sources for the orders service in the prod profile. Encrypted values can be stored as {cipher}... and decrypted by the server with a symmetric key or key pair, which keeps secrets out of plain text in Git without a separate vault, although Spring Cloud Vault or a cloud secret manager is the stronger option.
Clients add spring-cloud-starter-config and point at the server through the config-import mechanism from Boot 2.4 onwards:
spring:
application:
name: orders # becomes {application} in the request
config:
import: "optional:configserver:http://config:8888"
cloud:
config:
fail-fast: true # refuse to start without configuration in production
retry:
max-attempts: 6
The old bootstrap.yml approach still exists behind spring-cloud-starter-bootstrap but is legacy; spring.config.import is the current model and integrates with the property precedence described in the configuration guide.
Changing a value in Git does not change a running service until it re-reads its configuration. Expose the refresh Actuator endpoint and POST to it, and Boot re-binds @ConfigurationProperties beans and re-creates beans annotated @RefreshScope:
@RefreshScope
@Service
class PricingService {
private final BigDecimal surcharge;
PricingService(@Value("${pricing.surcharge}") BigDecimal surcharge) {
this.surcharge = surcharge; // a new instance is created on the next call after a refresh
}
}
Refreshing each instance by hand does not scale; Spring Cloud Bus connects the services to Kafka or RabbitMQ so that one POST /actuator/busrefresh on any instance (or a webhook from the Git host to the Config Server's /monitor endpoint) fans out to all of them. @RefreshScope proxies the bean, which costs a little per call and interacts badly with @Scheduled and with beans that hold connections; prefer @ConfigurationProperties, which are re-bound in place, for most refreshable settings.
Service discovery and load balancing
Hard-coding http://orders-2.internal:8080 fails the first time an instance is replaced. A service registry lets each instance register its name and address on startup, send heartbeats, and deregister on shutdown; clients ask the registry for the current instances of orders and pick one.
Eureka is the registry most Spring Cloud material describes. The server is a Boot application with spring-cloud-starter-netflix-eureka-server and @EnableEurekaServer; each service adds spring-cloud-starter-netflix-eureka-client and registers under its spring.application.name:
eureka:
client:
service-url:
defaultZone: http://eureka-1:8761/eureka/,http://eureka-2:8761/eureka/
instance:
prefer-ip-address: true
lease-renewal-interval-in-seconds: 10
Eureka favours availability over consistency: instances stay listed for a while after they die, and a server that loses contact with its peers keeps serving its last known registry (self-preservation mode). Clients therefore need retries and timeouts regardless; the registry is a cache, not a truth.
The client side is Spring Cloud LoadBalancer, which resolves a logical host name to an instance and applies a round-robin (default) or random policy. Boot 3.2+ services should use a load-balanced RestClient:
@Configuration
class ClientConfig {
@Bean
@LoadBalanced
RestClient.Builder loadBalancedRestClientBuilder() {
return RestClient.builder();
}
@Bean
InventoryApi inventoryApi(@LoadBalanced RestClient.Builder builder) {
RestClient client = builder.baseUrl("http://inventory").build(); // "inventory" is a service name
return HttpServiceProxyFactory.builderFor(RestClientAdapter.create(client))
.build().createClient(InventoryApi.class);
}
}
@LoadBalanced marks the builder so that an interceptor replaces inventory with a real host and port on every call. Spring Cloud OpenFeign offers the same through @FeignClient(name = "inventory") interfaces, with a richer set of contract annotations and encoders; it remains supported, but new code should prefer the framework's HTTP interfaces, which need no extra project and work with the same load balancer.
On Kubernetes, all of this is optional. A Service named inventory already resolves by DNS to a load-balanced virtual IP, so http://inventory works with a plain RestClient and no registry. Spring Cloud Kubernetes exists for applications that want the DiscoveryClient abstraction to read Kubernetes endpoints, mostly for hybrid deployments.
The gateway
External clients should not know your service topology. An API gateway is the single entry point that routes requests to services, terminates TLS, applies authentication and rate limits, and rewrites paths. Spring Cloud Gateway is built on Spring WebFlux and Project Reactor (a servlet-based variant, Spring Cloud Gateway Server MVC, exists for teams that want a blocking stack), and routes are declared in configuration or Java:
spring:
cloud:
gateway:
routes:
- id: orders
uri: lb://orders # lb:// resolves through the load balancer and registry
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1 # /api/orders/42 -> /orders/42 on the service
- name: CircuitBreaker
args:
name: ordersBreaker
fallbackUri: forward:/fallback/orders
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 50
redis-rate-limiter.burstCapacity: 100
- id: catalogue
uri: http://catalogue:8080
predicates:
- Path=/api/catalogue/**
- Method=GET
filters:
- AddResponseHeader=Cache-Control, public, max-age=60
A predicate decides whether a route matches (path, method, header, host, query, time of day); a filter transforms the request or response (strip or rewrite paths, add headers, retry, rate limit, circuit-break, relay an OAuth 2.0 token). Global filters apply to every route and are where correlation ids, request logging and authentication typically live. With Spring Security's OAuth 2.0 resource-server support the gateway validates access tokens once and forwards them, so downstream services can trust the Authorization header; the TokenRelay filter handles the forwarding.
In the 2025.0 release train the gateway artifacts were renamed to make the two stacks explicit (spring-cloud-starter-gateway-server-webflux and spring-cloud-starter-gateway-server-webmvc, with property prefixes under spring.cloud.gateway.server.*); the older names remain available for a transition period. Check the reference documentation for the train you use before copying property names.
Resilience: circuit breakers, retries and time limits
A slow dependency is more dangerous than a dead one: threads pile up waiting, and the caller becomes slow for everyone. Resilience4j provides the patterns and Spring Cloud Circuit Breaker wraps them behind a vendor-neutral factory:
@Service
class RecommendationService {
private final CircuitBreakerFactory<?, ?> breakers;
private final RecommendationApi api;
RecommendationService(CircuitBreakerFactory<?, ?> breakers, RecommendationApi api) {
this.breakers = breakers;
this.api = api;
}
List<Product> forCustomer(long customerId) {
return breakers.create("recommendations")
.run(() -> api.recommend(customerId),
throwable -> List.of()); // fallback: an empty list, not an error page
}
}
resilience4j:
circuitbreaker:
instances:
recommendations:
sliding-window-size: 20
failure-rate-threshold: 50 # open after 50 % failures in the window
wait-duration-in-open-state: 30s
permitted-number-of-calls-in-half-open-state: 5
timelimiter:
instances:
recommendations:
timeout-duration: 800ms
A circuit breaker counts failures in a sliding window; past the threshold it opens and fails calls immediately without touching the dependency, then after a wait lets a few trial calls through (half-open) and closes again if they succeed. A time limiter bounds how long a call may take. A retry repeats a failed call with backoff, which helps for transient errors and hurts for overload, so combine it with the breaker and keep attempts low. A bulkhead caps concurrent calls to one dependency so a slow one cannot consume every thread. The resilience4j-spring-boot3 starter also offers annotations (@CircuitBreaker(name = "recommendations", fallbackMethod = "empty")) applied through AOP, and publishes state and metrics to Actuator and Micrometer.
Fallbacks must be meaningful: an empty recommendation list, a cached price, a "try again later" response with a Retry-After header. A fallback that silently returns stale or made-up data is a bug with a delay.
Putting it together
A minimal but realistic topology on virtual machines: two Config Server instances backed by one Git repository; two Eureka instances that register with each other; a gateway that routes /api/** to services by name with a circuit breaker per route; each service pulling configuration on startup, registering with Eureka, calling peers through load-balanced HTTP interfaces protected by Resilience4j, and reporting health, metrics and traces through Actuator. On Kubernetes, remove Eureka and possibly the Config Server (ConfigMaps and Secrets with spring.config.import=kubernetes: or mounted config trees), keep the gateway or replace it with an ingress plus per-service security, and keep the resilience layer, which no platform provides for you.
Common mistakes
Mixing release trains and Boot versions. The BOM must match the Boot minor; symptoms range from NoSuchMethodError at startup to beans silently missing.
Copying Hystrix, Ribbon or Zuul examples. They will not compile against current trains. Translate to Resilience4j, Spring Cloud LoadBalancer and Spring Cloud Gateway.
Treating the registry as authoritative. Instances that crashed remain listed until their lease expires. Every client needs timeouts and retries with backoff independent of discovery.
Refreshing with @RefreshScope on beans that hold state or resources. The proxy recreates the bean, dropping caches, connection pools and scheduled tasks. Re-bind @ConfigurationProperties instead, and keep @RefreshScope for beans that are cheap to rebuild.
A single Config Server or registry instance. Both are on the critical path at startup; run at least two, and set fail-fast deliberately depending on whether a service may start with stale local defaults.
Retrying non-idempotent calls. A retried POST /payments charges twice. Retry only idempotent operations, or make the operation idempotent with a client-generated key.
Putting business logic in gateway filters. The gateway should route, secure, limit and observe. Transformation of payloads and orchestration belong in services, where they can be tested and versioned with the domain.
Key takeaways
- Spring Cloud is a set of coordinated projects released as trains; import the BOM that matches your Spring Boot minor and never mix them.
- Config Server serves versioned configuration from Git by application, profile and label; clients import it with
spring.config.importand refresh through Actuator or Spring Cloud Bus. - Discovery (Eureka, Consul, Kubernetes) plus Spring Cloud LoadBalancer let services call each other by name through a
@LoadBalancedRestClientor HTTP interface; on Kubernetes, DNS often makes the registry unnecessary. - Spring Cloud Gateway routes external traffic with predicates and filters, and is where authentication, rate limiting and per-route circuit breakers belong.
- Resilience4j circuit breakers, time limiters, retries and bulkheads keep one slow dependency from taking down the caller; fallbacks must return something the business can accept.
- Hystrix, Ribbon and Zuul are gone; Sleuth became Micrometer Tracing; OpenFeign is in maintenance mode in favour of Spring's HTTP interfaces.
Sources and further reading
Frequently asked questions
- Which Spring Cloud version works with my Spring Boot version?
- Spring Cloud ships release trains named after London tube stations and, since 2020, by year. The 2023.0.x train (Leyton) targets Spring Boot 3.2 and 3.3; 2024.0.x (Moorgate) targets Boot 3.4; 2025.0.x (Northfields) targets Boot 3.5. Import the spring-cloud-dependencies BOM for the matching train and let it manage every spring-cloud-starter version; the compatibility table on the Spring Cloud project page is the authority.
- Do I still need Eureka on Kubernetes?
- Usually not. Kubernetes Services already provide DNS-based discovery and load balancing, and a Spring Cloud Gateway or ingress controller can route by service name. Eureka still makes sense on virtual machines, on platforms without a service abstraction, or when you need client-side load-balancing decisions that Kubernetes does not offer. Spring Cloud Kubernetes bridges the two when a code base must run on both.
- Is Spring Cloud OpenFeign deprecated?
- It is in maintenance mode: it receives bug fixes and stays compatible with new release trains, but the Spring team recommends the HTTP interface clients built into Spring Framework 6 for new code. Existing Feign clients keep working; a migration can be done gradually, interface by interface, because both are declarative interfaces backed by a load-balanced client.
- What happened to Hystrix, Ribbon and Zuul?
- Netflix stopped developing them, and Spring Cloud removed their integrations in the 2020.0 (Ilford) release train. Their replacements are Spring Cloud Circuit Breaker with Resilience4j for Hystrix, Spring Cloud LoadBalancer for Ribbon, and Spring Cloud Gateway for Zuul. Eureka is the only Netflix component that remains in Spring Cloud Netflix.