Java NotesRohit’s interview study guide
Chapter 17

Microservices with Spring

The Spring side of a microservices architecture: what each Spring Cloud project is for, keeping one slow service from taking down the rest (timeouts, retries, circuit breakers), events with Kafka, keeping data consistent across services with the outbox pattern, and caching. Every example was run with Spring Boot 4.2.0 on Java 25; Kafka ran as an embedded broker inside the test.

Try it yourself. As in chapters 12 to 16: the starter project plus the files shown, extra starters added to pom.xml where an example says so. Runner-style examples use chapter 12's four-line application.properties and ./mvnw -q spring-boot:run; the Kafka example is a test, run with ./mvnw test. The design side of microservices (when to split, service boundaries, data ownership, consistency models) is covered in depth on the System Design site; this chapter is about doing it in Spring.

6 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#When microservices, and the Spring Cloud map

Added

A microservice architecture splits one application into small services that are deployed separately, each owning its data and talking to the others over the network. You get independent deploys, independent scaling and team autonomy. You pay with everything a network brings: calls that fail or hang, data that's no longer in one transaction, and much harder debugging. The honest interview answer is that most systems should start as a well-structured monolith (a "modular monolith", which Spring Modulith supports) and split off a service when there's a real reason: a team boundary, a part with very different scaling or reliability needs.

When you do split, the same problems appear in every system, and Spring Cloud is a set of projects that solve them for Spring Boot apps. The current release train is 2026.0.0 "Paddington" (November 2026), built for Boot 4.2:

ProblemSpring answerNotes in 2026
One entry point for clients: routing, auth, rate limitingSpring Cloud Gatewayruns on WebFlux or (Gateway MVC) on Spring MVC
Calling other servicesHTTP interface clients / RestClient (Spring Framework)Spring Cloud OpenFeign is feature-complete; its docs say to move to HTTP interface clients (chapter 13)
Finding servicesEureka (Spring Cloud Netflix), Consul, or Kubernetes DNSon Kubernetes, its own service discovery is usually enough
Central configurationSpring Cloud Config serveror Kubernetes ConfigMaps and Secrets
Slow or failing dependenciesSpring Cloud Circuit Breaker over Resilience4j; retries in Spring Framework 7 itselfHystrix is long gone
Events between servicesSpring for Apache Kafka, Spring Cloud StreamSpring Cloud Bus is now part of Stream
Following a request across servicesMicrometer Tracing / OpenTelemetry (chapter 16)

Names you'll still hear from older codebases and interview prep: Zuul (old gateway), Ribbon (old client-side load balancer) and Hystrix (old circuit breaker) were Netflix projects that Spring Cloud no longer ships; their replacements are Gateway, Spring Cloud LoadBalancer and Resilience4j.

#Timeouts, retries and circuit breakers

Added

In a monolith, a method call either returns or throws. Across a network, a call can also hang, and that's the dangerous case: every request waiting on a slow service holds a thread, a connection and memory, until your service runs out and fails too. A failure that spreads from one service to everything that calls it is a cascading failure, and three tools stop it:

  • Timeouts: never wait forever. Every client call gets a connect and read timeout (chapter 13).
  • Retries: try again on a transient failure (a dropped connection, a 503), with a growing delay between tries (exponential backoff) and some randomness (jitter) so a thousand clients don't retry in lockstep. Only retry operations that are safe to repeat (idempotent), or you'll charge a card twice.
  • Circuit breakers: when a dependency keeps failing, stop calling it for a while and fail fast (or return a fallback), giving it room to recover. Like the breaker in your house: after too many faults it trips (open), later lets a test call through (half-open), and closes again if that works.

Spring Framework 7 has retries built in: @Retryable on a bean method, switched on with @EnableResilientMethods. It works through a proxy, so the self-invocation rule from chapter 12 applies.

src/main/java/com/example/shop/Retries.java
package com.example.shop;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Configuration
@EnableResilientMethods
class ResilienceConfig {
}

class SupplierUnavailableException extends RuntimeException {
    SupplierUnavailableException(String message) {
        super(message);
    }
}

