Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 66 ยท Production Features

Microservices with Spring Cloud

A map of Spring Cloud for Boot developers: monolith versus microservices, Eureka discovery, OpenFeign calls, Config Server and Gateway, with runnable stand-ins.

Most Spring Boot applications start life as one deployable program, a monolith, and many stay that way happily. Some grow into several smaller services that are built, deployed and scaled independently. Once you have several services, new questions appear: how does one service find another, where does shared configuration live, how do outside clients reach all of them through one address? Spring Cloud is a family of projects built on Spring Boot that answers those questions.

This lesson is a map for Boot developers. It shows what each piece does, how little Boot code it takes, and how the pieces fit together. Each piece has its own deeper lesson in the Advanced Java tutorial, linked below; here you get the big picture plus two runnable stand-ins. Spring Cloud is not on this site's Java runner, so the real code is read-only and the demos are plain Java.

Monolith or microservices?

Monolith

One deployable One build, one release, one database.
Method calls Fast, transactional, easy to debug.
Shared fate One bug or load spike affects everything.

The right start for most teams.

1 / 2

Microservices trade simple code for independent deployment. They help when separate teams need to release separately, parts of the system scale very differently, or a failure must stay contained. They hurt when a small team splits a small system, because every method call becomes a network call that can time out, and every cross-service rule becomes a distributed-systems problem. A modular monolith (clear packages, one deployable) is a strong first step, and a split can follow along those same boundaries. The full discussion is in Microservices.

The Spring Cloud toolbox

Need Spring Cloud piece Deeper lesson
Services find each other by name Eureka server and client (service discovery) Service Discovery with Eureka
Call another service readably and pick an instance OpenFeign and Spring Cloud LoadBalancer Load Balancing and OpenFeign
Central configuration for all services Spring Cloud Config Server and client Config Server
One entry point for outside clients Spring Cloud Gateway API Gateway
Survive slow or failing dependencies Resilience4j circuit breakers Circuit Breakers and Resilience, Resilience
See a request across services Micrometer Tracing Observability

Spring Cloud is versioned in release trains named after a year (such as 2025.0), and each train supports specific Spring Boot versions. Pick the Spring Cloud version from the compatibility table for your Boot version and import its BOM; never mix versions by hand.

XML
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

Discovery: Eureka server and client

The registry is an ordinary Boot application with one dependency and one annotation:

Java
@SpringBootApplication
@EnableEurekaServer
public class RegistryApplication {
    public static void main(String[] args) { SpringApplication.run(RegistryApplication.class, args); }
}

A service that should be discoverable adds spring-cloud-starter-netflix-eureka-client and a name and registry address:

YAML
spring:
  application:
    name: catalog-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

On startup the service registers itself under CATALOG-SERVICE, then sends heartbeats. Other services ask the registry for the instances behind that name instead of using a fixed host and port.

Calling another service with OpenFeign

A Feign client is an interface; Spring generates the HTTP code. The URL contains only the service name:

Java
@FeignClient(name = "catalog-service")
interface CatalogClient {

    @GetMapping("/books/{id}")
    BookDto find(@PathVariable long id);
}

@Service
class OrderService {
    private final CatalogClient catalog;
    OrderService(CatalogClient catalog) { this.catalog = catalog; }

    Receipt place(long bookId) {
        BookDto book = catalog.find(bookId);      // resolved through discovery, then load-balanced
        return new Receipt(book.title(), book.priceInCents());
    }
}

Add @EnableFeignClients to a configuration class. If you prefer no extra library, Spring's own RestClient or declarative HTTP interface clients (see HTTP Clients) work with a load-balanced builder in the same way. Whatever you use, set timeouts and combine the call with a circuit breaker; a remote call without a timeout is how one slow service takes down the others.

Central config and the gateway

With Config Server, a service no longer holds all its settings; it imports them at startup:

YAML
spring:
  application:
    name: order-service
  config:
    import: "optional:configserver:http://localhost:8888"

The server itself is another Boot application, with the spring-cloud-config-server dependency and one annotation, pointed at the repository that holds the files:

Java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); }
}
YAML
server:
  port: 8888
spring:
  cloud:
    config:
      server:
        git:
          uri: https://git.example.com/platform/config-repo
          default-label: main

A client can read a value from that central source like any other property (@Value("${shop.banner}") or a @ConfigurationProperties class), and with Actuator's refresh support a @RefreshScope bean picks up a changed value without a restart. The server reads files such as order-service-prod.yml from the Git repository, so a configuration change is a reviewed commit. The gateway is the front door. Clients talk to one address and the gateway routes by path, using discovery to find the target:

YAML
spring:
  cloud:
    gateway:
      server:
        webflux:
          routes:
            - id: catalog
              uri: lb://catalog-service
              predicates:
                - Path=/api/books/**
              filters:
                - StripPrefix=1
            - id: orders
              uri: lb://order-service
              predicates:
                - Path=/api/orders/**
              filters:
                - StripPrefix=1

The lb:// scheme means "look the name up and load-balance". Property and starter names changed in the 2025.0 train (spring-cloud-starter-gateway-server-webflux), so check your version; the API Gateway lesson lists both spellings.

If your system runs on Kubernetes, the platform already provides discovery (a Service name resolves through DNS), load balancing, config maps and ingress. Many teams use Spring Boot with Kubernetes and skip Eureka, Config Server and Gateway. Spring Cloud is most valuable when you are not on such a platform, or for its Gateway, Feign and Resilience4j integrations.

How the pieces cooperate (stand-in)

The first demo is a small in-process "cloud" built from the same ideas: a registry that services register with, a client-side load balancer that picks instances round-robin and skips the ones that fail, and inter-service calls that go by name. What is real: the call-by-name flow and the failover idea. What is simplified: calls are method calls, there are no heartbeats (see the Eureka lesson for those) and no timeouts.

Java Registry, load balancing and a call between services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Heartbeats, leases and deregistration (stand-in)

The first demo skips something Eureka does all the time: it has to notice when an instance disappears. An instance holds a lease in the registry. It renews the lease with a heartbeat every 30 seconds by default (eureka.instance.lease-renewal-interval-in-seconds). If the registry hears nothing for 90 seconds (lease-expiration-duration-in-seconds), a background eviction task removes the instance, so clients stop being sent to it. A service that shuts down cleanly deregisters itself right away, which Boot does when the application context closes; a crash, a kill -9 or a network split leaves the lease to expire.

Two details are worth knowing. First, clients cache the registry and refresh it every 30 seconds (registry-fetch-interval-seconds), so after an instance dies there is a short window in which a caller can still pick it; that is why calls need timeouts, retries and a circuit breaker, not only discovery. Second, the Eureka server has self-preservation mode: if far more heartbeats than expected go missing at once, it assumes the network is the problem, not the services, and stops evicting. The dashboard then shows a red warning, which you will see in small local setups with one or two instances.

The next TryIt runs a registry with a virtual clock so you can watch renewals, an eviction and a clean deregistration. What is real: the lease, renewal and expiry logic. What is simplified: no network, no peer replication and no self-preservation.

Java Leases, heartbeats and eviction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The gateway as a router (stand-in)

The second demo shows what a gateway does with the route table above: match the path against predicates, apply the StripPrefix filter, and forward to the service named in the route. A request that matches nothing gets a 404 from the gateway itself, and the gateway is also the natural place to add checks that apply to every request (an API key here, a JWT in real systems).

Java Route matching and a gateway filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Where to go from here

Splitting a system is as much about data as code: each service should own its data, with no shared tables, and consistency across services comes from events and patterns such as the outbox (Messaging and Events Between Services, Kafka in Practice). For a complete multi-service build, follow Project: Microservices.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of service discovery?

    A registry maps names to the currently running instances, which is essential when addresses change on every deployment or scale-out.
  2. 2. In @FeignClient(name = "catalog-service"), what resolves the name to an address?

    The Feign client asks Spring Cloud LoadBalancer, which uses the discovery registry to choose an instance.
  3. 3. Which statement about microservices is the most accurate?

    Splitting a system trades in-process simplicity for independence, and it is only worth it when you need that independence.
  4. 4. What does a route with uri lb://order-service and predicate Path=/api/orders/** do?

    The predicate decides which requests the route matches and lb:// tells the gateway to resolve the service name through discovery.
  5. 5. Why is a Spring Cloud version chosen from a compatibility table?

    Spring Cloud is built against particular Boot versions, so mixing them can fail in confusing ways.

Summary

  • Start with a monolith unless you need independent deployment; microservices trade simple calls for network calls and distributed data.
  • Spring Cloud adds Eureka discovery, OpenFeign and LoadBalancer for calls by name, Config Server for central settings, Gateway as the front door and Resilience4j for failure handling.
  • Pick the Spring Cloud release train that matches your Boot version and import its BOM.
  • On Kubernetes, much of this is already provided by the platform.
  • Always combine remote calls with timeouts and circuit breakers.

Next: Resilience, or continue to Performance Tuning.