Microservices with Spring
As systems and teams grow, a single application (a monolith) can be split into microservices: small services, each owning one business capability and its own data, deployed independently. Spring Boot and Spring Cloud are the most common way to build them in Java. This lesson covers how services call each other, how they stay resilient, and how you observe them.
Monolith or microservices?
| Modular monolith | Microservices | |
|---|---|---|
| Deploy | One application | Many, independently |
| Data | One database (separate schemas per module) | One database per service |
| Calls between parts | Method calls: fast, transactional | Network calls: slow, can fail |
| Teams | Coordinate releases | Each team owns and releases its services |
| Operations | Simple | Needs service discovery, tracing, central logging, CI/CD per service |
Microservices solve organisational scaling problems at a large operational cost. Most teams should start with a well-structured monolith with clear module boundaries (Spring Modulith helps enforce them), and extract services only when there's a concrete reason: independent scaling, separate teams, different release speeds.
Calling other services: RestClient
RestClient is Spring's modern, fluent HTTP client:
RestClient client = RestClient.builder().baseUrl("http://catalog-service").build();
ProductDto mug = client.get()
.uri("/api/products/{id}", 2)
.retrieve()
.body(ProductDto.class);
List<ProductDto> kitchen = client.get()
.uri("/api/products?category=kitchen")
.retrieve()
.body(new ParameterizedTypeReference<List<ProductDto>>() {});Running this against the shop API from earlier lessons:
ProductDto[id=2, name=Mug, price=8.99, inStock=true] 2
A 4xx or 5xx response throws an exception you can catch: HttpClientErrorException.NotFound for a 404 (its message starts with 404 Not Found), HttpServerErrorException for 5xx. In Spring Boot apps, inject the auto-configured RestClient.Builder so clients share Boot's settings (JSON mapping, observability).
Declarative clients: HTTP interfaces
Instead of building requests by hand, declare an interface and let Spring implement it:
@HttpExchange("/api/products")
interface CatalogClient {
@GetExchange("/{id}")
ProductDto get(@PathVariable Long id);
@GetExchange
List<ProductDto> byCategory(@RequestParam String category);
}
CatalogClient catalog = HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(client))
.build()
.createClient(CatalogClient.class);
System.out.println(catalog.get(1L).name() + " " + catalog.byCategory("kitchen").stream().map(ProductDto::name).toList());Laptop [Mug, Teapot]
Spring Framework 7 can also register such interfaces as beans for you with @ImportHttpServices, configured through properties.
Resilience
Networks fail, services slow down, deployments restart pods. A service that waits forever on a slow dependency soon has every thread stuck, and the failure cascades. Defences:
| Pattern | Meaning |
|---|---|
| Timeouts | Never wait forever: set connect and read timeouts on every client |
| Retry with backoff | Retry idempotent calls on temporary errors, waiting longer each time |
| Circuit breaker | After many failures, stop calling a broken service for a while and fail fast |
| Fallback | Return a cached or default answer when the dependency is down |
| Bulkhead | Limit concurrent calls so one slow dependency can't use every thread |
Spring Framework 7 includes @Retryable and @ConcurrencyLimit (enable them with @EnableResilientMethods); for circuit breakers, use Resilience4j via Spring Cloud Circuit Breaker:
@Retryable(includes = HttpServerErrorException.class, maxRetries = 3, delay = 200, multiplier = 2)
public ProductDto fetchProduct(Long id) {
return catalog.get(id);
}Asynchronous messaging
Not every interaction should be a synchronous call. When an order is placed, the shipping, email and analytics services don't need to answer immediately. The order service publishes an event to a message broker, and the others consume it when they can:
order-service ──"OrderPlaced"──▶ Kafka / RabbitMQ ──▶ shipping-service
├──▶ email-service
└──▶ analytics-serviceServices become loosely coupled (the order service doesn't know who listens) and keep working when a consumer is down. Spring has first-class support with Spring for Apache Kafka (KafkaTemplate, @KafkaListener) and Spring AMQP for RabbitMQ:
@Service
class OrderEvents {
private final KafkaTemplate<String, OrderPlaced> kafka;
OrderEvents(KafkaTemplate<String, OrderPlaced> kafka) { this.kafka = kafka; }
void published(Order order) {
kafka.send("orders", order.getId().toString(), new OrderPlaced(order.getId(), order.total()));
}
}
@Component
class ShippingListener {
@KafkaListener(topics = "orders", groupId = "shipping")
void on(OrderPlaced event) { … }
}Events must be handled idempotently (they can arrive twice), and to publish reliably together with a database change, use the transactional outbox pattern: write the event to an outbox table in the same transaction, and relay it to the broker afterwards.
Spring Cloud and the platform
| Need | Common choice |
|---|---|
| API gateway (routing, auth, rate limits at the edge) | Spring Cloud Gateway |
| Service discovery | Kubernetes services (or Eureka / Consul outside Kubernetes) |
| Central configuration | Kubernetes ConfigMaps and Secrets, or Spring Cloud Config |
| Distributed tracing | Micrometer Tracing + OpenTelemetry, viewed in Grafana Tempo, Jaeger or Zipkin |
| Metrics | Micrometer → Prometheus → Grafana |
| Contract testing | Spring Cloud Contract or Pact |
Observability is not optional
When one user request crosses five services, you can only debug it if every service logs the same trace ID. Spring Boot's Actuator and Micrometer propagate trace IDs automatically through RestClient, Kafka and more; add the OpenTelemetry exporter and every request becomes a trace you can inspect end to end.
Practice
- Write a
CatalogClientHTTP interface with asearch(String q)method, and use it from a second Spring Boot app on another port. - Configure a read timeout of 2 seconds on the
RestClient(viaClientHttpRequestFactorySettingsor theJdkClientHttpRequestFactory). - Draw the services and events for a food-delivery app: which calls should be synchronous, and which should be events?
1.What's usually the best starting architecture for a new product?
2.What does a circuit breaker do?
3.Why publish an "OrderPlaced" event instead of calling the email service directly?