@Service
class SupplierClient {
    private final AtomicInteger calls = new AtomicInteger();

    @Retryable(includes = SupplierUnavailableException.class, maxRetries = 3, delay = 50, multiplier = 2)
    String stockFor(String sku) {
        int attempt = calls.incrementAndGet();
        System.out.println("attempt " + attempt + " for " + sku);
        if (attempt < 3) {
            throw new SupplierUnavailableException("503 from supplier");
        }
        return sku + ": 12 in stock";
    }

    @Retryable(includes = SupplierUnavailableException.class, maxRetries = 2, delay = 50)
    String alwaysDown(String sku) {
        System.out.println("trying " + sku);
        throw new SupplierUnavailableException("supplier is down");
    }
}

@Component
class RetryDemo implements CommandLineRunner {
    private final SupplierClient supplier;

    RetryDemo(SupplierClient supplier) {
        this.supplier = supplier;
    }

    @Override
    public void run(String... args) {
        System.out.println(supplier.stockFor("KB-1"));
        try {
            supplier.alwaysDown("MOUSE-22");
        } catch (SupplierUnavailableException e) {
            System.out.println("gave up: " + e.getMessage());
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
attempt 1 for KB-1
attempt 2 for KB-1
attempt 3 for KB-1
KB-1: 12 in stock
trying MOUSE-22
trying MOUSE-22
trying MOUSE-22
gave up: supplier is down
What’s happening
  1. @EnableResilientMethods turns on Spring Framework 7's resilience annotations. @Retryable on stockFor says: if it throws SupplierUnavailableException, retry up to 3 more times, waiting 50 ms, then 100 ms, then 200 ms (multiplier = 2).
  2. The fake supplier fails the first two calls. The output shows attempts 1 and 2 failing quietly (the proxy catches them and waits), attempt 3 succeeding, and the caller simply receiving KB-1: 12 in stock. The caller never knew it failed twice.
  3. alwaysDown fails every time. With maxRetries = 2 it's tried three times in total, then the last exception reaches the caller: gave up: supplier is down. Retries don't hide a real outage forever; they ride out blips.
  4. includes limits retries to the exception that means "try again later". Retrying a 400 Bad Request or a validation error is pointless: it'll fail the same way every time.
AdvancedA circuit breaker with Resilience4j

Resilience4j is the library behind Spring Cloud Circuit Breaker. Here it's used directly, which shows the state machine most clearly. A breaker watches the last N calls (a sliding window); when the failure rate passes a threshold it opens and rejects calls immediately; after a wait it goes half-open and lets a few trial calls through; success closes it again.

Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>io.github.resilience4j</groupId>
			<artifactId>resilience4j-circuitbreaker</artifactId>
			<version>2.4.0</version>
		</dependency>
src/main/java/com/example/shop/Breaker.java
package com.example.shop;

import java.time.Duration;
import java.util.List;

import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
class BreakerDemo implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        CircuitBreaker breaker = CircuitBreaker.of("supplier", CircuitBreakerConfig.custom()
                .slidingWindowSize(4)
                .minimumNumberOfCalls(4)
                .failureRateThreshold(50)
                .waitDurationInOpenState(Duration.ofMillis(300))
                .permittedNumberOfCallsInHalfOpenState(1)
                .build());

        List<Boolean> supplierWorks = List.of(false, true, false, false, true, true);
        for (int i = 0; i < supplierWorks.size(); i++) {
            if (i == 5) {
                Thread.sleep(400);
                System.out.println("... 400 ms later");
            }
            boolean works = supplierWorks.get(i);
            String result;
            try {
                result = breaker.executeSupplier(() -> {
                    if (!works) {
                        throw new IllegalStateException("supplier timed out");
                    }
                    return "stock: 12";
                });
            } catch (CallNotPermittedException e) {
                result = "rejected fast, fallback: stock unknown";
            } catch (IllegalStateException e) {
                result = "failed: " + e.getMessage();
            }
            System.out.println("call " + (i + 1) + " -> " + result + "   [breaker " + breaker.getState() + "]");
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
call 1 -> failed: supplier timed out   [breaker CLOSED]
call 2 -> stock: 12   [breaker CLOSED]
call 3 -> failed: supplier timed out   [breaker CLOSED]
call 4 -> failed: supplier timed out   [breaker OPEN]
call 5 -> rejected fast, fallback: stock unknown   [breaker OPEN]
... 400 ms later
call 6 -> stock: 12   [breaker CLOSED]
What’s happening
  1. The breaker judges the last 4 calls, needs at least 4 before deciding, and opens at a 50% failure rate. Once open it waits 300 ms, then allows 1 trial call.
  2. Calls 1 to 4 reach the supplier: fail, succeed, fail, fail. After the 4th call the window holds 3 failures out of 4, 75%, so the breaker goes OPEN.
  3. Call 5 would have worked, but the breaker doesn't even try: CallNotPermittedException is thrown immediately and the code uses a fallback. No thread waits on a supplier that's probably down; that's how a breaker stops a cascading failure.
  4. After 400 ms (longer than the 300 ms wait), call 6 is let through as a trial: the breaker is HALF_OPEN while it runs. It succeeds, so the breaker goes back to CLOSED and normal traffic resumes.
  5. In a Spring app you'd usually configure breakers in application.yml through Spring Cloud Circuit Breaker or Resilience4j's Spring Boot integration, and wrap the client call; the states and settings are the same.

#Messaging with Kafka

Added

Not every interaction should be a synchronous call. When an order is placed, shipping, email and analytics all need to know, but the customer shouldn't wait for them, and the order service shouldn't fail because the email service is down. The answer is events: the order service publishes "order placed" to a message broker, and each interested service consumes it in its own time.

Apache Kafka is the most common broker for this. Its model: topics are append-only logs split into partitions; producers append messages; consumer groups read them, each partition by one consumer of the group, tracking their position (offset). Messages stay in the log after they're read, so a new service can replay history. In Spring, KafkaTemplate sends and @KafkaListener receives; Boot configures both from spring.kafka.* properties. It's the Java counterpart of KafkaJS producers and consumers in Node.

The test below uses Spring Kafka's embedded broker: a real Kafka running inside the test JVM, so it needs no Docker and no installed Kafka.

Add these to pom.xml:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-kafka</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-kafka-test</artifactId>
			<scope>test</scope>
		</dependency>
src/main/java/com/example/shop/OrderEvents.java
package com.example.shop;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
class OrderPublisher {
    private final KafkaTemplate<String, String> kafka;

    OrderPublisher(KafkaTemplate<String, String> kafka) {
        this.kafka = kafka;
    }

    void orderPlaced(String orderId) {
        kafka.send("orders", orderId, "placed:" + orderId);
    }
}

@Component
class ShippingListener {
    final List<String> shipped = new CopyOnWriteArrayList<>();
    private final Set<String> seen = ConcurrentHashMap.newKeySet();

    @KafkaListener(topics = "orders", groupId = "shipping")
    void on(String event) {
        if (!seen.add(event)) {
            return; // already handled: Kafka delivers at least once, so duplicates must be harmless
        }
        shipped.add(event);
    }
}
src/test/java/com/example/shop/OrderEventsTest.java
package com.example.shop;

import java.time.Duration;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.test.context.EmbeddedKafka;

import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

@SpringBootTest(properties = {
        "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}",
        "spring.kafka.consumer.auto-offset-reset=earliest"})
@EmbeddedKafka(partitions = 1, topics = "orders")
class OrderEventsTest {

    @Autowired
    OrderPublisher publisher;

    @Autowired
    ShippingListener shipping;

    @Test
    void shippingHearsAboutEveryOrderOnce() {
        publisher.orderPlaced("ORD-1");
        publisher.orderPlaced("ORD-2");
        publisher.orderPlaced("ORD-1");

        await().atMost(Duration.ofSeconds(15)).untilAsserted(() ->
                assertThat(shipping.shipped).containsExactly("placed:ORD-1", "placed:ORD-2"));
    }
}
Terminal
$ ./mvnw test
[INFO] Results:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
What’s happening
  1. OrderPublisher sends to the orders topic with the order id as the key. Kafka puts all messages with the same key in the same partition, which keeps each order's events in order.
  2. ShippingListener consumes the topic in the consumer group shipping. Every service that cares (shipping, email, analytics) uses its own group, and each group gets every message.
  3. The test starts an embedded Kafka broker (@EmbeddedKafka), points Spring at it, publishes three events (ORD-1 twice) and waits up to 15 seconds for the listener, using Awaitility, because consumption is asynchronous.
  4. The listener records placed:ORD-1 and placed:ORD-2 only once each: the seen set drops the duplicate. That's an idempotent consumer, and it matters because Kafka's normal guarantee is at-least-once delivery: after a crash or rebalance, a consumer can see a message again.
  5. Maven's summary: Tests run: 2, Failures: 0 (this test plus the starter's own). In production the seen set would be a database table with a unique key, updated in the same transaction as the work.

#Data across services: sagas and the outbox pattern

Added

Inside one service, @Transactional makes "save the order and its lines" all-or-nothing. Across services there's no shared transaction: two-phase commit (XA) across databases and brokers is slow, fragile and mostly avoided. Two patterns replace it:

  • A saga splits a business transaction into local transactions, one per service, linked by events. If a later step fails, earlier steps are undone by compensating actions (refund the payment, release the stock). Sagas are either choreographed (each service reacts to events) or orchestrated (one coordinator tells each service what to do).
  • The transactional outbox solves the step every saga depends on: "update my database and publish an event" without a distributed transaction. You write the event into an outbox table in the same local transaction as the business change, and a separate publisher reads the outbox and sends to Kafka, marking rows as sent. Either both the order and its event are committed, or neither is.

The bug the outbox prevents is the dual write: saving the order, then calling kafka.send. If the app crashes between the two, the order exists but nobody hears about it; if you send first and the save fails, everyone hears about an order that doesn't exist.

src/main/java/com/example/shop/Outbox.java
package com.example.shop;

import java.util.List;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

import org.springframework.boot.CommandLineRunner;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Table(name = "orders")
class CustomerOrder {
    @Id
    @GeneratedValue
    Long id;
    String item;

    protected CustomerOrder() {
    }

    CustomerOrder(String item) {
        this.item = item;
    }
}

@Entity
class OutboxEvent {
    @Id
    @GeneratedValue
    Long id;
    String payload;
    boolean sent;

    protected OutboxEvent() {
    }

    OutboxEvent(String payload) {
        this.payload = payload;
    }
}

interface OrderRepository extends JpaRepository<CustomerOrder, Long> {
}

interface OutboxRepository extends JpaRepository<OutboxEvent, Long> {
    List<OutboxEvent> findBySentFalseOrderById();
}

@Service
class OrderService {
    private final OrderRepository orders;
    private final OutboxRepository outbox;

    OrderService(OrderRepository orders, OutboxRepository outbox) {
        this.orders = orders;
        this.outbox = outbox;
    }

    @Transactional
    void placeOrder(String item, boolean crashBeforeCommit) {
        CustomerOrder order = orders.save(new CustomerOrder(item));
        outbox.save(new OutboxEvent("OrderPlaced:" + order.id + ":" + item));
        if (crashBeforeCommit) {
            throw new IllegalStateException("crashed before commit");
        }
    }
}

@Service
class OutboxPublisher {
    private final OutboxRepository outbox;

    OutboxPublisher(OutboxRepository outbox) {
        this.outbox = outbox;
    }

    // In a real app: @Scheduled(fixedDelay = 1000), and kafka.send(...) instead of println.
    @Transactional
    int publishPending() {
        List<OutboxEvent> pending = outbox.findBySentFalseOrderById();
        for (OutboxEvent event : pending) {
            System.out.println("  published " + event.payload);
            event.sent = true;
        }
        return pending.size();
    }
}

@Component
class OutboxDemo implements CommandLineRunner {
    private final OrderService orders;
    private final OutboxPublisher publisher;
    private final OrderRepository orderRepo;
    private final OutboxRepository outboxRepo;

    OutboxDemo(OrderService orders, OutboxPublisher publisher, OrderRepository orderRepo, OutboxRepository outboxRepo) {
        this.orders = orders;
        this.publisher = publisher;
        this.orderRepo = orderRepo;
        this.outboxRepo = outboxRepo;
    }

    @Override
    public void run(String... args) {
        orders.placeOrder("Keyboard", false);
        try {
            orders.placeOrder("Mouse", true);
        } catch (IllegalStateException e) {
            System.out.println("Mouse order failed: " + e.getMessage());
        }
        System.out.println("orders: " + orderRepo.count() + ", outbox rows: " + outboxRepo.count());
        System.out.println("publisher run 1:");
        System.out.println("  sent " + publisher.publishPending());
        System.out.println("publisher run 2:");
        System.out.println("  sent " + publisher.publishPending());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
Mouse order failed: crashed before commit
orders: 1, outbox rows: 1
publisher run 1:
  published OrderPlaced:1:Keyboard
  sent 1
publisher run 2:
  sent 0
What’s happening
  1. placeOrder saves the order and an outbox row inside one @Transactional method, so both inserts commit together or not at all. (Entities and repositories are chapter 14's subject; here they're just two tables.)
  2. The Keyboard order commits: one order, one outbox row.
  3. The Mouse order "crashes" after both saves but before the commit. The transaction rolls back both rows, so there's no half-done state: orders: 1, outbox rows: 1. With a dual write, the crash could have left an order without an event or an event without an order.
  4. The publisher reads unsent rows, publishes them (printed here; kafka.send in real life) and marks them sent: run 1 publishes OrderPlaced:1:Keyboard, run 2 finds nothing new.
  5. If the publisher crashed after sending but before marking a row sent, the next run would send it again. So the outbox gives at-least-once delivery, and consumers must be idempotent, which is why the Kafka listener above drops duplicates. Tools like Debezium read the outbox from the database's change log instead of polling.

#Caching with Spring

Added

Some data is read far more often than it changes: product details, prices, configuration. Caching keeps recent results in memory so repeated reads skip the database or the remote call. Spring's cache abstraction does it with annotations: @Cacheable on a method returns the cached value for the same arguments instead of calling the method; @CacheEvict removes an entry when the data changes; @CachePut updates it. Like @Transactional, it works through a proxy (chapter 12), so self-invocation skips the cache.

By default the cache is an in-process ConcurrentHashMap. In a service with several instances you'd use a shared cache, usually Redis (add the Redis starter and Spring uses it automatically), or a bounded local cache like Caffeine with a time-to-live.

Add this to pom.xml:

pom.xml
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>
src/main/java/com/example/shop/Caching.java
package com.example.shop;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.boot.CommandLineRunner;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Configuration
@EnableCaching
class CacheConfig {
}

@Service
class PriceService {
    private final AtomicInteger databaseCalls = new AtomicInteger();
    private long keyboardPrice = 4999;

    int databaseCalls() {
        return databaseCalls.get();
    }

    @Cacheable("prices")
    long priceOf(String sku) {
        databaseCalls.incrementAndGet();
        return sku.equals("KB-1") ? keyboardPrice : 1950;
    }

    @CacheEvict(cacheNames = "prices", key = "#sku")
    void changePrice(String sku, long cents) {
        keyboardPrice = cents;
    }
}

@Component
class CacheDemo implements CommandLineRunner {
    private final PriceService prices;

    CacheDemo(PriceService prices) {
        this.prices = prices;
    }

    @Override
    public void run(String... args) {
        System.out.println("KB-1 = " + prices.priceOf("KB-1") + ", KB-1 = " + prices.priceOf("KB-1") + ", MS-2 = " + prices.priceOf("MS-2"));
        System.out.println("database calls so far: " + prices.databaseCalls());
        prices.changePrice("KB-1", 4499);
        System.out.println("after the price change, KB-1 = " + prices.priceOf("KB-1"));
        System.out.println("database calls so far: " + prices.databaseCalls());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
KB-1 = 4999, KB-1 = 4999, MS-2 = 1950
database calls so far: 2
after the price change, KB-1 = 4499
database calls so far: 3
What’s happening
  1. @EnableCaching switches the cache proxies on, and the cache starter gives a default in-memory cache manager.
  2. priceOf("KB-1") runs the method once (database call 1) and stores 4999 under the key KB-1 in the prices cache. The second priceOf("KB-1") is answered by the proxy from the cache: the method doesn't run. MS-2 is a different key, so it runs (call 2): database calls so far: 2.
  3. changePrice is @CacheEvict with key = "#sku" (a SpEL expression naming the parameter), so it removes the KB-1 entry.
  4. The next priceOf("KB-1") misses the cache, runs the method (call 3) and sees the new price, 4499. Without the eviction it would have kept serving 4999: stale data is the price of caching.
  5. Cache invalidation is famously hard: evict on every write path (including other services writing the same data, which an in-process cache can't see), and set a time-to-live as a safety net.
AdvancedGotcha: fields of a proxied bean are null
AdvancedGotcha: cache keys and mutable values

#Your turn: microservices

Added
Your turn: retry only what's worth retrying

A payment client should retry PaymentTimeoutException up to 2 times but never retry CardDeclinedException (retrying a declined card won't change the answer, and could look like fraud). Write the method and show both cases.

Show answer
src/main/java/com/example/shop/Payments.java
package com.example.shop;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Configuration
@EnableResilientMethods
class ResilienceConfig {
}

class PaymentTimeoutException extends RuntimeException {
}

class CardDeclinedException extends RuntimeException {
}

@Service
class PaymentClient {
    private final AtomicInteger attempts = new AtomicInteger();

    int attempts() {
        return attempts.get();
    }

    void resetAttempts() {
        attempts.set(0);
    }

    @Retryable(includes = PaymentTimeoutException.class, maxRetries = 2, delay = 20)
    String charge(String card) {
        attempts.incrementAndGet();
        if (card.equals("declined")) {
            throw new CardDeclinedException();
        }
        throw new PaymentTimeoutException();
    }
}

@Component
class PaymentDemo implements CommandLineRunner {
    private final PaymentClient client;

    PaymentDemo(PaymentClient client) {
        this.client = client;
    }

    @Override
    public void run(String... args) {
        for (String card : new String[] { "slow", "declined" }) {
            client.resetAttempts();
            try {
                client.charge(card);
            } catch (RuntimeException e) {
                System.out.println(card + ": " + e.getClass().getSimpleName() + " after " + client.attempts() + " attempt(s)");
            }
        }
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
slow: PaymentTimeoutException after 3 attempt(s)
declined: CardDeclinedException after 1 attempt(s)
What’s happening
  1. includes = PaymentTimeoutException.class makes only timeouts retryable; any other exception goes straight to the caller.
  2. The slow card times out every time: 1 call plus 2 retries, PaymentTimeoutException after 3 attempt(s).
  3. The declined card throws CardDeclinedException, which isn't included, so there's no retry: after 1 attempt(s).
  4. In real payment code, even retrying a timeout needs an idempotency key sent to the payment provider, because the first attempt may have succeeded on their side before the timeout.
Your turn: why did the order disappear?

A colleague replaced the outbox with this, and in production some orders are saved but shipping never hears about them. Explain why, and which pattern fixes it.

@Transactional void placeOrder(Order o) { orders.save(o); kafka.send("orders", o.id(), "placed"); }

Show answer

This is a dual write: two systems (the database and Kafka) updated by one method with no shared transaction.

What’s happening
  1. @Transactional covers the database only. kafka.send is asynchronous and isn't part of that transaction.
  2. If the send fails (broker down, app killed right after save), the database transaction can still commit: the order exists, no event was published, shipping never knows.
  3. The reverse also happens: the send succeeds, then the commit fails (a constraint, a deadlock), and shipping gets an event for an order that doesn't exist.
  4. The fix is the transactional outbox: write the event to an outbox table in the same transaction as the order, and let a separate publisher send it to Kafka (at least once, with idempotent consumers).

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.