▚ The Software Engineer's Field Manual
Chapter E22 · Primer + drill

Spring Boot in Depth — AOP, @Cacheable, @Async, @Retryable & the Topics E4 Skips

"Five annotations, one proxy. Learn the proxy once and @Cacheable, @Async, @Retryable, @PreAuthorize and @Transactional stop surprising you."

100 questions · answers collapsed Every output from a real Spring Boot 4.2 run Heavy on: Spring AOP · caching · async · retry & circuit breakers · scheduling · config & starters · Boot 4.x Companion to E4 — links, never repeats

01 · Why this chapter existsFive Annotations, One Proxy

Three bugs shipped in one QuickBite sprint: a cache that never cached, an email that still blocked checkout, and a payment that was retried into a double charge. They share one cause. Each of these annotations is extra code that Spring attaches to a proxy, and a proxy only sees the calls that arrive through it. This chapter teaches the proxy once, then every annotation built on top of it.

QuickBite is a food-delivery start-up. Its menu page shows 30 prices, and each price comes from a database query that takes about 180 ms. That is 30 × 180 ms = 5.4 seconds of database time for one page view. The team decides to cache.

A developer adds @Cacheable to MenuService.price(). A second developer adds @Async to NotificationService.send(), because the confirmation email takes 4 seconds and checkout waits for it. Both changes are one line each. Both pass code review. Both are in production by Friday.

On Monday the numbers have not moved. The menu page still takes 5.4 seconds, and checkout still waits 4 seconds for the email. The developers look at the annotations. They are there, spelled correctly, with the right imports. Nothing is wrong with them.

In the same sprint, a third developer wraps the payment call in @Retryable. The payment gateway returns a 503 error for about 2 % of calls, so a retry sounds sensible. The charge is not idempotent, which means calling it twice takes the money twice. Out of 1,000 charges, about 20 hit a 503. If the gateway took the money before it failed, the retry charges the customer again. Two customers notice in the first week.

Three bugs, and they look unrelated. They are not. Every one of these annotations works the same way: Spring puts a stand-in object in front of your bean, and the stand-in runs extra code around each call. If a call does not go through the stand-in, the extra code never runs. And the extra code runs in an order that you may not expect. This chapter teaches that one idea until you can predict all three bugs before they ship.

Incident one and two: the cache and the email that did nothing

We reproduce the first two in miniature, scaled down so the program finishes in seconds: a 100 ms query instead of 180 ms, and a 300 ms email instead of 4 seconds. Each service has the annotation and a method that calls it from inside the same class, which is what the two developers did.

The setup: MenuService counts how many times the "database" is hit. priceLabel() is a convenience method that formats the price, and it calls price() on the same object. A second class, OrderService, calls price() from outside, as another bean would.

MenuService.java · Boot 4.2runs offline
@Service
public class MenuService {
    private final AtomicInteger dbCalls = new AtomicInteger();

    @Cacheable("prices")
    public int price(String item) {
        dbCalls.incrementAndGet();
        sleep(100);                       // pretend: a 100 ms database query
        return 24900;
    }

    public String priceLabel(String item) {
        return "Rs " + price(item) / 100;  // calls price() on "this", not on the proxy
    }

    public int dbCalls() { return dbCalls.get(); }

    static void sleep(long ms) {
        try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
    }
}

The notification service has the same shape. send() is annotated with @Async, and it prints the name of the thread it runs on. confirm() calls send() from inside the class. OrderService.place() calls it from outside.

NotificationService.java · Boot 4.2runs offline
@Service
public class NotificationService {
    @Async
    public void send(String order) {
        System.out.println("   send(" + order + ") runs on thread " + Thread.currentThread().getName());
        MenuService.sleep(300);           // pretend: a 300 ms email gateway
    }

    public void confirm(String order) {
        send(order);                      // calls send() on "this", not on the proxy
    }
}
OrderService.java · Boot 4.2runs offline
@Service
public class OrderService {
    private final MenuService menu;
    private final NotificationService mail;

    OrderService(MenuService menu, NotificationService mail) {
        this.menu = menu;
        this.mail = mail;
    }

    public int priceOf(String item) { return menu.price(item); }       // goes through the proxy

    public void place(String order) { mail.send(order); }              // goes through the proxy
}

The last piece is the runner that calls everything and prints what happened. @EnableCaching and @EnableAsync sit on the configuration class: without them the annotations do nothing at all, a different bug that we meet in section 04.

Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan @EnableCaching @EnableAsync
public class Demo {
    @Bean CommandLineRunner run(MenuService menu, NotificationService mail, OrderService orders) {
        return args -> {
            System.out.println("== 1. @Cacheable: called from another bean vs from the same class");
            for (int i = 1; i <= 3; i++) {
                long t0 = System.nanoTime();
                String label = menu.priceLabel("biryani");
                System.out.printf("   same-class call #%d -> %s in %d ms, db calls so far: %d%n",
                        i, label, (System.nanoTime() - t0) / 1_000_000, menu.dbCalls());
            }
            for (int i = 1; i <= 3; i++) {
                long t0 = System.nanoTime();
                int cents = orders.priceOf("pizza");
                System.out.printf("   other-bean call #%d -> %d in %d ms, db calls so far: %d%n",
                        i, cents, (System.nanoTime() - t0) / 1_000_000, menu.dbCalls());
            }
            System.out.println("== 2. @Async: called from the same class vs from another bean");
            long t0 = System.nanoTime();
            mail.confirm("A-100");
            System.out.printf("   same-class call returned after %d ms%n", (System.nanoTime() - t0) / 1_000_000);
            t0 = System.nanoTime();
            orders.place("A-101");
            System.out.printf("   other-bean call returned after %d ms%n", (System.nanoTime() - t0) / 1_000_000);
            Thread.sleep(600);
        };
    }
}

Make the invisible visible: the output of --demo=selfinv. The first group calls the cached method from inside its own class three times, then from another bean three times. The second group does the same for the async method.

run --demo=selfinv · Boot 4.2runs offline
== 1. @Cacheable: called from another bean vs from the same class
   same-class call #1 -> Rs 249 in 101 ms, db calls so far: 1
   same-class call #2 -> Rs 249 in 100 ms, db calls so far: 2
   same-class call #3 -> Rs 249 in 100 ms, db calls so far: 3
   other-bean call #1 -> 24900 in 113 ms, db calls so far: 4
   other-bean call #2 -> 24900 in 0 ms, db calls so far: 4
   other-bean call #3 -> 24900 in 0 ms, db calls so far: 4
== 2. @Async: called from the same class vs from another bean
   send(A-100) runs on thread main
   same-class call returned after 300 ms
   send(A-101) runs on thread task-1
   other-bean call returned after 4 ms

What you see: called from inside its own class, price() hit the database every time: 3 calls, 3 queries, about 100 ms each. Called from another bean, the first call took 113 ms and the next two took 0 ms, with the query counter frozen at 4. For @Async, the same-class call ran on thread main and blocked the caller for 300 ms. The other-bean call ran on task-1 and returned after 4 ms.

Why: the annotation is not magic inside the method. It is a note that Spring reads at startup, and Spring acts on it by wrapping the bean in a proxy. When OrderService calls menu.price(), it holds the proxy, so the cache code runs first. When priceLabel() calls price(), it is already inside the real object. The call goes straight to the real method and skips the proxy.

The fix is the same in both cases: make the call go through the proxy. The simplest way is to move the method to another bean and call it from there. The duo below shows the smallest version of this change. Section 02 lists every way to do it and ranks them.

Broken

The cached method is called on this, so the cache is skipped.

MenuService.java · Boot 4.2runs offline
@Service
class MenuService {
  @Cacheable("prices")
  int price(String item) { ... }

  String priceLabel(String item) {
    return "Rs " + price(item) / 100;
  }
}

Fixed

The caller holds the proxy of another bean, so the cache runs.

OrderService.java · Boot 4.2runs offline
@Service
class OrderService {
  private final MenuService menu;

  String priceLabel(String item) {
    return "Rs " + menu.price(item) / 100;
  }
}

The shift: an annotation only works on calls that arrive from outside the bean, so move the call to another bean.

Bridge: a proxy, one level down

A proxy is an object that looks like your bean from the outside and stands in front of it. It has the same methods. When someone calls one, the proxy first runs some extra code, then passes the call on to your real object, which Spring calls the target. When the target returns, the proxy can run more extra code before the answer goes back to the caller.

Spring builds proxies at startup, right after it creates each bean. It asks one question for every bean: "does any extra code apply to a method of this bean?" The extra code comes from annotations such as @Cacheable and @Transactional, and from your own aspects. If the answer is no, you keep the plain object. If the answer is yes, Spring builds a proxy and puts that proxy in the container instead of the plain object.

By default Boot builds the proxy as a subclass of your class, using a library called CGLIB. You can see this in the output of any demo in this chapter: the bean's class prints as OrderService$$SpringCGLIB$$0. The alternative is a JDK proxy, which only works through an interface. Chapter E4 explains both in the container section. This chapter assumes CGLIB, because it is Boot's default.

The extra code is not one block. It is a list of small pieces, called an interceptor chain. The call passes through the pieces in order, goes into your method at the end, and the answer comes back through the same pieces in reverse. Figure 22.1 shows the chain for a method that carries three annotations and a custom aspect. The order in the figure is what we measured on Boot 4.2.0, and section 03 proves it.

another bean calls price() Proxy: MenuService$$SpringCGLIB$$0 1 · Retry (outermost) 2 · Cache 3 · Transaction 4 · Your own aspect Target: your real method The answer comes back up the chain @Retryable needs @EnableResilientMethods @Cacheable needs @EnableCaching @Transactional on by default in Boot @Aspect with @Around starter: spring-boot-starter-aspectj plain Java: it knows nothing about any of the layers above
Fig. 22.1 — One call, one proxy, one chain. The call from another bean enters the proxy and passes through four layers before it reaches your method. A call from inside the same class never enters the proxy at all. The layer order is the measured default on Boot 4.2.0 (section 03). @Async, when present, sits outside all four.

Read the figure from the top. The caller thinks it is calling MenuService. It is really calling the proxy, and the proxy hands the call to layer 1. Layer 1 is retry, which can call the rest of the chain again if it fails. Layer 2 is the cache, which can answer without ever calling the layers below it. Layer 3 opens a transaction. Layer 4 is any aspect you wrote. Only after all that does your method run.

Two things in this picture explain most of the bugs in this chapter. First, a call that does not enter at the top of the figure skips every layer. That is the self-invocation bug above. Second, the layers are in an order, and the order changes what each layer sees. A cache above a transaction never opens a transaction on a cache hit. A retry above a transaction gets a fresh transaction per attempt. Section 03 runs both.

The annotations this chapter covers

Every annotation in the table follows the pattern above: Spring finds it at startup, builds a proxy, and adds a layer. The middle column is the switch that turns the layer on. If the switch is off, the annotation is silently ignored, which is the first thing to check when "nothing happens".

The annotations E22 teaches, what turns each one on, and where to read about it
AnnotationEnabled bySection
@Aspect with @Around, @Before, @Afterspring-boot-starter-aspectj on the classpath (Boot turns on auto-proxying)02 · Spring AOP from zero
@Cacheable, @CachePut, @CacheEvict@EnableCaching04 · Caching
@Async@EnableAsync05 · Async
@Retryable, @ConcurrencyLimit (Spring Framework 7)@EnableResilientMethods06 · Retry and limits
@CircuitBreaker (Resilience4j)the Resilience4j Boot starter and its aspect support06 · Retry and limits
@Scheduled, @SchedulerLock (ShedLock)@EnableScheduling, and a lock provider for ShedLock07 · Scheduling
@TransactionalEventListener, @PreAuthorize, @Validated, @Observedtransaction support, @EnableMethodSecurity, validation auto-configuration, observation aspect07 · Scheduling and friends
@Transactionalauto-configured by Boot when a transaction manager existsE4 · Data

How this chapter relates to E4

E4 is the Spring Boot chapter. It teaches the container, the web layer, @Transactional, configuration, testing, security, observability and production behaviour. E22 starts where E4 stops. It teaches what E4 only touches inside a few drill answers (@Cacheable, @Async, @Retryable, custom aspects, ordering) and the topics E4 leaves thin: profiles, starters, logging, migrations, WebSocket and SSE, messaging, Spring Batch, and the changes in Boot 4.0 to 4.2.

E22 never repeats E4. When an idea is already there, you get a link. The proxy mechanism is in E4 · container, the @Transactional rules and its self-invocation trap are in E4 · data, configuration is in E4 · config, and production behaviour is in E4 · prod. Where an E4 drill question already answers something, such as E4 Q11 on proxies or Q114 on caching, the text names it.

How to read this chapter

The chapter has two halves. The first half is ten teaching sections, numbered 02 to 11. The second half is a 100-question drill with collapsed answers. Every number and every output block comes from a real run on Spring Boot 4.2.0, Spring Framework 7.1 and Java 25, on a 12-core machine. Timings will differ on yours; the shapes will not.

  1. Start with the incident: each section opens with a short QuickBite story that has real numbers. Read it first, so the definitions have something to attach to.
  2. Run the miniature: after the story you see a small program and its real output. The project is a Maven project under code/e22-spring-in-depth/. You can build it offline and run it with --demo=name.
  3. Read the "Bridge" parts: a bridge takes one mechanism and shows it one level down, so you can see the pieces move.
  4. Keep the idioms: thirty idioms are marked with an id such as pat-around-proceed-once. Each has a problem, a fix, a real before-and-after, and a one-line interview answer. The last section lists all thirty.
  5. Then drill: the 100 questions repeat the ideas from a new angle. Try to answer before you open an answer.

Sections 02 and 03 come first on purpose. Everything after them (cache, async, retry, schedule, security, validation, metrics) is an interceptor in the same chain. Once you can draw Figure 22.1 from memory, the rest of the chapter is detail.

02 · Spring AOP from zeroSpring AOP from Zero: Write the Extra Code Once

Aspect-oriented programming (AOP) means writing code that must run around many methods in one place, instead of pasting it into each method. Spring does this with proxies. This section builds the whole picture from zero: the words, the five kinds of advice, the pointcut language, a custom @Audited annotation, the two classic @Around bugs, the calls Spring can never intercept, and how two aspects are ordered. Every claim comes with a run.

QuickBite's product manager wants to know which service calls are slow. The request is simple: log how long every service method takes. A developer opens the nine service classes and pastes a timer into each method, 40 methods in total. It takes a day, and the logs look good.

Two weeks later a review finds three problems. In five methods the timer only runs on success, because the developer put the log line after the call instead of inside a finally block, so failed calls never appear in the logs. In two methods the log text was copied from a neighbour and names the wrong method. And a new service added last week has no timer at all, because nobody remembered.

A teammate deletes all 40 timers and writes one class of about a dozen lines. It covers every method of every service, including the ones added later. This is what AOP is for: a rule that cuts across many classes (a "cross-cutting concern"), written once and applied by pattern. The duo shows the same method before and after.

Hand-written

The timer is pasted into every method.

snippet · Boot 4.2runs offline
public int price(String item) {
  long t0 = System.nanoTime();
  try {
    return loadFromDb(item);
  } finally {
    log.info("price took {} ms",
      (System.nanoTime() - t0) / 1_000_000);
  }
}

One aspect

The method is plain. One class times all of them.

snippet · Boot 4.2runs offline
public int price(String item) {
  return loadFromDb(item);
}

@Aspect @Component
class TimingAspect {
  @Around("execution(* *..*Service.*(..))")
  Object time(ProceedingJoinPoint pjp)
      throws Throwable { /* below */ }
}

The shift: the rule moves out of 40 methods and into one class that selects them by pattern.

Now the real thing. Three services with two methods each, and one aspect that times all of them. The services contain no timing code. The only change to a service is that it exists in a package the aspect selects.

The setup: each service method sleeps for a fixed time (60, 5, 30, 12, 120 and 80 ms) to stand in for real work, so we know what the timer should report. The aspect's pointcut is execution(* com.quickbite.aop.timing.*Service.*(..)): any method of any class whose name ends in Service in that package.

TimingAspect.java · Boot 4.2runs offline
@Aspect
@Component
public class TimingAspect {
    @Around("execution(* com.quickbite.aop.timing.*Service.*(..))")
    Object time(ProceedingJoinPoint pjp) throws Throwable {
        long t0 = System.nanoTime();
        try {
            return pjp.proceed();
        } finally {
            System.out.printf("[timing] %s took %d ms%n",
                    pjp.getSignature().toShortString(), (System.nanoTime() - t0) / 1_000_000);
        }
    }
}
MenuService.java · Boot 4.2runs offline
@Service
public class MenuService {
    public int price(String item) { Svc.sleep(60); return 24900; }
    public java.util.List<String> items() { Svc.sleep(5); return java.util.List.of("biryani", "dosa"); }
}
PaymentService.java · Boot 4.2runs offline
@Service
public class PaymentService {
    public String charge(String id, int cents) { Svc.sleep(120); return "paid"; }
    public void refund(String id) { Svc.sleep(80); }
}

The runner calls the six methods once each. The two other services (OrderService with place and cancel) have the same shape, and the full project is in code/e22-spring-in-depth/A/aop-demo.

Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan
public class Demo {
    @Bean CommandLineRunner run(MenuService menu, OrderService orders, PaymentService pay) {
        return args -> {
            menu.price("biryani");
            menu.items();
            orders.place("A-100", 2);
            orders.cancel("A-100");
            pay.charge("A-100", 49800);
            pay.refund("A-100");
        };
    }
}

Make the invisible visible: six calls, six timing lines, and no timing code in any service.

run --demo=timing · Boot 4.2runs offline
[timing] MenuService.price(..) took 66 ms
[timing] MenuService.items() took 7 ms
[timing] OrderService.place(..) took 36 ms
[timing] OrderService.cancel(..) took 14 ms
[timing] PaymentService.charge(..) took 122 ms
[timing] PaymentService.refund(..) took 84 ms

What you see: each line reports the sleep time plus a few milliseconds. charge sleeps 120 ms and reports 122. refund sleeps 80 ms and reports 84. The first calls of each method cost a little extra, mostly because the JVM is still warming up. The aspect printed one line per call without any of the three services knowing it exists.

That is the whole promise of AOP. Everything else in this section explains how Spring keeps it, and where it breaks.

Bridge: the seven words of AOP, in plain words

AOP has a vocabulary that sounds harder than it is. Seven words cover almost everything. The table gives each one a plain meaning and points at the thing it names in the timing demo you just ran.

The AOP vocabulary, in plain words
WordPlain meaningIn the timing demo
Join pointA moment where extra code could be added. In Spring AOP it is always a method call on a Spring bean.Each of the six calls the runner makes.
PointcutA rule that picks which join points you care about.The execution(...) text inside @Around.
AdviceThe extra code, and when it runs: before, after, or around the method.The body of time().
AspectA class that bundles pointcuts and advice.TimingAspect.
AdvisorSpring's internal pair of one pointcut and one advice. The proxy stores a list of them.One advisor, created from time(). Section 03 prints them.
ProxyThe stand-in object that runs the advice around each call (see section 01).MenuService$$SpringCGLIB$$0.
WeavingConnecting aspects to the code they affect. Spring does it at runtime by building a proxy. AspectJ can do it earlier, by changing bytecode.Happened once at startup, when the proxy was built.

Figure 22.2 puts the words on one picture. On the left are the calls Spring can intercept, which are the join points. The pointcut is the filter. The three calls that match go into the advice. The rest run untouched, and nothing in their path changes.

Join points: calls Spring can intercept OrderService.place() OrderService.cancel() OrderService.status() MenuService.price() PaymentService.charge() PaymentService.refund() Aspect = pointcut + advice Pointcut: which calls? execution(* OrderService.*(..)) Advice: what to run? @Around: time the call not matched: run untouched Spring keeps each pointcut + advice pair as one "advisor". The proxy runs the advice around every matched call.
Fig. 22.2 — A pointcut selects join points; advice wraps the ones it selects. Solid frames are matched calls, dashed frames are calls the pointcut does not match. An aspect is the class that holds both halves.

Bridge: the five kinds of advice

Advice has a position: before the method, after it, or around it. Spring offers five kinds. Four of them are narrow tools and one is the general tool. The reason for having all five is to use the weakest one that does the job, because a weaker advice cannot break the call.

The experiment calls OrderService.place() twice. The first call succeeds. The second throws an IllegalStateException. One aspect has all five kinds of advice on that method, and each prints a numbered line, so you can read the order.

FiveAdvices.java · Boot 4.2runs offline
@Aspect
@Component
public class FiveAdvices {
    @Pointcut("execution(* com.quickbite.aop.advice.OrderService.place(..))")
    void place() {}

    @Around("place()")
    Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("  1 @Around     before proceed()");
        try {
            return pjp.proceed();
        } finally {
            System.out.println("  6 @Around     after proceed() (finally)");
        }
    }

    @Before("place()")
    void before(JoinPoint jp) {
        System.out.println("  2 @Before     args=" + Arrays.toString(jp.getArgs()));
    }

    @AfterReturning(pointcut = "place()", returning = "result")
    void afterReturning(Object result) {
        System.out.println("  4 @AfterReturning result=" + result);
    }

    @AfterThrowing(pointcut = "place()", throwing = "ex")
    void afterThrowing(Exception ex) {
        System.out.println("  4 @AfterThrowing  ex=" + ex.getMessage());
    }

    @After("place()")
    void after() {
        System.out.println("  5 @After      (always, like finally)");
    }
}
OrderService.java · Boot 4.2runs offline
@Service
public class OrderService {
    public String place(String id) {
        System.out.println("      >>> place() body runs");
        if (id.startsWith("bad")) throw new IllegalStateException("kitchen closed");
        return "placed " + id;
    }
}

Make the invisible visible: the same five pieces of advice, on a success and on a failure. Look for which line changes, and which lines stay.

run --demo=advice · Boot 4.2runs offline
--- call 1: place("A-100") succeeds
  1 @Around     before proceed()
  2 @Before     args=[A-100]
      >>> place() body runs
  4 @AfterReturning result=placed A-100
  5 @After      (always, like finally)
  6 @Around     after proceed() (finally)
caller got: placed A-100
--- call 2: place("bad-7") throws
  1 @Around     before proceed()
  2 @Before     args=[bad-7]
      >>> place() body runs
  4 @AfterThrowing  ex=kitchen closed
  5 @After      (always, like finally)
  6 @Around     after proceed() (finally)
caller got exception: kitchen closed

What you see: on the success, the order is @Around (before), @Before, the method, @AfterReturning, @After, @Around (after). On the failure, @AfterThrowing takes the place of @AfterReturning, and everything else stays. In both cases the caller got what the method produced: the string, or the exception.

Figure 22.3 draws the two timelines. The order within one aspect is a Spring rule, not an accident: in current Spring versions advice of the same aspect runs in the sequence shown here. If you ever depend on a subtler order, print it first, as this demo does.

The call succeeds 1@Around (in) 2@Before 3method returns 4@AfterReturning 5@After 6@Around (out) The call throws 1@Around (in) 2@Before 3method throws 4@AfterThrowing 5@After 6@Around (out)
Fig. 22.3 — The five advice types on one method, in the order the demo printed them. Top: the call returns. Bottom: the call throws, and @AfterThrowing replaces @AfterReturning. @Around encloses everything else.

The table says when to use each. The last column is the real rule: pick the first row that can do what you need, and only reach for @Around when you need to change the call itself.

The five advice types: what each can and cannot do
AdviceRunsCan it change the result?Use it for
@Beforebefore the methodNo. It can only stop the call by throwing.Checks and logging of arguments.
@AfterReturningafter a normal returnIt sees the result (returning = "r") but cannot replace it.Audit lines for successful calls, metrics for success.
@AfterThrowingafter an exceptionIt sees the exception (throwing = "ex") but cannot swallow it.Failure logs and alerts.
@Afteralways, like finallyNo. It sees neither result nor exception.Cleanup.
@Aroundaround the call, you decide whether and when the method runsYes. You can skip the call, call it twice, change arguments, or replace the result.Timing, caching, retries, transactions: anything that must control the call.

The power of @Around is also its danger, because the method runs only if your code asks it to. The next two subsections look at how a pointcut picks its calls, and then at the two ways an @Around advice goes wrong.

Bridge: pointcut expressions, one level down

A pointcut expression is a small text language. Spring borrowed it from AspectJ, and that is why the starter is called spring-boot-starter-aspectj even though Spring AOP uses proxies. The most common form is execution, which matches a method signature. Read it from left to right: a return type, a class and method name, then the parameters.

Take execution(* com.quickbite.aop.pointcuts.OrderService.*(..)). The first * means any return type. Then comes the full class name, a dot, and another * for any method name. The (..) means any number of parameters of any type. Two wildcards do most of the work: * stands for one name part, and .. stands for any number of package levels or parameters.

There are other designators. Some look at the method's name, some at its class, some at an annotation, some at the Spring bean name, and some at the arguments. You can combine any of them with &&, || and !. The best way to learn them is to run all of them on one set of methods and print which methods each matched.

The setup: three services, eight methods, two custom annotations. @Audited marks single methods. @Sensitive marks a whole class (PaymentService). A single aspect has seven @Before advices, each tagged with a letter, and each records the method names it matched.

Matches.java · Boot 4.2runs offline
@Aspect
@Component
public class Matches {
    final Map<String, List<String>> seen = new TreeMap<>();

    private void note(String pointcut, JoinPoint jp) {
        seen.computeIfAbsent(pointcut, k -> new ArrayList<>()).add(jp.getSignature().toShortString());
    }

    @Before("execution(* com.quickbite.aop.pointcuts.OrderService.*(..))")
    void a(JoinPoint jp) { note("A execution(* OrderService.*(..))", jp); }

    @Before("within(com.quickbite.aop.pointcuts.PaymentService)")
    void b(JoinPoint jp) { note("B within(PaymentService)", jp); }

    @Before("@annotation(com.quickbite.aop.pointcuts.Audited)")
    void c(JoinPoint jp) { note("C @annotation(Audited)", jp); }

    @Before("@within(com.quickbite.aop.pointcuts.Sensitive)")
    void d(JoinPoint jp) { note("D @within(Sensitive)", jp); }

    @Before("bean(menuService)")
    void e(JoinPoint jp) { note("E bean(menuService)", jp); }

    @Before("execution(* com.quickbite.aop.pointcuts.*.*(..)) && args(String, ..)")
    void f(JoinPoint jp) { note("F args(String, ..)", jp); }

    @Before("execution(* com.quickbite.aop.pointcuts.*Service.*(..)) && !execution(* *..*Service.s*(..))")
    void g(JoinPoint jp) { note("G ... && !execution(* s*(..))", jp); }
}

The three services are small. Only the annotations and the first parameter matter for this experiment.

OrderService.java · Boot 4.2runs offline
@Service
public class OrderService {
    @Audited public String place(String customer, int qty) { return "A-100"; }
    public void cancel(long orderId) {}
    public String status(String orderId) { return "COOKING"; }
}
PaymentService.java · Boot 4.2runs offline
@Service
@Sensitive
public class PaymentService {
    public String charge(String customer, int cents) { return "paid"; }
    public void refund(long orderId) {}
}
MenuService.java · Boot 4.2runs offline
@Service
public class MenuService {
    public int price(String item) { return 24900; }
    public List<String> items() { return List.of("biryani", "dosa"); }
    @Audited public void setPrice(String item, int cents) {}
}

The runner calls each of the eight methods once and prints, for each pointcut, the methods it matched. The map is a TreeMap, so the letters come out in order.

Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan
public class Demo {
    @Bean CommandLineRunner run(MenuService menu, OrderService orders, PaymentService pay, Matches matches) {
        return args -> {
            menu.price("biryani");
            menu.items();
            menu.setPrice("biryani", 25900);
            orders.place("asha", 2);
            orders.cancel(100L);
            orders.status("A-100");
            pay.charge("asha", 49800);
            pay.refund(100L);
            System.out.println("Methods called: price, items, setPrice, place, cancel, status, charge, refund");
            matches.seen.forEach((k, v) -> System.out.println(k + "\n      -> " + v));
        };
    }
}

Make the invisible visible: which of the eight calls does each pointcut catch?

run --demo=pointcuts · Boot 4.2runs offline
Methods called: price, items, setPrice, place, cancel, status, charge, refund
A execution(* OrderService.*(..))
      -> [OrderService.place(..), OrderService.cancel(..), OrderService.status(..)]
B within(PaymentService)
      -> [PaymentService.charge(..), PaymentService.refund(..)]
C @annotation(Audited)
      -> [MenuService.setPrice(..), OrderService.place(..)]
D @within(Sensitive)
      -> [PaymentService.charge(..), PaymentService.refund(..)]
E bean(menuService)
      -> [MenuService.price(..), MenuService.items(), MenuService.setPrice(..)]
F args(String, ..)
      -> [MenuService.price(..), MenuService.setPrice(..), OrderService.place(..),
        OrderService.status(..), PaymentService.charge(..)]
G ... && !execution(* s*(..))
      -> [MenuService.price(..), MenuService.items(), OrderService.place(..),
        OrderService.cancel(..), PaymentService.charge(..), PaymentService.refund(..)]

The table puts the seven letters in a form you can keep. The last column is read straight from the output above.

Pointcut designators, with what each matched in the demo
Letter and designatorIt matchesMatched in the demo
A · execution(* OrderService.*(..))Calls whose method signature fits the pattern: return type, class, name, parameters.place, cancel, status
B · within(PaymentService)Every method declared inside a class, or inside a package (within(com.quickbite..*)).charge, refund
C · @annotation(Audited)Methods that carry the annotation.setPrice, place
D · @within(Sensitive)Every method of a class that carries the annotation.charge, refund
E · bean(menuService)Every method of the Spring bean with that name. Spring-only; plain AspectJ has no beans.price, items, setPrice
F · args(String, ..)Calls whose first argument is a String at runtime. Also used to bind the argument into the advice.price, setPrice, place, status, charge
G · execution(...) && !execution(* s*(..))Combinations: && and, || or, ! not.Everything in the three services except the methods whose names start with s: setPrice and status are missing.

Compare C and D. Both use an annotation, but C selects methods and D selects classes. PaymentService has the annotation on the class, so D matched both of its methods, while C matched only the two methods that carry @Audited. Compare A and B as well. They match different things for different reasons: A matches a name pattern, B matches a place. They happen to select the same methods for different classes in this demo, which is a reason to read the output and not the expression.

Two practical points. First, keep advised methods public. Whether non-public methods are advised depends on the proxy type and the Spring version, and a pointcut that matches a method the proxy cannot intercept fails silently. Second, a pointcut that names packages and classes is fragile: it fails quietly when someone renames a package or creates a class that does not follow the naming convention. That leads to the first idiom.

Idiom: Select methods with an annotation, not with a name pattern

The problem: QuickBite's compliance team needs an audit line for every price change and every order cancellation. The first version used execution(* com.quickbite..*Service.*(..)). It audited every method of every service, including harmless reads, and it missed the new RefundHandler class, because its name does not end in Service. The pointcut selected by accident, and it was wrong in both directions.

How it works: define an annotation, put it only on the methods that need the behaviour, and write the pointcut as @annotation(audited). The name audited in the pointcut is also a parameter of the advice method, so Spring hands the aspect the annotation instance, with its attributes.

  1. Define the marker: @Retention(RUNTIME) is required. With a shorter retention the annotation is gone at run time and the pointcut matches nothing, with no error.
  2. Write the aspect once: @Around("@annotation(audited)"), with the annotation as a second parameter. It can read attributes such as action.
  3. Mark the methods: the intent is visible at the method, and reading the code shows exactly which methods are audited.
Audited.java · Boot 4.2runs offline
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface Audited {
    String action();
}
AuditAspect.java · Boot 4.2runs offline
@Aspect
@Component
public class AuditAspect {
    @Around("@annotation(audited)")
    Object audit(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
        String who = CurrentUser.get();
        String what = audited.action() + " " + Arrays.toString(pjp.getArgs());
        try {
            Object result = pjp.proceed();
            System.out.println("AUDIT user=" + who + " action=" + what + " outcome=OK");
            return result;
        } catch (Throwable t) {
            System.out.println("AUDIT user=" + who + " action=" + what + " outcome=FAILED " + t.getMessage());
            throw t;
        }
    }
}

The service marks two methods. A third method, list(), has no annotation. CurrentUser is a small thread-local holder that stands in for the logged-in user; in a real application you would read it from the security context. The runner sets the user, calls all three methods, and makes one cancellation fail on purpose.

MenuAdmin.java · Boot 4.2runs offline
@Service
public class MenuAdmin {
    @Audited(action = "price.change")
    public void changePrice(String item, int cents) {
        System.out.println("   (changing " + item + " to " + cents + ")");
    }

    @Audited(action = "order.cancel")
    public void cancel(String orderId) {
        if (orderId.startsWith("shipped")) throw new IllegalStateException("already shipped");
        System.out.println("   (cancelled " + orderId + ")");
    }

    public String list() { return "biryani, dosa"; }          // not annotated: never audited
}
Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan
public class Demo {
    @Bean CommandLineRunner run(MenuAdmin admin) {
        return args -> {
            CurrentUser.set("asha@quickbite.test");
            admin.list();
            admin.changePrice("biryani", 25900);
            admin.cancel("A-100");
            try { admin.cancel("shipped-7"); } catch (IllegalStateException e) { System.out.println("   caller saw: " + e.getMessage()); }
        };
    }
}

Make the invisible visible: audit lines for the annotated methods only, with the user, the action name from the annotation, the arguments, and the outcome.

run --demo=audited · Boot 4.2runs offline
   (changing biryani to 25900)
AUDIT user=asha@quickbite.test action=price.change [biryani, 25900] outcome=OK
   (cancelled A-100)
AUDIT user=asha@quickbite.test action=order.cancel [A-100] outcome=OK
AUDIT user=asha@quickbite.test action=order.cancel [shipped-7] outcome=FAILED already shipped
   caller saw: already shipped

Four calls, three audit lines. list() produced none, because it has no annotation. The failed cancellation produced a line marked FAILED, and the caller still received its exception, because the aspect rethrows it. That second point is the subject of the next idiom.

Idiom: In an @Around advice, call proceed() exactly once, return its result, and rethrow its exception

The problem: with @Around the method does not run unless your advice calls pjp.proceed(). The call is yours to make, and you also decide what comes back. Three small slips turn a logging aspect into a production incident: you drop the result, you swallow the exception, or you call the method twice.

How it works: proceed() runs the rest of the chain and then your method, and returns what the method returned. If the method throws, proceed() throws the same exception. Your advice sits between the caller and that result, so whatever it returns is what the caller gets.

  1. Call it once: a second call runs the method again, with all its side effects (a second charge, a second email).
  2. Return the result: return pjp.proceed();, or store it in a variable and return that. Dropping it returns null.
  3. Rethrow what you catch: catch to log or clean up, then throw t;. Use finally for work that must always run.

The experiment is a service with three methods. receipt() returns a string. total() returns a primitive int. charge() counts how many times it was really called, and always fails, like a gateway that is down. One aspect class exists in four versions, picked at start-up by a --bug= argument. The runner calls all three methods and prints what each caller saw.

OrderService.java · Boot 4.2runs offline
@Service
public class OrderService {
    private final AtomicInteger charges = new AtomicInteger();

    public String receipt(String id) { return "receipt-" + id; }

    public int total(String id) { return 49800; }

    public String charge(String id) {
        int n = charges.incrementAndGet();
        if (id.startsWith("A-")) throw new IllegalStateException("gateway down (charge attempt " + n + ")");
        return "charged";
    }

    public int charges() { return charges.get(); }
}

Here are the four versions of the aspect. Read each @Around method against the three steps above and find the line that breaks a step.

Aspects.java · Boot 4.2runs offline
public class Aspects {
    static final String ONLY_SERVICE = "execution(* com.quickbite.aop.around.OrderService.*(..)) && !execution(* *.charges())";

    @Aspect @Component @ConditionalOnProperty(name = "bug", havingValue = "forget")
    public static class ForgotReturn {
        @Around(ONLY_SERVICE)
        Object log(ProceedingJoinPoint pjp) throws Throwable {
            System.out.println("[aspect] calling " + pjp.getSignature().getName());
            pjp.proceed();                       // BUG: the result is thrown away
            return null;
        }
    }

    @Aspect @Component @ConditionalOnProperty(name = "bug", havingValue = "swallow")
    public static class Swallowed {
        @Around(ONLY_SERVICE)
        Object log(ProceedingJoinPoint pjp) throws Throwable {
            try {
                return pjp.proceed();
            } catch (Throwable t) {              // BUG: logged, then forgotten
                System.out.println("[aspect] saw " + t.getMessage());
                return null;
            }
        }
    }

    @Aspect @Component @ConditionalOnProperty(name = "bug", havingValue = "twice")
    public static class CalledTwice {
        @Around(ONLY_SERVICE)
        Object log(ProceedingJoinPoint pjp) throws Throwable {
            try {
                return pjp.proceed();
            } catch (IllegalStateException first) {
                System.out.println("[aspect] first try failed, trying again");
                return pjp.proceed();            // BUG: a hidden retry on a non-idempotent call
            }
        }
    }

    @Aspect @Component @ConditionalOnProperty(name = "bug", havingValue = "ok")
    public static class Correct {
        @Around(ONLY_SERVICE)
        Object log(ProceedingJoinPoint pjp) throws Throwable {
            try {
                Object result = pjp.proceed();   // once, and keep the result
                System.out.println("[aspect] " + pjp.getSignature().getName() + " returned " + result);
                return result;                   // hand it back
            } catch (Throwable t) {
                System.out.println("[aspect] " + pjp.getSignature().getName() + " failed: " + t.getMessage());
                throw t;                         // let the caller see the failure
            }
        }
    }
}

The duo condenses the two bugs of the first two versions against the fix.

Broken

The result is dropped, and the failure is swallowed.

snippet · Boot 4.2runs offline
Object log(ProceedingJoinPoint pjp)
    throws Throwable {
  try {
    pjp.proceed();
    return null;
  } catch (Throwable t) {
    log(t);
    return null;
  }
}

Fixed

Once, returned, and rethrown.

snippet · Boot 4.2runs offline
Object log(ProceedingJoinPoint pjp)
    throws Throwable {
  try {
    Object r = pjp.proceed();
    log(r);
    return r;
  } catch (Throwable t) {
    log(t);
    throw t;
  }
}

The shift: the advice sits between the caller and the method, so it must pass the result and the failure through untouched.

Make the invisible visible: first the version that forgets the result (--bug=forget). The long line is wrapped here.

run --demo=around --bug=forget · Boot 4.2runs offline
[aspect] calling receipt
receipt(A-100) -> null
[aspect] calling total
total(A-100)   threw AopInvocationException: Null return value from advice does not match
        primitive return type for: public int
        com.quickbite.aop.around.OrderService.total(java.lang.String)
[aspect] calling charge
charge(A-100)  threw java.lang.IllegalStateException: gateway down (charge attempt 1)
gateway was really charged 1 time(s)

The string method returned null. The primitive method did not return null, because it cannot; Spring raised an AopInvocationException with a message that names the cause. That exception is the lucky case, because it is loud. The method that returns an object gives a silent null that travels on until something dereferences it.

Make the invisible visible: now the version that catches and forgets (--bug=swallow).

run --demo=around --bug=swallow · Boot 4.2runs offline
receipt(A-100) -> receipt-A-100
total(A-100)   -> 49800
[aspect] saw gateway down (charge attempt 1)
charge(A-100)  -> null
gateway was really charged 1 time(s)

The gateway was down, yet the caller printed charge(A-100) -> null with no exception. To the code that called it, the charge looked like it had worked and returned nothing. The aspect printed its log line, so the failure is in the log, but nothing in the program's control flow knows. This is the bug that makes a payment look successful and ships the food for free.

Make the invisible visible: the version that calls proceed() twice (--bug=twice), a hidden retry.

run --demo=around --bug=twice · Boot 4.2runs offline
receipt(A-100) -> receipt-A-100
total(A-100)   -> 49800
[aspect] first try failed, trying again
charge(A-100)  threw java.lang.IllegalStateException: gateway down (charge attempt 2)
gateway was really charged 2 time(s)

The caller saw one failure, which looks reasonable. The last line shows the truth: the gateway was called twice. For a charge that fails after the gateway already took the money, the second call takes it again. Retry is a real technique, and it belongs in a tool built for it, with a limit and a delay and an idempotency key; section 06 builds that. A silent second proceed() is not that tool.

The fix: the correct version (--bug=ok). It calls once, returns the value, and rethrows.

run --demo=around --bug=ok · Boot 4.2runs offline
[aspect] receipt returned receipt-A-100
receipt(A-100) -> receipt-A-100
[aspect] total returned 49800
total(A-100)   -> 49800
[aspect] charge failed: gateway down (charge attempt 1)
charge(A-100)  threw java.lang.IllegalStateException: gateway down (charge attempt 1)
gateway was really charged 1 time(s)

Every caller sees exactly what the method produced: the string, the number, the exception. The aspect added log lines and changed nothing else. That is the rule for any advice that is not meant to change behaviour.

Bridge: what Spring AOP cannot intercept

Spring AOP works by standing in front of a bean. That one design choice explains its limits, because anything that does not pass through the stand-in is invisible to it. There are six common cases. We run each one and let the aspect report what it saw, so you do not have to trust the list.

The setup: OrderService.place() calls five things from its own body: another public method of itself (confirm), a private helper, a static method, a PaymentClient created with new, and an injected PaymentClient bean. One aspect, CallLog, prints a line for every call it can see on OrderService, PaymentClient and ConfirmationService. The service also has a final method that returns a field.

OrderService.java · Boot 4.2runs offline
@Service
public class OrderService {
    private final String shop = "QuickBite " + System.getProperty("city", "Central");  // set at runtime
    private final PaymentClient payments;
    private final ConfirmationService confirmations;

    OrderService(PaymentClient payments, ConfirmationService confirmations) {
        this.payments = payments;
        this.confirmations = confirmations;
    }

    public String place(String id) {
        System.out.println("   body of place(): this.confirm(...)");
        confirm(id);
        System.out.println("   body of place(): private helper(...)");
        helper(id);
        System.out.println("   body of place(): static tag(...)");
        tag(id);
        System.out.println("   body of place(): new PaymentClient().charge(...)");
        new PaymentClient().charge(id);
        System.out.println("   body of place(): injected payments.charge(...)");
        payments.charge(id);
        return "placed " + id;
    }

    public String confirm(String id) { return "confirmed " + id; }

    private String helper(String id) { return "helped " + id; }

    public static String tag(String id) { return "tag-" + id; }

    public final String shopName() { return shop; }

    public String placeViaOtherBean(String id) {
        System.out.println("   body: confirmations.confirm(...) on ANOTHER bean");
        return confirmations.confirm(id);
    }

    public String placeViaProxy(String id) {
        System.out.println("   body: AopContext.currentProxy().confirm(...)");
        return ((OrderService) AopContext.currentProxy()).confirm(id);
    }
}
CallLog.java · Boot 4.2runs offline
@Aspect
@Component
public class CallLog {
    @Around("execution(* com.quickbite.aop.cannot.OrderService.*(..))"
            + " || execution(* com.quickbite.aop.cannot.PaymentClient.*(..))"
            + " || execution(* com.quickbite.aop.cannot.ConfirmationService.*(..))")
    Object log(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("   [aspect] " + pjp.getSignature().toShortString());
        return pjp.proceed();
    }
}

The two other beans are one-liners. PaymentClient.charge() returns a string, and ConfirmationService.confirm() returns a string. The runner calls place() from outside, then the final method, then the two fixes that the next idiom explains.

Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan
@EnableAspectJAutoProxy(exposeProxy = true)
public class Demo {
    @Bean CommandLineRunner run(OrderService orders) {
        return args -> {
            System.out.println("bean class: " + orders.getClass().getSimpleName() + "  (proxy: " + AopUtils.isAopProxy(orders) + ")");
            System.out.println("-- 1. place(): what does the aspect see?");
            orders.place("A-100");
            System.out.println("-- 2. final method called on the proxy");
            System.out.println("   shopName() -> " + orders.shopName());
            System.out.println("-- 3. the fixes for self-invocation");
            orders.placeViaOtherBean("A-101");
            orders.placeViaProxy("A-102");
        };
    }
}

Make the invisible visible: every [aspect] line is a call that the proxy saw. A call with no [aspect] line was invisible to it.

run --demo=cannot · Boot 4.2runs offline
bean class: OrderService$$SpringCGLIB$$0  (proxy: true)
-- 1. place(): what does the aspect see?
   [aspect] OrderService.place(..)
   body of place(): this.confirm(...)
   body of place(): private helper(...)
   body of place(): static tag(...)
   body of place(): new PaymentClient().charge(...)
   body of place(): injected payments.charge(...)
   [aspect] PaymentClient.charge(..)
-- 2. final method called on the proxy
   shopName() -> null
-- 3. the fixes for self-invocation
   [aspect] OrderService.placeViaOtherBean(..)
   body: confirmations.confirm(...) on ANOTHER bean
   [aspect] ConfirmationService.confirm(..)
   [aspect] OrderService.placeViaProxy(..)
   body: AopContext.currentProxy().confirm(...)
   [aspect] OrderService.confirm(..)

What you see: the outside call to place() was seen. Inside its body, the call to confirm(), the private helper, the static method and the new PaymentClient() all produced no [aspect] line. Only the injected payments.charge() was seen, because the injected object is the proxy. The final method returned null although the field is set, and it also left no aspect line.

Why: confirm() was called on this, which is the real object, not the proxy. A private method is not part of what a subclass can override, so a proxy cannot stand in for it. A static method belongs to the class and not to the object, so there is no object to stand in front of.

An object made with new was never given to Spring, so Spring never wrapped it. A final method cannot be overridden either, which is why the proxy runs it on its own, empty instance. Spring creates the proxy without running your constructor, so shop is still null on that instance.

A final class is worse than a final method, because Spring cannot create a subclass at all. The experiment is a final service plus an aspect that matches it. The application does not start.

run --demo=finalcls · Boot 4.2 (trimmed to the two Caused by lines)runs offline
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass
        of class com.quickbite.aop.finalcls.Demo$BillingService: Common causes ... a final class
        or a non-visible class
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class
        com.quickbite.aop.finalcls.Demo$BillingService

Both messages say the same thing: the class is final, so the proxy cannot be built. Notice that this fails loudly, at startup, while a final method fails silently at run time. That difference makes final methods on advised beans the more dangerous case.

What Spring AOP cannot advise, why, and what to do
CaseWhy the proxy misses itWhat to do
Call to this.method() (self-invocation)The call stays inside the real object and never reaches the proxy.Move the method to another bean (next idiom).
Private methodA subclass cannot override it, so the proxy cannot stand in for it.Make it public on another bean, or accept that it is not advised.
Final methodCannot be overridden. The proxy runs it on its own empty instance and your field values are missing.Remove final from methods of advised beans.
Final classCannot be subclassed, so Spring cannot build the CGLIB proxy. Startup fails.Remove final, or give it an interface and set spring.aop.proxy-target-class=false to get a JDK proxy.
Static methodIt belongs to the class, so there is no object to wrap.Make it an instance method of a bean.
Object created with newSpring never saw it, so it never wrapped it.Let Spring create the object and inject it.

The first row is the one that matters most, because it is the one people write by accident. The same trap catches @Transactional; chapter E4 shows that version in the data section. Everything in the table applies to @Cacheable, @Async, @Retryable and every other annotation in this chapter, because they all sit on the same proxy.

Idiom: Fix self-invocation by calling through another bean

The problem: a method annotated with @Cacheable, @Async, @Retryable, @Transactional or your own annotation is called from another method in the same class. The proxy is skipped, so the advice never runs. It is silent: the code compiles, the tests that call the method from outside pass, and only production behaves differently.

How it works: the call must travel from a caller that holds the proxy. Another bean always holds the proxy of the bean it receives by injection. So the cleanest fix is to put the advised method in a different bean.

  1. Extract the method into its own bean (best): ConfirmationService in the demo. The caller injects it and calls it. This also tends to give the class a single clear job.
  2. Use AopContext.currentProxy() (last resort): ask Spring for the proxy of the current object and call through it. It needs @EnableAspectJAutoProxy(exposeProxy = true).
  3. Move to AspectJ weaving (heavy): weaving changes the bytecode of the method itself, so self-calls are advised. It brings its own costs, shown in the table below.

Make the invisible visible: the last part of the earlier output: the two fixes, and the aspect lines they produce.

run --demo=cannot · Boot 4.2 (the two fixes)runs offline
-- 3. the fixes for self-invocation
   [aspect] OrderService.placeViaOtherBean(..)
   body: confirmations.confirm(...) on ANOTHER bean
   [aspect] ConfirmationService.confirm(..)
   [aspect] OrderService.placeViaProxy(..)
   body: AopContext.currentProxy().confirm(...)
   [aspect] OrderService.confirm(..)

With the extracted bean, the aspect saw ConfirmationService.confirm() as a call of its own. With AopContext.currentProxy(), the aspect saw OrderService.confirm() inside placeViaProxy(), which it did not see in the self-invocation case. Both fixes work. The first one is the one to use.

Why is the second one a last resort? It makes business code depend on Spring AOP: the method now contains a cast and a call into Spring's own infrastructure, and it fails at run time with an exception if exposeProxy is not switched on. It is also easy to forget in a unit test where no proxy exists. If you reach for it, write a comment that says why, and know that you are working around a design that wanted to be two classes.

Bridge: Spring AOP or AspectJ?

Spring AOP is the proxy system you have just used. AspectJ is a separate, older tool that changes the bytecode of your classes instead. Spring borrows AspectJ's annotations (@Aspect, @Around) and its pointcut language, so the code you write looks the same.

What differs is how the advice reaches the method. In AspectJ the advice code is woven into the class file, either when you compile (compile-time weaving) or when the JVM loads the class (load-time weaving, using a Java agent). There is no proxy, so there is no "call must come from outside".

That is why AspectJ can advise things Spring AOP cannot: self-calls, private methods, static methods, constructors, field reads, and objects created with new. It is also why it costs more. You need a compiler plugin or a JVM flag, the build is slower, and a developer must know which of the two systems is running. Most Spring applications never need it. Both are in the table, with two cheaper options.

Spring AOP, AspectJ weaving, or no AOP at all
OptionPick it whenCost or catch
Spring AOP (proxies, the default)You advise calls between Spring beans: timing, auditing, security, caching, retry. This covers nearly every application.Misses self-invocation, private, static, final and new (table above). One proxy per advised bean.
AspectJ, compile-time weavingYou must advise self-calls, private methods, constructors or non-Spring objects, or you cannot afford a proxy hop on a hot path.A build plugin (the AspectJ compiler), slower builds, more complex IDE and debugging setup.
AspectJ, load-time weavingYou cannot recompile the classes (third-party code) but must change them.A -javaagent flag at every launch, extra start-up time, easy to get wrong in containers and tests.
No AOP: a plain decorator or an explicit callThere are one or two call sites, or the rule is business logic that readers should see.You must remember it at every call site. Fine for two places, painful for forty.

Spring's own annotations can use AspectJ as well. The enable annotations for transactions, caching and async have a mode attribute whose ASPECTJ value switches that feature from proxies to woven code, which then also covers self-invocation. It needs the spring-aspects library and weaving to be set up, so check the reference documentation for your version before you rely on it. The rest of this chapter stays with proxies, because that is what you get by default and what your team will meet.

Bridge: two aspects on one method, ordered with @Order

When two aspects match the same method, Spring needs a rule for which one goes first. By default there is no promise. If it matters, you set it with @Order(n) on the aspect class, or by implementing Ordered. The rule is: the lower the number, the higher the precedence, and the higher the precedence, the further out the aspect sits. The outermost aspect runs first on the way in and last on the way out. This is the "onion".

The setup: two aspects match MenuService.price(). Outer has @Order(1) and Inner has @Order(2). Each prints a line when it enters and when it exits. The runner first prints the advisor chain (section 03 explains that list), then calls the method.

Aspects.java · Boot 4.2runs offline
public class Aspects {
    @Aspect @Component @Order(2)
    public static class Inner {
        @Around("execution(* com.quickbite.aop.order.MenuService.*(..))")
        Object around(ProceedingJoinPoint pjp) throws Throwable {
            System.out.println("      enter Inner (@Order(2))");
            try { return pjp.proceed(); }
            finally { System.out.println("      exit  Inner (@Order(2))"); }
        }
    }

    @Aspect @Component @Order(1)
    public static class Outer {
        @Around("execution(* com.quickbite.aop.order.MenuService.*(..))")
        Object around(ProceedingJoinPoint pjp) throws Throwable {
            System.out.println("    enter Outer (@Order(1))");
            try { return pjp.proceed(); }
            finally { System.out.println("    exit  Outer (@Order(1))"); }
        }
    }
}
Chain.java · Boot 4.2runs offline
final class Chain {
    static void print(Object bean) {
        int i = 1;
        for (Advisor a : ((Advised) bean).getAdvisors()) {
            String order = a instanceof Ordered o ? String.valueOf(o.getOrder()) : "-";
            String text = a.toString();
            int at = text.indexOf("advice method [");
            String detail = at < 0 ? a.getAdvice().getClass().getSimpleName()
                    : text.substring(text.indexOf("com.quickbite", at), text.indexOf("(", at));
            System.out.printf("  %d. order=%-11s %s%n", i++, order, detail);
        }
    }
}

Make the invisible visible: the printed chain, then the order in which the two aspects and the method ran.

run --demo=order · Boot 4.2runs offline
  1. order=-2147483647 ExposeInvocationInterceptor
  2. order=1           com.quickbite.aop.order.Aspects$Outer.around
  3. order=2           com.quickbite.aop.order.Aspects$Inner.around
---
    enter Outer (@Order(1))
      enter Inner (@Order(2))
        price() runs
      exit  Inner (@Order(2))
    exit  Outer (@Order(1))
result: 24900

What you see: Outer entered first and exited last. Inner was closer to the method. The chain at the top lists the same order: Spring's own ExposeInvocationInterceptor first (it has the lowest number of all, so it is outermost), then Outer with order 1, then Inner with order 2.

The numbers are positions in a queue, not priorities in a fight. Think of what each aspect needs to see. A timing aspect that must include the cost of everything else should be outermost, so give it the lowest number. A security aspect that must reject a call before anything else happens should also be near the outside.

An aspect that works on the call's arguments or result, such as a cache key, should sit close to the method. If two aspects have the same order, or none, Spring does not promise which goes first, so do not depend on what you saw once. Set an explicit order on any aspect whose position matters.

Your own aspects are not the only things in the chain. Section 03 shows that @Transactional, @Cacheable, @Async and @Retryable are advisors in the same list. Their positions relative to your @Order number decide what a cache hit looks like in your metrics and whether a retry gets a fresh transaction.

When an annotation seems to do nothing: a five-question checklist

You now have enough to debug the most common Spring complaint, "I added the annotation and nothing happened". Ask five questions, in this order. Each question is cheap, and each one matches a demo from this section or section 01.

  1. Is the feature switched on? @Cacheable needs @EnableCaching, @Async needs @EnableAsync, @Retryable needs @EnableResilientMethods, and aspects need the AspectJ starter on the classpath. Without the switch the annotation is silently ignored.
  2. Is the bean a proxy? Print bean.getClass(). A name such as MenuService$$SpringCGLIB$$0 says yes. A plain name says no advisor matched, or the object was never a Spring bean (the new case).
  3. Does the call go through the proxy? Look at the caller. If it is the same class, you have self-invocation, so extract the method to another bean.
  4. Is the method advisable? It should be public, not final, not static, and in a class that is not final.
  5. What is the chain, and in what order? Print getAdvisors(). If the chain is right and the behaviour is still odd, the cause is order, which is the next section.
Symptom, likely cause, and where this chapter ran it
SymptomLikely causeSeen in
The cache never hits, the database is called every time.Self-invocation, or @EnableCaching missing.Section 01 (selfinv)
The async method blocks the caller, thread name is main.Self-invocation, or @EnableAsync missing.Section 01 (selfinv)
A method returns null only when an aspect is on.An @Around that does not return the result of proceed().Section 02 (around --bug=forget)
A failed call looks like a success.An @Around that catches and does not rethrow.Section 02 (around --bug=swallow)
A side effect happens twice.A second proceed(), or a retry on a method that is not safe to repeat.Section 02 (around --bug=twice)
A field is null in an advised bean.A final method run on the proxy's own empty instance.Section 02 (cannot)
The application fails at startup with "Cannot subclass final class".A final class that an aspect or annotation needs to proxy.Section 02 (finalcls)
A cache hit never appears in your metrics.Your aspect is inside the cache layer.Section 03 (stacked)
UnexpectedRollbackException after a retry that "worked".A retry loop inside a transaction.Section 03 (doomed)

The two rows from section 01 account for most of the real-world cases. If you can only remember two questions from this list, remember the first and the third: is it switched on, and does the call come from outside?

03 · The interceptor chainThe Interceptor Chain: When Several Annotations Meet One Method

Section 02 put one aspect on a method. Real methods carry several things at once: a retry, a transaction, a cache and a timer. Spring builds one proxy with one ordered list of advisors, and the order decides what each layer sees. In this section you print that list, run a method that carries all four, and watch how the order changes the result.

QuickBite has three services that read menu prices, written by three teams. All three put the same annotations on the price method: @Retryable, @Transactional and @Cacheable. They also use the same timing aspect. The three services behave differently.

In the first service, the timing dashboard shows only slow prices. The average is 300 ms, but customers see fast pages, because most prices come from the cache. The timing aspect is simply not running on cache hits, so the dashboard counts only the misses. In the second service, a developer gave the aspect @Order(Ordered.HIGHEST_PRECEDENCE). Cache hits show up there as 1 ms entries, and the dashboard is honest.

In the third service, a developer wrote a retry loop by hand inside a @Transactional method, because the database sometimes times out. After the first timeout, every further attempt fails too. The last line in the log is a message that mentions rollback-only, which the developer has never seen.

Same annotations, three behaviours. The difference is the order of the layers, and nobody had ever looked at it. We start with the stacked demo, which has all four layers, and then explain the pieces.

The setup: MenuService.price() carries @Retryable(maxRetries = 3, delay = 50), @Transactional and @Cacheable("prices"). The method fails on its first two attempts and succeeds on the third. On each attempt it prints the attempt number, whether a transaction is active, and (when the transaction ends) whether it committed or rolled back. A timing aspect wraps the method with an enter line and an exit line.

MenuService.java · Boot 4.2runs offline
@Service
public class MenuService {
    private final AtomicInteger attempts = new AtomicInteger();

    @Retryable(maxRetries = 3, delay = 50)
    @Transactional
    @Cacheable("prices")
    public int price(String item) {
        int n = attempts.incrementAndGet();
        boolean tx = TransactionSynchronizationManager.isActualTransactionActive();
        System.out.println("      price() attempt " + n + ", transaction active = " + tx);
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override public void afterCompletion(int status) {
                System.out.println("      attempt " + n + " transaction "
                        + (status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED BACK"));
            }
        });
        if (n < 3) throw new IllegalStateException("db timeout");
        return 24900;
    }

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

The timing aspect is the one from section 02, in a version that prints "enter" and "exit". Four copies exist, selected by a --knob= argument. This is the default one. The others differ only in @Order and are used a little later.

Aspects.java · Boot 4.2 (the default aspect)runs offline
public class Aspects {
    static Object time(ProceedingJoinPoint pjp) throws Throwable {
        long t0 = System.nanoTime();
        System.out.println("      [aspect] enter " + pjp.getSignature().getName());
        try {
            return pjp.proceed();
        } finally {
            System.out.printf("      [aspect] exit  %s after %d ms%n",
                    pjp.getSignature().getName(), (System.nanoTime() - t0) / 1_000_000);
        }
    }

    @Aspect @Component @ConditionalOnProperty(name = "knob", havingValue = "default", matchIfMissing = true)
    public static class Plain {
        @Around("execution(* com.quickbite.aop.stacked.MenuService.price(..))")
        Object around(ProceedingJoinPoint pjp) throws Throwable { return time(pjp); }
    }

    // three more copies follow: First, AfterCache, AfterTx
}

The configuration enables the three features, @EnableCaching, @EnableAsync (used later) and @EnableResilientMethods, which switches on Spring Framework 7's @Retryable. The runner prints the advisor chain, then makes two calls: a first call with a cold cache, and a second call.

Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan @EnableResilientMethods @EnableAsync
public class Demo {
    @Configuration @EnableCaching
    @ConditionalOnProperty(name = "knob", havingValue = "default", matchIfMissing = true)
    static class DefaultKnobs {}

    @Configuration @EnableCaching @EnableTransactionManagement
    @ConditionalOnProperty(name = "knob", havingValue = "aspectFirst")
    static class AspectFirstKnobs {}

    @Configuration @EnableCaching(order = Ordered.HIGHEST_PRECEDENCE + 10)
    @ConditionalOnProperty(name = "knob", havingValue = "cacheFirst")
    static class CacheFirstKnobs {}

    @Configuration @EnableCaching @EnableTransactionManagement(order = Ordered.HIGHEST_PRECEDENCE + 10)
    @ConditionalOnProperty(name = "knob", havingValue = "txFirst")
    static class TxFirstKnobs {}

    @Bean CommandLineRunner run(MenuService menu, NotificationService mail) {
        return args -> {
            System.out.println("advisor chain, outermost first:");
            Chain.print(menu);
            System.out.println("advisor chain of NotificationService (@Async @Transactional):");
            Chain.print(mail);
            System.out.println("== (a) first call: cache miss, fails twice, third attempt works");
            long t0 = System.nanoTime();
            System.out.println("   result " + menu.price("biryani") + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms");
            System.out.println("== (b) second call: cache hit");
            t0 = System.nanoTime();
            System.out.println("   result " + menu.price("biryani") + " after " + (System.nanoTime() - t0) / 1_000_000 + " ms");
            System.out.println("method body ran " + menu.attempts() + " times in total");
        };
    }
}

Make the invisible visible: the stacked method, with all four layers and the default settings. Ignore the first block for now: it is the advisor chain, and the next idiom explains it. Read the second half.

run --demo=stacked · Boot 4.2runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  4. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$Plain.around
advisor chain of NotificationService (@Async @Transactional):
  1. order=-2147483648 AsyncAnnotationAdvisor / AnnotationAsyncExecutionInterceptor
  2. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
== (a) first call: cache miss, fails twice, third attempt works
      [aspect] enter price
      price() attempt 1, transaction active = true
      [aspect] exit  price after 5 ms
      attempt 1 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 2, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 2 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 3, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 3 transaction COMMITTED
   result 24900 after 305 ms
== (b) second call: cache hit
   result 24900 after 2 ms
method body ran 3 times in total

What you see: the first call made three attempts. Each attempt printed an [aspect] enter line, a body line with transaction active = true, an [aspect] exit line, and then its own transaction ending: two rolled back and the third committed. The second call returned in 2 ms and printed nothing else: no aspect lines, no body, no transaction. The method body ran three times in total, all during the first call.

Why: the output tells you the order, if you read it as evidence. The aspect printed once per attempt, so the retry layer is outside the aspect. Each transaction ended after its aspect's exit line, so the transaction layer is outside the aspect too.

On the cache hit, the aspect printed nothing, so the cache is outside the aspect. And on the hit there is no transaction at all, so the cache is also outside the transaction. The 345 ms for the first call is two 50 ms pauses plus one-time costs such as the first database connection.

That is how the first service lost its cache hits: the aspect is inside the cache, so a hit never reaches it. The deduction above came from reading prints. It is better to ask Spring for the list directly, which is the next idiom. First we need to know where the list comes from.

Bridge: how annotations become advisors, one level down

Spring creates your beans one by one. After each bean is created, Spring passes it through a list of helper objects called bean post-processors. A post-processor can look at the bean and replace it with something else. This is the mechanism behind every proxy in this chapter, and chapter E4 describes it in the container section.

Different annotations use different post-processors. For your own aspects, Boot registers one auto-proxy creator. It reads every @Aspect class, turns each advice method into an advisor, and then checks every bean against every advisor's pointcut. For @Transactional and @Cacheable, an advisor is registered in the same way: a pointcut that means "a method with this annotation", and an interceptor that does the work. @Async and @Retryable come with their own post-processors, which add an advisor to a bean's proxy, or create a proxy when none exists yet.

The result is always the same shape: one proxy per bean, holding a list of advisors. When a bean already has a proxy, later features add their advisor to the same proxy instead of wrapping it again. This is why a method with four annotations does not become four nested objects. It is one proxy with an ordered list. When a call arrives, the proxy builds the chain of interceptors that apply to that method, runs them in order, and calls your method at the end.

How is the list ordered? Each advisor can have an order number. Spring sorts the list by that number: the lowest number goes first, which means outermost. Features that add themselves in front of the list (async and retry, as the output below shows) do not follow the numbers at all. Advisors with the same number keep the order in which they were registered. That last rule matters, and it is not a contract, as the next idiom shows.

Idiom: Print the advisor chain instead of guessing the order

The problem: three developers can argue for an hour about which runs first, the cache or the transaction, and each can quote a blog post. The blog posts are about different Spring versions. The answer is a fact about your application, and the proxy can tell you.

How it works: a Spring AOP proxy implements an interface called Advised. Cast the bean to it and call getAdvisors(). You get the list in the order the chain will run, outermost first.

  1. Get the bean: inject it, or look it up from the context. You need the proxy that Spring created, not a class you made with new.
  2. Cast and list: ((Advised) bean).getAdvisors(). Check AopUtils.isAopProxy(bean) first, since a bean that has no advisors is not a proxy and the cast fails.
  3. Print the order number and the advice: for an aspect, the advice method name tells you which of yours it is.
Chain.java · Boot 4.2runs offline
final class Chain {
    static void print(Object bean) {
        int i = 1;
        for (Advisor a : ((Advised) bean).getAdvisors()) {
            String order = a instanceof Ordered o ? String.valueOf(o.getOrder()) : "-";
            String text = a.toString();
            int at = text.indexOf("advice method [");
            String detail = at < 0
                    ? a.getClass().getSimpleName() + " / " + a.getAdvice().getClass().getSimpleName()
                    : text.substring(text.indexOf("com.quickbite", at), text.indexOf("(", at));
            System.out.printf("  %d. order=%-11s %s%n", i++, order, detail);
        }
    }
}

Make the invisible visible: the first lines of the stacked output: the chain of MenuService, then of a second service that carries @Async and @Transactional.

run --demo=stacked · Boot 4.2 (the two advisor chains)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  4. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$Plain.around
advisor chain of NotificationService (@Async @Transactional):
  1. order=-2147483648 AsyncAnnotationAdvisor / AnnotationAsyncExecutionInterceptor
  2. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor

Read the first chain from top to bottom. Retry is first, so it is the outermost layer. Next is Spring's own ExposeInvocationInterceptor, a piece of infrastructure that lets advice find the current call. Then the cache, the transaction, and last your aspect, Aspects$Plain.around. That matches the evidence from the prints.

The order numbers need careful reading. Integer extremes are used as markers: -2147483648 is HIGHEST_PRECEDENCE (outermost) and 2147483647 is LOWEST_PRECEDENCE (innermost). The cache, the transaction and the aspect all show 2147483647. They are tied, and the position of the three in this output is just the order in which they were registered.

It is stable for this Spring version, and it is not a promise. The retry advisor also reports 2147483647 but sits at the very top, because its post-processor puts it in front of the others. So the number alone does not tell the whole story, which is exactly why you print the list.

The second chain shows @Async first, with -2147483648, the highest precedence, outside the transaction. That detail explains why an @Async @Transactional method opens its transaction on the new thread. The last part of this section runs it.

Idiom: Retry outside the transaction, so every attempt gets a fresh one

The problem: the third QuickBite service retried a flaky database read with a loop inside its @Transactional method. A database transaction that has seen a failure may be doomed. Retrying inside it cannot rescue it, and the final commit throws an exception that nobody expected.

How it works: when a @Transactional method joins an existing transaction and then throws a runtime exception, its interceptor does not roll back the whole transaction on the spot. It marks the shared transaction rollback-only. From that moment the transaction can only roll back, whatever the outer code does. If the outer method catches the exception and carries on, the commit at the very end finds the mark and throws UnexpectedRollbackException.

  1. Put the retry outside: each attempt must start a new transaction and end it, win or lose, before the next one begins.
  2. Let Spring do the placing: in Spring Framework 7, @Retryable is always outermost, outside @Transactional and @Cacheable, whatever order values you set. The runs in this section agree: it was first in all four settings.
  3. Make the method safe to repeat: a retried call runs the whole method again, so it must be idempotent or protected by a key (section 06).

Make the invisible visible: first the broken shape, built by hand to isolate the effect: a @Transactional method that loops over a @Transactional call. The loader fails on its first two attempts. The retry loop catches the failure and tries again, inside the same outer transaction.

PriceService.java · Boot 4.2runs offline
@Service
public class PriceService {
    private final PriceLoader loader;

    PriceService(PriceLoader loader) { this.loader = loader; }

    // The retry loop is INSIDE the transaction, like Spring Retry with the wrong order.
    @Transactional
    public int priceWithRetryInside(String item) {
        for (int attempt = 1; attempt <= 3; attempt++) {
            try {
                return loader.load(item, attempt);
            } catch (IllegalStateException e) {
                boolean doomed = TransactionAspectSupport.currentTransactionStatus().isRollbackOnly();
                System.out.println("   caught \"" + e.getMessage() + "\"; outer transaction rollback-only = " + doomed);
            }
        }
        throw new IllegalStateException("gave up");
    }
}
PriceLoader.java · Boot 4.2runs offline
@Service
public class PriceLoader {
    @Transactional
    public int load(String item, int attempt) {
        System.out.println("   load(" + item + ") attempt " + attempt);
        if (attempt < 3) throw new IllegalStateException("db timeout");
        return 24900;
    }
}
run --demo=doomed · Boot 4.2runs offline
   load(biryani) attempt 1
   caught "db timeout"; outer transaction rollback-only = true
   load(biryani) attempt 2
   caught "db timeout"; outer transaction rollback-only = true
   load(biryani) attempt 3
caller got UnexpectedRollbackException:
   Transaction silently rolled back because it has been marked as rollback-only

What you see: after the first failure, the outer transaction was already rollback-only = true. The third attempt ran normally and returned, so the method looked successful, yet the caller received UnexpectedRollbackException. The loop did its job and the data was never saved. Two attempts and a successful third could not undo a mark set by the first.

This is a hand-written stand-in for "the retry sits inside the transaction". In the days of Spring Retry, the position of the retry interceptor relative to the transaction depended on order settings, and a wrong setting gave this same shape. Check Spring Retry's documentation for how it orders itself in your version.

Retry inside

One transaction for all attempts. It is doomed after the first failure.

snippet · Boot 4.2runs offline
@Transactional
public int price(String item) {
  for (int i = 1; i <= 3; i++) {
    try {
      return loader.load(item, i);
    } catch (IllegalStateException e) {
      // try again, same transaction
    }
  }
  throw new IllegalStateException();
}

Spring Framework 7

Retry is outside. Each attempt is a whole new call.

snippet · Boot 4.2runs offline
@Retryable(maxRetries = 3, delay = 50)
@Transactional
public int price(String item) {
  // one attempt = the whole method,
  // in a fresh transaction
  return load(item);
}

The shift: the retry moves outside the transaction, so a failed attempt ends its transaction before the next one starts.

The fix: here is the same set of attempts with @Retryable on the method, from the stacked demo. Look at the transaction lines: one per attempt, each ending before the next attempt begins.

run --demo=stacked · Boot 4.2 (the first call)runs offline
== (a) first call: cache miss, fails twice, third attempt works
      [aspect] enter price
      price() attempt 1, transaction active = true
      [aspect] exit  price after 5 ms
      attempt 1 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 2, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 2 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 3, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 3 transaction COMMITTED
   result 24900 after 305 ms

Attempts 1 and 2 each opened a transaction and rolled it back. Attempt 3 opened a new one and committed it. There was no rollback-only mark to inherit, because there was no shared transaction. The caller got 24900.

Bridge: the ordering knobs, measured

You can move some layers and not others. The table lists the order values we printed on Boot 4.2.0 with all defaults, and where each knob lives. Remember the reading rule: lower means more outer, and tied values are placed by registration order.

Default advisor order on Spring Boot 4.2.0 (printed by the demos), and the knob that changes it
LayerOrder value printedPosition measuredThe knob
@Async-2147483648 (highest)Outermost on its bean.@EnableAsync(order = ...)
@Retryable2147483647 (lowest)Outermost anyway: first in every run, placed in front by its post-processor.None you need: Spring Framework 7 keeps it outside @Transactional and @Cacheable.
Spring's ExposeInvocationInterceptor-2147483647Right after retry. Infrastructure; leave it.None.
@Cacheable and friends2147483647Third in the default run, ahead of the transaction.@EnableCaching(order = ...)
@Transactional2147483647Fourth in the default run, behind the cache.@EnableTransactionManagement(order = ...)
Your aspect without @Order2147483647Innermost in the default run.@Order(n) on the aspect class

Now we turn the knobs. The same stacked program runs four times. The runs differ only in one setting, chosen by --knob=. The first run is the default you have already seen. The second gives the aspect @Order(Ordered.HIGHEST_PRECEDENCE). The third gives the cache an explicit order of HIGHEST_PRECEDENCE + 10. The fourth gives the transaction the same explicit order.

Make the invisible visible: run two, --knob=aspectFirst, in full. Compare the second half with the default run: the aspect now appears on the cache hit.

run --demo=stacked --knob=aspectFirst · Boot 4.2runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483648 com.quickbite.aop.stacked.Aspects$First.around
  3. order=-2147483647  / ExposeInvocationInterceptor
  4. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  5. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
advisor chain of NotificationService (@Async @Transactional):
  1. order=-2147483648 AsyncAnnotationAdvisor / AnnotationAsyncExecutionInterceptor
  2. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
== (a) first call: cache miss, fails twice, third attempt works
      [aspect] enter price
      price() attempt 1, transaction active = true
      attempt 1 transaction ROLLED BACK
      [aspect] exit  price after 91 ms
      [aspect] enter price
      price() attempt 2, transaction active = true
      attempt 2 transaction ROLLED BACK
      [aspect] exit  price after 2 ms
      [aspect] enter price
      price() attempt 3, transaction active = true
      attempt 3 transaction COMMITTED
      [aspect] exit  price after 6 ms
   result 24900 after 224 ms
== (b) second call: cache hit
      [aspect] enter price
      [aspect] exit  price after 0 ms
   result 24900 after 1 ms
method body ran 3 times in total

The aspect moved to second place, ahead of the cache and the transaction. Two things followed. The cache hit now passes through the aspect: it printed enter and exit lines with 1 ms. This is how the second QuickBite service got honest numbers. And the aspect still printed once per attempt on the miss, three times, because the retry is outside it. Even HIGHEST_PRECEDENCE did not get an ordinary aspect in front of the retry.

That has a practical result. If you want one timing for the whole user call, including all retries, you cannot get it from an aspect on the retried method. Time it one level up, at the caller. The aspect on the method itself times each attempt.

Make the invisible visible: the chains for runs three and four. Only the chains are shown, because the behaviour on the miss is the same as in the default run.

run --demo=stacked --knob=cacheFirst · Boot 4.2 (chain)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=-2147483638 BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  4. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$AfterCache.around
run --demo=stacked --knob=txFirst · Boot 4.2 (chain)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=-2147483638 BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  4. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$AfterTx.around

With cacheFirst the cache shows -2147483638 and is still ahead of the transaction, as in the default run. The difference is that the position is now a number you wrote down, and not an accident of registration. With txFirst the transaction took the number and moved ahead of the cache: the order of those two layers swapped. The table puts the four runs side by side.

Four settings of the same stacked method (chain outermost first, from the printed output)
RunChain, outermost firstCache hit seen by your aspect?Per attempt on a miss
defaultretry, cache, transaction, aspectNo. The aspect is inside the cache.One aspect call and one transaction per attempt.
aspectFirstretry, aspect, cache, transactionYes: enter and exit lines on the hit, 1 ms.Same: still once per attempt, inside the retry.
cacheFirstretry, cache, transaction, aspectNo. The same as the default, now by an explicit number.Same.
txFirstretry, transaction, cache, aspectNo. The aspect is still innermost.Same. A hit is now inside the transaction layer (the chain shows it).

The lesson is in the second column. Order is a design choice with consequences, so make it on purpose. For a metrics aspect that must see every call, set an explicit low @Order. For anything where the relative order of the cache and the transaction matters, set both numbers in the same place, so a reader can see the intent.

Bridge: @Async and @Transactional on one method

The second chain in the idiom output showed @Async outside @Transactional. The consequence is simple. The proxy first hands the call to another thread. The transaction layer runs on that thread, so the transaction starts on the worker, and the caller's transaction is not shared with it. The experiment starts a transaction on the main thread, calls the async method from inside it, and prints the thread and the transaction state on both sides.

AuditService.java · Boot 4.2runs offline
@Service
public class AuditService {
    @Async
    @Transactional
    public void record(String order) {
        System.out.println("   record(" + order + ") on thread " + Thread.currentThread().getName()
                + ", transaction active = " + TransactionSynchronizationManager.isActualTransactionActive()
                + ", name = " + TransactionSynchronizationManager.getCurrentTransactionName());
    }
}
Demo.java · Boot 4.2runs offline
@Configuration @ComponentScan @EnableAsync
public class Demo {
    @Bean CommandLineRunner run(AuditService audit, PlatformTransactionManager tm) {
        return args -> {
            new TransactionTemplate(tm).executeWithoutResult(status -> {
                System.out.println("   caller on thread " + Thread.currentThread().getName()
                        + ", transaction active = " + TransactionSynchronizationManager.isActualTransactionActive());
                audit.record("A-100");
                System.out.println("   caller's own transaction is still open, and it does not own the audit work");
            });
            Thread.sleep(500);
        };
    }
}
run --demo=asynctx · Boot 4.2runs offline
   caller on thread main, transaction active = true
   caller's own transaction is still open, and it does not own the audit work
   record(A-100) on thread task-1, transaction active = true, name =
        com.quickbite.aop.asynctx.AuditService.record

What you see: the caller was on thread main with a transaction active. The audit method ran on task-1 and had its own transaction, named after the method. The caller's transaction was still open when the audit work ran. The two transactions are separate, and either can commit or roll back without the other.

Two practical results follow. If the caller's transaction rolls back after it queued the async work, the audit record still commits on its own. And data created in the caller's transaction may not be visible to the worker yet, because that transaction has not committed. Section 05 uses this to show what happens when you pass an entity into an async method (it fails on lazy loading), and the fix: pass ids, not entities.

The onion, drawn

Figure 22.4 puts the default order of this section into one picture. Each layer wraps the next. A call walks inward, passing each layer's "before" half. Your method sits in the middle. The result walks outward, passing each layer's "after" half. A layer can stop the walk early: the cache does it on a hit, and the retry can restart it from the top on a failure.

1 · Retry every attempt walks inward again 2 · Cache a cache hit answers here 3 · Transaction a fresh transaction per attempt 4 · Your aspect runs once per attempt 5 · Target your method runs here call in result out
Fig. 22.4 — The interceptor onion for a method with @Retryable, @Cacheable, @Transactional and a custom aspect, default order on Boot 4.2.0. The call goes in along the top arrow and the result comes out along the bottom one. Each ring may end the walk early: the cache on a hit, the retry by starting again.

Three habits keep you out of trouble with this picture. They are simple, and each comes from a run in this section.

  1. Print the chain once: in a test or at start-up, for any bean where order matters, and keep the result in a test so an upgrade cannot change it silently.
  2. Write the order down: an aspect whose position matters gets an explicit @Order. A cache and a transaction whose relative position matters get explicit orders too.
  3. Keep retries outside and methods repeatable: use @Retryable instead of loops inside transactions, and only on operations that are safe to run twice. Section 06 returns to this.

That finishes the proxy machinery. The next section, 04 · Caching, takes the cache layer from this onion and opens it up: how @Cacheable chooses keys, what sync = true does, and why ConcurrentMapCache can fill your memory. Section 05 does the same for @Async, and section 06 for @Retryable.

04 · CachingCaching with @Cacheable, the Right Way

A cache is a small, fast store that remembers answers you already worked out. @Cacheable puts that store in front of a method with one line, and the Spring cache abstraction hides which store it is. The one line is easy. The five things around it (the key, the expiry, the size limit, many callers at once, and many servers) are where real systems break. This section runs each one and prints the numbers.

Back to QuickBite. The menu page shows 30 prices, and every price comes from a database query. In production each query takes about 180 ms. One page view is therefore 30 × 180 ms = 5.4 seconds of database time, and the same 30 prices change maybe twice a day. We are asking the database the same question thousands of times and getting the same answer.

The fix sounds obvious: remember the answer. The risk is just as obvious: remember it wrongly, and customers see yesterday's price. We will build the cache in small steps and watch each step with a counter. To keep the demo fast and honest, the "database" is a class that sleeps 200 ms per call and counts its calls.

The setup: a fake price repository (200 ms per read, a call counter) and a MenuService with one cached method. The whole project is a Spring Boot 4.2 Maven project; the programs of this section live in one folder and are chosen with --demo=.

PriceRepository.java · Boot 4.2runs offline
@Component
public class PriceRepository {
    public final AtomicInteger calls = new AtomicInteger();
    public final Map<String, Integer> prices = new ConcurrentHashMap<>(
            Map.of("biryani", 24900, "dosa", 8900, "lassi", 5900));

    public Integer find(String item) {
        calls.incrementAndGet();
        sleep(200);                    // pretend: a 200 ms query
        return prices.get(item);       // null when the item does not exist
    }
}
MenuService.java · Boot 4.2runs offline
@Service
public class MenuService {
    private final PriceRepository repo;
    public MenuService(PriceRepository repo) { this.repo = repo; }

    @Cacheable("prices")                         // the one line
    public Integer price(String item) { return repo.find(item); }
}

One more line switches the feature on. @EnableCaching goes on the application class. Without it, @Cacheable is only a label that nobody reads, and every call goes to the database. This is the most common reason a first cache "does nothing".

Make the invisible visible: call price("biryani") three times and price("dosa") once. The program prints the time of each call and the repository's call counter.

run --demo=basic · Boot 4.2runs offline
cache manager: CaffeineCacheManager
price(biryani) 1st                 -> 24900     215 ms   db calls so far: 1 (MISS)
price(biryani) 2nd                 -> 24900       0 ms   db calls so far: 1 (hit)
price(biryani) 3rd                 -> 24900       0 ms   db calls so far: 1 (hit)
price(dosa)    1st                 -> 8900      200 ms   db calls so far: 2 (MISS)

What you see: the first call took 215 ms and raised the database counter to 1. The second and third calls took 0 to 2 ms and left the counter at 1. dosa is a different item, so it missed once (201 ms) and went to the database.

Why: the cache is organised by item. The first request for an item is a miss (nobody has asked yet), so the method really runs and its answer is stored. Every later request for the same item is a hit: the answer comes from memory and the method body does not run at all. The first line of the output also shows which store is in use, CaffeineCacheManager.

Check your own numbers against the table of costs: at 180 ms per query and 30 prices, the menu page drops from 5.4 s to about 0.2 s after the first view of each item. The database is asked 30 times a day instead of 30 times per page view.

To see what the annotation saves you, here is the same behaviour written by hand and with the annotation.

Hand-written

A map, a check, a store. Easy to get wrong.

snippet · Boot 4.2runs offline
private final Map<String, Integer> c =
    new ConcurrentHashMap<>();

public Integer price(String item) {
    Integer p = c.get(item);
    if (p == null) {
        p = repo.find(item);
        if (p != null) c.put(item, p);
    }
    return p;
}

With the annotation

The proxy does the same dance.

snippet · Boot 4.2runs offline
@Cacheable("prices")
public Integer price(String item) {
    return repo.find(item);
}

The shift: the caching steps move out of your method into the proxy, so the method says only what it computes, and the store (map, Caffeine, Redis) becomes a setting.

The hand-written version has no expiry, no size limit and no lock, and it never caches a null. Every one of those is a decision the annotation version lets you make in configuration instead of in code.

Bridge: how @Cacheable works, one level down

You already know from E4 (the container) that Spring wraps some beans in a proxy: a stand-in object that receives every call first and then forwards it. @Cacheable is built on exactly that. The proxy holds a cache interceptor, a small piece of code that runs before your method.

Four names appear in the machinery, and each has one job.

The four parts of the Spring cache abstraction
PartWhat it isPlain-words job
@EnableCachingAn annotation on a configuration classRegisters the cache interceptor so annotations are noticed.
CacheInterceptorCode inside the proxyBuilds the key, asks the cache, calls your method only on a miss, stores the answer.
CacheManagerAn interface (Caffeine, Redis, a plain map...)Hands out named caches. One manager, many caches.
CacheAn interface with get, put, evict, clearOne named store, such as prices. This is where the answers live.

The recipe the interceptor follows is called cache-aside (or "look-aside"): the application, not the cache, is in charge of loading. Figure 22.5 shows the path of one call.

One call to price("biryani"), step by step Caller OrderService Proxy of MenuService CacheInterceptor runs first: key = "biryani" 1 Cache "prices" (Caffeine) biryani = 24900 ? dosa = 8900 2 get HIT: the key is there 3a return 24900 now. Your method never runs. MISS: the key is not there 3b call the real method (the 200 ms query) 4 put the answer into the cache then return it to the caller The cache never loads anything by itself. The interceptor decides: look, load, store. That is why it is called cache-aside.
Fig. 22.5 — The path of one @Cacheable call. Steps 1 and 2 happen on every call. Step 3a ends the story on a hit. Steps 3b and 4 happen only on a miss, and they are the only ones that touch the database.

Three consequences follow from the picture, and each one explains a bug you will meet later.

Which store is "the cache"? Spring Boot picks the first provider it finds on the classpath (Caffeine, Redis, and so on) and falls back to a plain ConcurrentHashMap if there is none. The base project of this chapter sets spring.cache.type=caffeine explicitly, so the output above is honest about its store. We compare providers further down.

Bridge: @Cacheable, @CachePut, @CacheEvict, @Caching, @CacheConfig

Reading is half the story. Prices change, and the cache must hear about it. Spring gives you five annotations, and each answers a different question.

The five cache annotations
AnnotationDoes your method run?What it does to the cacheUse it when
@CacheableOnly on a missReads. On a miss, stores the result.A read method. The common case.
@CachePutAlwaysAlways writes the result under the key.A write method that returns the new value, so the next read is a hit.
@CacheEvictAlwaysRemoves one key, or every key with allEntries = true.A write or delete, when you would rather reload lazily.
@CachingAs its parts sayGroups several of the above on one method.One write touches two caches.
@CacheConfig(class level)Sets the default cache name, key generator or manager for a whole class.You are tired of repeating "prices".

We run the first three. @Caching and @CacheConfig are plain grouping and defaults, so we describe them and do not repeat their output.

Make the invisible visible: the write methods of MenuService. Each one changes the price in the fake database; the annotation decides what happens to the cache.

MenuService.java (write side) · Boot 4.2runs offline
@CachePut(value = "prices", key = "#item")
public Integer setPrice(String item, int cents) {
    repo.update(item, cents);
    return cents;                       // this return value is stored
}

@CacheEvict(value = "prices", key = "#item")
public void changePrice(String item, int cents) {
    repo.update(item, cents);           // the entry is removed after this returns
}

@CacheEvict(value = "prices", key = "#item")
public void changePriceThenFail(String item, int cents) {
    throw new IllegalStateException("commit failed");   // the write rolled back
}

@CacheEvict(value = "prices", key = "#item", beforeInvocation = true)
public void changePriceFailsBeforeEvict(String item, int cents) {
    throw new IllegalStateException("db down");
}

@CacheEvict(value = "prices", allEntries = true)
public void clearPrices() { }

The runner calls them in a fixed order and prints what the next read costs. Read the output line by line against the comments in the code.

run --demo=evict · Boot 4.2runs offline
price(biryani)                     -> 24900     224 ms   db calls so far: 1 (MISS)
price(biryani)                     -> 24900       6 ms   db calls so far: 1 (hit)
-- changePrice(biryani, 26900) with @CacheEvict
price(biryani) after evict         -> 26900     200 ms   db calls so far: 2 (MISS)
-- setPrice(biryani, 27900) with @CachePut
price(biryani) after put           -> 27900       0 ms   db calls so far: 2 (hit)
-- changePriceThenFail: the method throws, so the evict is skipped
   threw commit failed
price(biryani) still cached        -> 27900       0 ms   db calls so far: 2 (hit)
-- changePriceFailsBeforeEvict: beforeInvocation=true evicts first
   threw db down
price(biryani) after early evict   -> 27900     201 ms   db calls so far: 3 (MISS)
-- clearPrices() with allEntries=true
price(biryani)                     -> 27900     202 ms   db calls so far: 5 (MISS)
price(dosa)                        -> 8900      202 ms   db calls so far: 6 (MISS)

What you see: after changePrice the next read costs 200 ms and returns the new price, 26900. After setPrice the next read costs 0 ms, because the put stored 27900 directly. When the method throws, a normal @CacheEvict does nothing, so the old entry stays. With beforeInvocation = true the entry is removed even though the method threw. Finally allEntries = true emptied everything, so both biryani and dosa missed.

Why: by default Spring evicts after your method returns normally. That is what you want when the method writes to a database: if the write fails and rolls back, the old cached value is still true. Use beforeInvocation = true only when you would rather lose a cached value than risk serving it, for example when a failure leaves the database state unknown.

One trap hides in "evict after the method returns". If your service method is @Transactional, the method returns before the transaction commits. A reader on another thread can miss, load the old price from the database, and put it back, all in the gap between your eviction and your commit. For prices that is a few seconds of staleness. For stock counts, it is worth thinking about. The safe pattern evicts after commit, which is the subject of @TransactionalEventListener in the scheduling and events section.

Idiom: evict (or put) on every write path

The problem: you cached price() and forgot that three other methods change prices: an admin screen, a CSV import and a nightly job. Each write leaves the cache stale until the entry expires. The stale price is not an error, so nothing alerts you; a customer simply sees 249 and is charged 269.

How it works: every method that changes data also tells the cache. @CacheEvict removes the entry so the next read reloads it. @CachePut replaces the entry in the same call. Both name the same cache and the same key as the read method.

  1. List the write paths: search for every place that updates the table behind the cached read. Admin, import, batch job, another service, a database script.
  2. Choose evict or put: evict is safer (the next read always loads the truth); put saves one query but needs the write method to return exactly what the read would return.
  3. Use the same key: key = "#item" on the write must produce the same key as the default key on the read, or the evict removes nothing.
  4. Keep a time limit as a safety net: an expiry (next section) bounds the damage of a write path you forgot.

Bridge: cache keys, the part everyone skips

A cache key is the label under which an answer is stored. When you call price("biryani") the key is the word biryani. The cache is a map, so the key must be comparable: Spring looks the key up with equals and hashCode, like any HashMap key.

If you write no key, Spring builds one from the method's parameters with a simple rule.

The default key (the built-in SimpleKeyGenerator)
Method parametersKeyExample
NoneAn empty marker, SimpleKey.EMPTYmenuOfTheDay()
Exactly oneThat parameter itselfprice("biryani") has key biryani
Two or moreA SimpleKey holding all of themprice("biryani", "Mysuru")

This default is right surprisingly often. It fails in three ways: the parameters are objects with no equals, the parameters include things that should not be part of the key (a timestamp, a request object), or two different methods write into the same cache with overlapping keys. The cure for all three is the same: say the key yourself, in the annotation.

The key attribute takes a SpEL expression (Spring Expression Language, a tiny language for reading values). Inside it, #item means "the parameter called item", and #result means the return value. Your parameter names must be known at runtime, which the Spring Boot parent pom arranges by compiling with the -parameters flag.

Make the invisible visible: three calls that look identical, once with the default key on an object, once with an explicit key. The program also prints what the native Caffeine map holds afterwards.

MenuService.java (keys) · Boot 4.2runs offline
// a mutable class WITHOUT equals/hashCode
public class PriceQuery {
    private String item, city;
    public PriceQuery(String item, String city) { ... }
    public String getItem() { return item; }
    public String getCity() { return city; }
}

@Cacheable(value = "cityPrices", key = "#item + ':' + #city")
public Integer price(String item, String city) { ... }

@Cacheable("byQuery")                                    // default key = the object
public Integer priceBy(PriceQuery q) { ... }

@Cacheable(value = "byQueryFixed", key = "#q.item + ':' + #q.city")
public Integer priceByFixed(PriceQuery q) { ... }
run --demo=keys · Boot 4.2runs offline
== SpEL key: item + ':' + city
   cache 'cityPrices' holds 2 entries: [biryani:Mysuru, biryani:Hubli]
== entity as key, no equals/hashCode: three equal-looking queries
priceBy(new PriceQuery(biryani,Mysuru)) -> 24900     203 ms   db calls so far: 3 (MISS)
priceBy(new PriceQuery(biryani,Mysuru)) -> 24900     201 ms   db calls so far: 4 (MISS)
priceBy(new PriceQuery(biryani,Mysuru)) -> 24900     202 ms   db calls so far: 5 (MISS)
   cache 'byQuery' holds 3 entries: [PriceQuery[biryani,Mysuru], PriceQuery[biryani,Mysuru], PriceQuery[biryani,Mysuru]]
== same queries, explicit key = #q.item + ':' + #q.city
priceByFixed(new PriceQuery(...))  -> 24900     217 ms   db calls so far: 6 (MISS)
priceByFixed(new PriceQuery(...))  -> 24900       0 ms   db calls so far: 6 (hit)
priceByFixed(new PriceQuery(...))  -> 24900       0 ms   db calls so far: 6 (hit)
   cache 'byQueryFixed' holds 1 entries: [biryani:Mysuru]

What you see: the SpEL key #item + ':' + #city produced two readable keys, biryani:Mysuru and biryani:Hubli. The object key never hit: all three calls missed (3 database calls, 200 ms each) and the cache now holds three entries that look identical. With the explicit key, one miss and two hits, and one entry.

Why: a class without equals and hashCode compares by identity, so every new PriceQuery(...) is a different key. The cache is not broken; it is storing exactly what you asked. Worse, those three entries are now garbage that nobody can ever hit, and the cache grows by one on every call. The same thing happens with a mutable object that is changed after it was used as a key.

Idiom: write the key explicitly

The problem: the default key is built from objects you may not control. A PriceQuery without equals never hits, a JPA entity compares by id only after it is saved, and a request DTO may carry a field (a trace id, a timestamp) that makes every key unique.

How it works: key = "..." in the annotation picks exactly the values that identify the answer and builds a string or a small value type from them. For logic that SpEL cannot express nicely, you can write a class that implements KeyGenerator and name it with keyGenerator = "myKeys".

  1. Ask: which inputs decide the answer? Item and city decide the price. The caller's session id does not.
  2. Write the key from those inputs only: key = "#item + ':' + #city". Use a separator so ("ab","c") and ("a","bc") cannot collide.
  3. Use value types for objects: a record has equals and hashCode built in, so a record parameter is a good key as it is.
  4. Keep keys small and stable: never put a large object or a list into a key. With Redis the key is sent over the network on every call.
illustrative · a custom KeyGenerator (not run)illustrative
// illustrative: one key rule for a whole service
@Component("menuKeys")
class MenuKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object... params) {
        return method.getName() + ":" + Arrays.stream(params).map(String::valueOf)
                .collect(Collectors.joining(":"));
    }
}
// use it: @Cacheable(value = "prices", keyGenerator = "menuKeys")

Bridge: condition, unless, nulls and Optional

Sometimes a result should not be cached. The abstraction has two switches that look alike and act at different moments.

condition versus unless
AttributeCheckedCan it see #result?If it blocks
conditionBefore the method runsNoThe cache is skipped completely: no lookup, no store. The method always runs.
unlessAfter the method returnsYesThe lookup still happened; only the store is skipped.

Rule of thumb: use condition for decisions about the input ("only cache names longer than 4 letters"), and unless for decisions about the answer ("do not store null"). The next program tries both, plus a null result and an Optional.

MenuService.java (condition and unless) · Boot 4.2runs offline
@Cacheable(value = "unlessNull", unless = "#result == null")
public Integer priceUnlessNull(String item) { return repo.find(item); }

@Cacheable("nullsCached")                                    // no unless: null is stored
public Integer priceNullsCached(String item) { return repo.find(item); }

@Cacheable(value = "cond", condition = "#item.length() > 4")
public Integer priceCond(String item) { return repo.find(item); }

@Cacheable("opt")
public Optional<Integer> optPrice(String item) {
    return Optional.ofNullable(repo.find(item));
}
run --demo=condition · Boot 4.2runs offline
== unless="#result == null" on a missing item
priceUnlessNull(ghost) 1st         -> null      270 ms   db calls so far: 1 (MISS)
priceUnlessNull(ghost) 2nd         -> null      202 ms   db calls so far: 2 (MISS)
== no unless: the null is cached too
priceNullsCached(ghost) 1st        -> null      202 ms   db calls so far: 3 (MISS)
priceNullsCached(ghost) 2nd        -> null        0 ms   db calls so far: 3 (hit)
== condition="#item.length() > 4"
priceCond(dosa) 1st                -> 8900      208 ms   db calls so far: 4 (MISS)
priceCond(dosa) 2nd                -> 8900      200 ms   db calls so far: 5 (MISS)
priceCond(biryani) 1st             -> 24900     201 ms   db calls so far: 6 (MISS)
priceCond(biryani) 2nd             -> 24900       0 ms   db calls so far: 6 (hit)
== Optional return type
optPrice(lassi) 1st                -> Optional[5900]  201 ms   db calls so far: 7 (MISS)
optPrice(lassi) 2nd                -> Optional[5900]    0 ms   db calls so far: 7 (hit)
optPrice(ghost) 1st                -> Optional.empty  200 ms   db calls so far: 8 (MISS)
optPrice(ghost) 2nd                -> Optional.empty    0 ms   db calls so far: 8 (hit)
   stored in 'opt': {lassi=5900, ghost=null}

What you see: with unless = "#result == null" the missing item ghost misses twice, so every request for it hits the database. Without unless, the second call is a hit: Spring stored the null itself. For condition, dosa (4 letters) never hit, biryani hit on the second call. The Optional results hit, and the cache holds 5900 and a null, not Optional objects.

Why: Spring unwraps an Optional before storing it and wraps the stored value again on a hit. So an empty Optional is stored as a null, and the method sees the same behaviour as for a plain null. Whether to cache "not found" is a business decision. Caching it protects the database from a flood of lookups for missing items (an attack technique known as cache penetration). It also hides a newly created item until the null expires, so give "not found" a short expiry.

Bridge: the stampede, many threads missing at once

A cache stampede (also called a thundering herd) happens when many requests ask for the same missing key at the same moment. Each one sees a miss, so each one runs the slow method. The cache then holds one answer, but the database has already paid for all of them.

QuickBite met it after a deploy. A new version starts with an empty cache. The lunch rush arrives in the first minute, and 200 requests ask for the biryani price at once. Instead of one query, the database receives 200, and the slow queries make the next requests slower, which makes more of them overlap.

We reproduce it in miniature: 20 threads wait on a latch (a starting gate), then all call the same method on a cold cache. First without protection, then with sync = true.

MenuService.java (stampede) · Boot 4.2runs offline
@Cacheable("plain")
public Integer slow(String item) { return repo.find(item); }

@Cacheable(value = "synced", sync = true)
public Integer slowSync(String item) { return repo.find(item); }
DemoRunner.java (stampede) · Boot 4.2runs offline
CountDownLatch go = new CountDownLatch(1);
for (int i = 0; i < 20; i++) futures.add(pool.submit(() -> {
    go.await();                                        // all 20 wait here
    return sync ? menu.slowSync("biryani") : menu.slow("biryani");
}));
go.countDown();                                        // open the gate
run --demo=stampede · Boot 4.2runs offline
sync=false 20 threads, same key, cold cache: db calls = 20, wall time = 221 ms
sync=true  20 threads, same key, cold cache: db calls = 1, wall time = 205 ms
sync = false (the default) sync = true 20 threads, same key cold cache, all start at t = 0 cache lookup: 20 misses nobody has stored anything yet database: 20 identical queries measured: db calls = 20 20 × 200 ms of database work 20 threads, same key cold cache, all start at t = 0 lock per key: 1 thread wins 19 threads wait at the lock database: 1 query measured: db calls = 1 the 19 waiters then read the cache
Fig. 22.6 — A stampede, and the lock that stops it. With sync = true the cache lets one caller per key compute the value while the others wait. The lock exists inside one JVM only, so six pods can still produce six queries.

What you see: without protection, 20 database calls. With sync = true, exactly 1. The wall time is the same (about 205 to 221 ms), because the waiting threads still wait for one 200 ms query. What changed is the load on the database, which dropped to one twentieth.

Why: with sync = true the interceptor asks the cache to run the loading step itself, under a lock for that key. The first thread loads; the rest block on the lock and then find the value. Different keys do not block each other.

Idiom: sync = true for hot, expensive keys

The problem: a popular key expires (or the cache starts cold) and every concurrent request recomputes it. The more expensive the method, the longer the window, and the more requests pile in.

How it works: @Cacheable(sync = true) makes the cache provider load the value under a per-key lock. It is a Spring feature, but the lock is the provider's (Caffeine does it natively; Redis cannot lock across servers this way).

  1. Find the hot and expensive keys: the menu, the home page feed, an exchange-rate lookup. A method that takes 2 ms does not need it.
  2. Add sync = true: it has restrictions (for example, one cache name and no other cache operation on the same method), so check the reference documentation for your version if Spring complains at startup.
  3. Remember the scope: one JVM. With N pods expect up to N loads, not one. For a hard guarantee use a distributed lock or refresh the entry in the background.

Bridge: providers, and why "no TTL" is not an oversight

Here is a fact that surprises people: @Cacheable has no expiry setting. There is no ttl = 10. The Spring cache abstraction only defines how to talk to a cache (get, put, evict). How long entries live, how many fit, and where they are stored are decisions of the provider, the library behind the CacheManager. That is why the same annotations work with a plain map, Caffeine and Redis.

The consequence is easy to miss. If you do nothing, you get the provider's default, and the default of the simplest provider is "keep everything forever". We start with that one.

The default provider: ConcurrentMapCacheManager

When Boot finds no provider library, it uses ConcurrentMapCacheManager: one ConcurrentHashMap per cache. It is perfect for tests and for a map of 30 constants. It has no time limit and no size limit. Every distinct key adds an entry and nothing ever removes one.

QuickBite's search page cached results per search text. Users type anything, so the number of distinct keys has no ceiling. We simulate it: a cached method that returns a 1,000-character string for key numbers 1 to 200,000 (about 200 MB if all were kept), run with only 128 MB of heap.

MenuService.java (growth) · Boot 4.2runs offline
@Cacheable("blobs")
public String blob(int i) { return "x".repeat(1000); }       // ~1 KB per entry
run --demo=growth --spring.cache.type=simple -Xmx128mruns offline
cache manager: ConcurrentMapCacheManager
max heap = 128 MB
keys=20,000  used heap=43 MB
keys=40,000  used heap=64 MB
keys=60,000  used heap=86 MB
keys=80,000  used heap=106 MB
keys=100,000  used heap=125 MB
Caused by: java.lang.OutOfMemoryError: Java heap space

What you see: the used heap rises by about 21 MB for every 20,000 keys: 43 MB, 64 MB, 86 MB, 106 MB, 125 MB. Near 100,000 keys, with a 128 MB limit, the JVM throws OutOfMemoryError: Java heap space and the demo dies. Nothing was leaking in the usual sense. The cache was doing its job, and its job has no end.

Now the same loop with Caffeine and a size limit, set by one property.

run --demo=growth --spring.cache.caffeine.spec=maximumSize=10000 -Xmx128mruns offline
cache manager: CaffeineCacheManager
max heap = 128 MB
keys=20,000  used heap=33 MB
keys=40,000  used heap=34 MB
keys=60,000  used heap=34 MB
keys=80,000  used heap=34 MB
keys=100,000  used heap=35 MB
keys=120,000  used heap=35 MB
keys=140,000  used heap=34 MB
keys=160,000  used heap=34 MB
keys=180,000  used heap=35 MB
keys=200,000  used heap=33 MB
finished 200,000 keys

What you see now: the heap stays at 33 to 35 MB for all 200,000 keys, and the program finishes. Caffeine keeps at most 10,000 entries and quietly drops the ones least likely to be used again.

Bridge: Caffeine, size and TTL

Caffeine is an in-memory cache library for Java, and it is the usual default for local caches. Spring Boot configures it through one property, spring.cache.caffeine.spec, a comma-separated list of settings.

application.properties · Boot 4.2runs offline
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m,recordStats
  1. maximumSize=500: at most 500 entries per cache. Beyond that, Caffeine evicts entries that are least likely to be read again.
  2. expireAfterWrite=10m: an entry older than 10 minutes counts as missing. There is also expireAfterAccess, which measures from the last read.
  3. recordStats: keeps hit and miss counters. They cost a little; turn them on if you plan to look at them (we do, below).

To see expiry without waiting 10 minutes, run the same price() method with expireAfterWrite=2s and read it at 0, 1, 2.3 and 2.5 seconds.

run --demo=expiry --spring.cache.caffeine.spec=expireAfterWrite=2s,recordStatsruns offline
price(biryani) t=0.0s              -> 24900     276 ms   db calls so far: 1 (MISS)
price(biryani) t=1.0s              -> 24900       2 ms   db calls so far: 1 (hit)
price(biryani) t=2.3s (expired)    -> 24900     200 ms   db calls so far: 2 (MISS)
price(biryani) t=2.5s              -> 24900       0 ms   db calls so far: 2 (hit)
caffeine stats: CacheStats{hitCount=2, missCount=2, loadSuccessCount=0, loadFailureCount=0, totalLoadTime=0, evictionCount=1, evictionWeight=1}

What you see: at 1.0 s the entry is still there (2 ms). At 2.3 s it has expired, so the call costs 200 ms again and refills it. At 2.5 s it hits again. The statistics line reports 2 hits, 2 misses and one eviction, the expired entry.

Why: Caffeine does not run a timer for each entry. It checks the age when the entry is read (and during routine cleanup), so an expired entry that nobody asks for may sit in memory a little longer. That is fine; it can never be returned after it expired.

Idiom: set TTL and size in the provider, never trust "forever"

The problem: the cache annotation has no expiry, so a team adds @Cacheable, sees the speed-up, and ships. The defaults then keep entries forever, so a write path you forgot (see the evict idiom) leaves stale data for weeks, and the entry count grows until memory runs out.

How it works: every cache gets two limits in the provider's configuration: a maximum size and a time to live. The size protects memory. The time protects correctness, because after the time limit a wrong value cannot survive.

  1. Pick the TTL from the business: how long may a customer see an old price? 10 minutes for menu prices, 1 minute for stock, hours for a country list.
  2. Pick the size from memory: entries × average size must fit the heap with room to spare. Start at a few thousand and watch the stats.
  3. Different caches, different limits: with the property above all caches share one spec. When they must differ, define a CaffeineCacheManager bean or register each cache with its own builder.

One more TTL trap deserves a name: the cache avalanche. If you load 5,000 entries at deploy time with the same 10-minute TTL, all 5,000 expire in the same second, and the database receives 5,000 queries at once, which is a stampede on every key together. Two cheap defences exist.

Spread the expiry with a little randomness (Caffeine has no built-in jitter for a spec string, so you set different TTLs per cache or add jitter in a custom builder), and warm the cache gradually instead of all at once. Or accept it when the data set is small, and let sync = true keep each key to one query.

A short rule of thumb for sizing: take the number of distinct keys that matter (30 menu items, 500 restaurants), multiply by the size of one entry, and check that the product is a small fraction of the heap. If the key space is open-ended, the size limit is not optional.

Bridge: Redis, a cache shared by every pod

Redis is a separate server that keeps data in memory and answers over the network. Used as a cache, it gives every pod the same view: a value stored by pod A is visible to pod B. The price is a network round trip on every lookup and the need to turn objects into bytes.

Spring Boot needs the Redis starter and a few properties. The prefix is useful when several applications share one Redis.

application.properties · Boot 4.2runs offline
spring.cache.type=redis
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.cache.redis.time-to-live=10m
spring.cache.redis.key-prefix=quickbite:
spring.cache.redis.cache-null-values=true

We ran this against a real Redis 7 started with docker run --rm -d -p 16379:6379 redis:7. The method returns a small record. First with the default serialization (Java's own), then with a JSON serializer. We look at the stored key, its remaining time to live and the stored value with redis-cli.

run --demo=redis against redis:7 · Boot 4.2needs Docker
# JDK serialization (default)
cache manager: RedisCacheManager
item(biryani) 1st                  -> MenuItem[name=biryani, cents=24900] 1356 ms   db calls so far: 1 (MISS)
item(biryani) 2nd                  -> MenuItem[name=biryani, cents=24900]   43 ms   db calls so far: 1 (hit)
$ redis-cli --scan
quickbite:items::biryani
$ redis-cli TTL quickbite:items::biryani
19
$ redis-cli GET (escaped)
"\xac\xed\x00\x05sr\x00\x1ccom.quickbite.cache.MenuItem\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x02I\x00\x05centsL\x00\x04namet\x00\x12Ljava/lang/Stri

# JSON serializer bean (demo.redis-json=true)
cache manager: RedisCacheManager
item(biryani) 1st                  -> MenuItem[name=biryani, cents=24900]  951 ms   db calls so far: 1 (MISS)
item(biryani) 2nd                  -> MenuItem[name=biryani, cents=24900]   42 ms   db calls so far: 1 (hit)
quickbite:items::biryani
30
{"@class":"com.quickbite.cache.MenuItem","name":"biryani","cents":24900}

What you see: the key is quickbite:items::biryani: prefix, cache name, two colons, the key. The remaining time to live is counting down (19 of 20 seconds, then 30 in the second run). The default value is a Java-serialized blob (\xac\xed\x00\x05...) that only a Java program can read and that breaks if you rename the class.

The JSON value is readable by any tool. The first call took about a second because it includes opening the Redis connection; the second, a hit, cost 42 to 43 ms in this setup.

Why: Redis stores bytes, so something must convert the object. The JSON version came from a configuration bean using GenericJacksonJsonRedisSerializer (Jackson 3, class names under tools.jackson). It writes a @class field so it can rebuild the right type, which means the stored JSON names your Java class. Restrict which packages it may rebuild, as the next snippet does.

RedisJsonConfig.java · Boot 4.2needs Docker
@Bean
RedisCacheConfiguration cacheConfiguration() {
    return RedisCacheConfiguration.defaultCacheConfig()
        .entryTtl(Duration.ofSeconds(30))
        .prefixCacheNameWith("quickbite:")
        .serializeValuesWith(SerializationPair.fromSerializer(
            GenericJacksonJsonRedisSerializer.builder()
                .enableDefaultTyping(BasicPolymorphicTypeValidator.builder()
                    .allowIfSubType("com.quickbite").build())
                .build()));
}

One detail in the output is easy to miss. The second run printed a time to live of 30, not the 20 that the property asked for. When your own RedisCacheConfiguration bean exists, Boot uses it as the base and the spring.cache.redis.* properties no longer apply to it, which is why the bean sets the TTL and prefix itself. If a property seems ignored, look for a bean that replaced it.

What does a Redis cache need that a local cache does not? A serializer for values, a key prefix, a TTL (Redis has no default), a decision about null values, a connection with timeouts, and a plan for when Redis is down. By default a failed Redis call throws, and the request fails. Most services decide that a cache outage should mean "slower", not "down", and add a CacheErrorHandler that logs and falls back to the method.

Which provider? The stack table

Cache provider choices
OptionPick it whenCost or catch
ConcurrentMapCacheManager (Boot's fallback)Tests, a handful of constants, a demo.No TTL, no size limit: unbounded growth (the OutOfMemoryError above).
Caffeine (local, in-process)One pod, or data that may differ slightly between pods. Lowest latency (0 to 2 ms above).Each pod has its own copy: stale reads between pods, cold start after every deploy, memory per pod.
Redis (shared, network)Many pods that must agree, large data sets, survive restarts.Network hop on every call (about 40 ms in this local setup, usually 1 ms or less in a good network), serialization, one more thing to run and monitor.
Two levels (Caffeine in front of Redis)Very hot keys where even Redis latency hurts.Two copies to keep consistent. Spring has no built-in two-level manager; you write a composite or use a library.

Switch when: the data must be identical on all pods (move from Caffeine to Redis), or Redis latency shows up in your p99 (add a short-lived Caffeine layer in front).

Bridge: multi-instance staleness

Now the scenario QuickBite will really meet. Three pods each run the menu service, each with its own Caffeine cache, and one shared database. An admin changes the price of biryani from 249 to 269. The request lands on pod A, and the evict runs on pod A. Pods B and C never hear about it.

We simulate three pods inside one JVM: three separate Caffeine caches (3 s TTL) over one shared map that plays the database.

DemoRunner.java (three pods) · Boot 4.2runs offline
static class Pod {
    final String name; final Map<String, Integer> db; final CaffeineCache cache;
    Pod(String name, Map<String, Integer> db) {
        this.name = name; this.db = db;
        this.cache = new CaffeineCache("prices", Caffeine.newBuilder()
                .expireAfterWrite(Duration.ofSeconds(3)).build());
    }
    Integer price(String item) { return cache.get(item, () -> db.get(item)); }
}
run --demo=pods · Boot 4.2runs offline
all pods warm: pod-A=24900  pod-B=24900  pod-C=24900
-- price changes to 26900; the request hit pod-A, which evicts its own entry only
after change:  pod-A=26900  pod-B=24900  pod-C=24900
-- fix 1: broadcast the eviction (stand-in for Redis pub/sub)
after broadcast: pod-A=27900  pod-B=27900  pod-C=27900
-- fix 2: TTL only. Change the price, evict nowhere, wait for the 3 s TTL
t=0.0s:        pod-A=27900  pod-B=27900  pod-C=27900
t=3.2s:        pod-A=28900  pod-B=28900  pod-C=28900
Price change 24900 to 26900, evicted on pod A only Database biryani = 26900 (the truth) Pod A (got the request) evicted, reloaded serves 26900 Pod B never told, entry still valid serves 24900 (stale) Pod C never told, entry still valid serves 24900 (stale) reload B and C stay stale until their TTL ends (up to the whole TTL, 10 min in the incident) A customer who is routed to B sees 249, then to A sees 269, on the same page.
Fig. 22.7 — Local caches drift apart. The database is right, pod A is right, and two pods are wrong for as long as their entries live. The size of the problem is the TTL, not the code.

What you see: after the change, pod A answers 26900 and pods B and C still answer 24900. The broadcast version (every pod evicts) makes all three agree at once. In the TTL-only run, the database says 28900 but all three pods still answer 27900 at t = 0, and all three answer 28900 after the 3 s TTL.

The options, from cheapest to most work, are in this table.

Keeping pods consistent
OptionPick it whenCost or catch
Short TTLStaleness of seconds or a minute is acceptable.More database load (every pod reloads each key every TTL). Staleness never reaches zero.
Shared cache (Redis)All pods must see one value.Network latency, one more system to operate.
Broadcast eviction (Redis pub/sub, a message topic)You want local speed and fast invalidation.A message can be lost, so keep a TTL as backup. We ran only an in-JVM stand-in for the broadcast above.
Versioned keys (menu:v42:biryani)Bulk changes ("a new menu was published").The version must be read from somewhere fast and shared; old versions linger until they expire.

Bridge: seeing the cache work, with metrics

A cache you cannot see is a cache you cannot trust. Two tools exist. The Actuator endpoint /actuator/caches lists the caches. Micrometer metrics named cache.gets, cache.puts, cache.evictions and cache.size count what happens, and cache.gets carries a result tag with the values hit and miss. The hit ratio is hits divided by hits plus misses. For a menu cache you expect well over 90 percent.

We started the app as a web application, warmed the cache (2 misses and 2 hits), and asked the endpoints with curl. Two settings were needed, and the first attempt showed why.

application.properties · Boot 4.2runs offline
management.endpoints.web.exposure.include=caches,metrics
spring.cache.cache-names=prices
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m,recordStats

With recordStats alone, the metrics list had no cache entries at all. The cause: the caches were created lazily on first use, after Boot had already registered its metrics, so nothing was bound to the meter registry. Declaring the names with spring.cache.cache-names creates the caches at startup, and then they appear. The same is true for any dynamically created cache: if the metrics are missing, name your caches up front.

curl · Boot 4.2runs offline
[{'statistic': 'COUNT', 'value': 4.0}] [{'tag': 'result', 'values': ['hit', 'miss']}, {'tag': 'cache.manager', 'values': ['cacheManager']}, {'tag': 'cache', 'values': ['prices']}, {'tag': 'name', 'values': ['prices']}]
$ curl -s 'localhost:18431/actuator/metrics/cache.gets?tag=name:prices&tag=result:hit'
cache.gets [{'statistic': 'COUNT', 'value': 2.0}]
$ curl -s 'localhost:18431/actuator/metrics/cache.gets?tag=name:prices&tag=result:miss'
cache.gets [{'statistic': 'COUNT', 'value': 2.0}]
cache.size [{'statistic': 'VALUE', 'value': 2.0}]

What you see: 2 hits and 2 misses out of 4 lookups (a 50 percent ratio in this tiny warm-up), and a cache size of 2 entries. The available tags for cache.gets include result, cache and name. Alert on a falling hit ratio and on a rising eviction count: both mean the size limit is too small.

Bridge: testing that a method is really cached

Do not trust the annotation, assert the effect. The test replaces the repository with a mock (a stand-in that records calls), calls the service twice, and verifies the repository was called once. A second test checks that a write evicts. Both run in a real Spring context, because the proxy only exists inside one.

MenuServiceCachingTest.java · Boot 4.2runs offline
@SpringBootTest(args = "--demo=none")
class MenuServiceCachingTest {
    @Autowired MenuService menu;
    @Autowired CacheManager cacheManager;
    @MockitoBean PriceRepository repo;

    @BeforeEach void clean() {
        cacheManager.getCacheNames().forEach(n -> cacheManager.getCache(n).clear());
    }

    @Test void secondCallIsServedFromTheCache() {
        when(repo.find("biryani")).thenReturn(24900);
        assertThat(menu.price("biryani")).isEqualTo(24900);
        assertThat(menu.price("biryani")).isEqualTo(24900);
        verify(repo, times(1)).find("biryani");
    }

    @Test void changingThePriceEvictsTheEntry() {
        when(repo.find("biryani")).thenReturn(24900);
        menu.price("biryani");
        menu.changePrice("biryani", 26900);
        when(repo.find("biryani")).thenReturn(26900);
        assertThat(menu.price("biryani")).isEqualTo(26900);
        verify(repo, times(2)).find("biryani");
    }
}
./mvnw -o test -Dtest=MenuServiceCachingTestruns offline
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.84 s -- in com.quickbite.MenuServiceCachingTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

Two tips. Clear the caches before each test, or one test's entries leak into the next and the order of tests changes the result. And do not use @MockitoSpyBean on the service itself to count calls: a spy replaces the proxy's target, and it is easy to end up testing the spy instead of the cache.

When not to cache

A review checklist for any new @Cacheable

When someone adds a cache in a pull request, five questions catch most bugs. You can answer each from this section.

  1. Is the key explicit and stable? Does it contain only the inputs that decide the answer, and does every part have a working equals?
  2. What limits it? A TTL and a maximum size in the provider, not the default map.
  3. Who invalidates it? Every write path has a @CacheEvict or @CachePut, or the TTL is short enough that nobody minds.
  4. What if many callers miss together? A hot, expensive key has sync = true; a many-pod system accepts one load per pod.
  5. How will we know it works? The cache is named at startup, recordStats is on, and a hit-ratio panel exists.

If the answer to any of these is "we have not thought about it", the cache is not ready, however fast the demo looks. The speed-up is the easy half of caching. The five questions are the other half.

05 · Asynchronous methods@Async: Running Work in the Background Without Losing It

An asynchronous method returns to its caller at once and does its work later, on another thread. @Async gives you that with one annotation, and it hands the job to an executor, a pool of worker threads. The speed-up is real and immediate. The costs are quiet: errors go somewhere else, the logged-in user and the request id are left behind, a transaction does not follow the work, and anything still waiting when the process stops is gone.

QuickBite's checkout does four things: it saves the order, charges the card, writes an audit row, and sends a confirmation email through a slow mail server. The email takes about 2 seconds on a good day and 4 seconds on a bad one. Checkout waits for it, so the 99th-percentile checkout time (p99, the time that 99 of 100 requests beat) is 4 seconds. Customers do not need the email before they see "order placed", so the team moves it off the request thread with @Async.

We measure that change first. The "email" sleeps 2,000 ms. One method is plain, the other has @Async, and the program prints the caller's thread, the worker's thread and the time checkout spent.

MailService.java · Boot 4.2runs offline
public void sendSync(String to) {
    sleep(2000);                                           // pretend: a slow mail server
    System.out.println("  email to " + to + " sent on [" + t() + "]");
}

@Async
public void sendAsync(String to) {
    sleep(2000);
    System.out.println("  email to " + to + " sent on [" + t() + "]");
}

As with caching, one line on the application class switches the feature on: @EnableAsync. Without it, @Async is ignored and the method runs on the caller's thread, which looks exactly like a slow email and has no error message.

run --demo=sync-vs-async · Boot 4.2runs offline
caller thread = [main]
  email to asha@example.com sent on [main]
checkout with sendSync : 2001 ms
checkout with sendAsync: 3 ms
  email to asha@example.com sent on [task-1]

What you see: the synchronous call kept checkout busy for 2,001 ms and ran on the caller thread, main. The asynchronous call returned in 3 ms, and the email was sent two seconds later on a worker thread called task-1. Checkout time dropped from about 2,000 ms to a few milliseconds.

That is the good news. After a week in production the team found three things the annotation had hidden.

  1. A failing email left no trace in the checkout. The caller got no exception and no result. The only evidence was one error line in the log, if anyone looked.
  2. The audit row said the user was "anonymous". The code that wrote the row ran on a worker thread, and the logged-in user did not travel with the work.
  3. Emails vanished on every deploy. Work that was queued in memory died with the old process.

Each of these has a cause you can point to and a fix you can run. We take them in order, after one look at the machinery.

Bridge: how @Async works, one level down

Like @Cacheable, @Async is a proxy trick (E4 explains proxies). @EnableAsync registers a post-processor that wraps the bean in a proxy whose interceptor is called AsyncExecutionInterceptor. When you call sendAsync(...), the interceptor does not run your method. It wraps the call in a small task object, hands the task to a TaskExecutor (Spring's name for "something that runs tasks on threads"), and returns. A worker thread runs the real method later.

Because the interceptor owns the hand-off, it also owns the problems of the hand-off. Figure 22.8 shows what moves to the worker and what stays behind.

What happens to sendAsync("asha") Caller thread [http-1] 1 calls the proxy 2 interceptor makes a task 3 submit() and return 4 carries on (3 ms) holds: user, MDC, open tx Executor queue of waiting tasks [ t3 ][ t2 ][ t1 ] reject if full (bounded) lost if the JVM dies Worker threads task-1, task-2, ... run your real method their own empty user, MDC, transaction Left behind on the caller thread SecurityContext, MDC request id (ThreadLocals) the open transaction and its session the exception (the caller has already returned) Carried over, if you ask for it a TaskDecorator copies context to the worker a CompletableFuture carries the result or error ids, not entities, carry the data
Fig. 22.8 — The async hand-off. The caller returns after step 3. Everything that lives in a ThreadLocal stays with the caller, so the worker starts clean. On the bean the @Async advice is the outermost one (measured order: async first), which is why @Async @Transactional starts the transaction on the worker.

Bridge: Boot's default executor, printed

You never created an executor, yet task-1 ran the email. Spring Boot created one for you, a bean named applicationTaskExecutor. We do not guess its settings; the next program prints them.

DemoRunner.java (defaults) · Boot 4.2runs offline
Object bean = ctx.getBean("applicationTaskExecutor");
System.out.println("applicationTaskExecutor is a " + bean.getClass().getName());
if (bean instanceof ThreadPoolTaskExecutor ex) {
    ThreadPoolExecutor tp = ex.getThreadPoolExecutor();
    System.out.println("  corePoolSize         = " + ex.getCorePoolSize());
    System.out.println("  maxPoolSize          = " + ex.getMaxPoolSize());
    System.out.println("  queueCapacity        = " + (tp.getQueue().remainingCapacity() + tp.getQueue().size()));
    System.out.println("  keepAliveSeconds     = " + ex.getKeepAliveSeconds());
    System.out.println("  allowCoreThreadTimeOut = " + tp.allowsCoreThreadTimeOut());
    System.out.println("  threadNamePrefix     = " + ex.getThreadNamePrefix());
}
run --demo=defaults · Boot 4.2runs offline
Executor beans: [applicationTaskExecutor]
applicationTaskExecutor is a org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
  corePoolSize         = 8
  maxPoolSize          = 2147483647
  queueCapacity        = 2147483647
  keepAliveSeconds     = 60
  allowCoreThreadTimeOut = true
  threadNamePrefix     = task-
runner finished at 00:45:41
  task 1 started on [task-1]
  task 1 FINISHED

What you see: core size 8, maximum size 2,147,483,647 (that is Integer.MAX_VALUE), queue capacity 2,147,483,647, keep-alive 60 seconds, core threads are allowed to time out, and the thread names start with task-.

Why this matters: a pool grows past its core size only when its queue is full (see the ThreadPoolExecutor decision path in E21). This queue never fills, so the "maximum" of two billion is never used. In practice you have eight threads and an unbounded queue. If tasks arrive faster than eight threads can finish them, the queue grows without limit, the heap fills, and the first symptom is an OutOfMemoryError far from the cause. There is no back-pressure at all.

The settings are properties, so you can change them without code.

Properties for the default executor
PropertyMeasured defaultMeaning
spring.task.execution.pool.core-size8Threads kept ready.
spring.task.execution.pool.max-sizeunboundedOnly used once the queue is full.
spring.task.execution.pool.queue-capacityunboundedSet a number to get a bounded queue, and then rejections.
spring.task.execution.pool.keep-alive60sHow long an idle thread waits before it ends.
spring.task.execution.pool.allow-core-thread-timeouttrueWhether core threads may also end when idle.
spring.task.execution.thread-name-prefixtask-Name of the threads in logs and thread dumps.

Bridge: the 60-second linger

A small surprise for anyone who runs a Spring Boot command-line tool. The work finishes, main returns, and the process stays alive for another minute. Nothing is wrong. The pool's worker threads are ordinary (non-daemon) threads, and a JVM exits only when every non-daemon thread has ended. An idle worker ends only after its keep-alive time, 60 seconds by default.

We measured it. The program uses @Async once, which creates one worker, then the runner returns without closing the application. The timer is the whole process, including about 7 seconds of startup.

time java -jar async-demo.jar --demo=defaults --lingerruns offline
$ time java -Xmx256m -jar async-demo.jar --demo=defaults --linger
runner finished at 00:46:08; main returns, JVM stays
JVM wall time: 66.98 s

$ ... --spring.task.execution.pool.keep-alive=5s
JVM wall time: 9.90 s

$ ... --spring.task.execution.pool.keep-alive=2s
JVM wall time: 8.43 s

What you see: 67 seconds in total with the default 60-second keep-alive. With keep-alive=5s the process ended after 9.9 seconds, and with 2 seconds after 8.4 seconds. The difference between those and the first run is almost exactly the keep-alive time.

In a web application you never notice, because the server keeps the process alive anyway. In a scheduled batch job, a Kubernetes job or a CI task, the extra minute is real money and a confusing delay. The cleanest fix is to end the application on purpose: System.exit(SpringApplication.exit(context)) closes the context (which shuts the executor down) and then exits. A shorter keep-alive is the second-best fix.

Bridge: separate executors for separate work

One shared pool for everything has a cruel failure mode. A slow report job and a quick email both queue behind the same eight threads. When the reports pile up, emails wait behind them, and checkout confirmations arrive twenty minutes late. This is called the noisy neighbour problem, and the cure is a bulkhead: separate pools, so one workload can fill only its own compartment, as in a ship.

The second problem is the unbounded queue we just saw. A pool that can say "I am full" is a pool that protects the rest of the system.

Idiom: one named, bounded executor per workload

The problem: every @Async method shares applicationTaskExecutor: 8 threads, an unbounded queue, no name that says what is running. A burst of one kind of work delays all the others, memory grows without warning, and a thread dump shows only task-3.

How it works: you declare an executor bean for each kind of work, with its own size, queue length and thread-name prefix, and you name it in the annotation: @Async("mailExecutor"). When the queue is full the executor applies a rejection policy: the default throws an exception to the caller, and the alternative CallerRunsPolicy makes the caller run the task itself, which slows the caller down and so slows the producer.

  1. Size by the work: a mail pool of 2 threads suits a mail server that takes 1 second per message and tolerates 2 parallel connections.
  2. Bound the queue: choose how many waiting tasks you can afford to lose or delay. Small numbers are good, because they make overload visible.
  3. Choose the full-queue behaviour: reject (the caller must handle the error) or caller-runs (automatic slow-down). Never silently discard.
  4. Name the threads: mail-1 in a log or thread dump tells you whose thread it is.
ExecutorsConfig.java · Boot 4.2runs offline
@Bean ThreadPoolTaskExecutor mailExecutor() {       // 2 threads + 3 waiting, then reject
    ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
    ex.setThreadNamePrefix("mail-");
    ex.setCorePoolSize(2);
    ex.setMaxPoolSize(2);
    ex.setQueueCapacity(3);
    return ex;
}

@Bean ThreadPoolTaskExecutor reportExecutor() {     // 1 thread + 1 waiting, then the caller runs it
    ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
    ex.setThreadNamePrefix("report-");
    ex.setCorePoolSize(1);
    ex.setMaxPoolSize(1);
    ex.setQueueCapacity(1);
    ex.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    return ex;
}

The demo submits 7 mail tasks (each takes 1 second) to the mail pool, then 4 report tasks (0.5 second each) to the report pool. The mail pool can hold 2 running plus 3 waiting, so the sixth and seventh must be rejected.

run --demo=reject --demo.executors=named · Boot 4.2 (trimmed)runs offline
Executor beans: [mailExecutor, reportExecutor]
  mail #1 running on [mail-1]
submitted #1
submitted #2
submitted #3
submitted #4
submitted #5
  mail #2 running on [mail-2]
submit #6 FAILED: TaskRejectedException: ExecutorService in active state did not accept task: org.springframework.aop.in
submit #7 FAILED: TaskRejectedException: ExecutorService in active state did not accept task: org.springframework.aop.in
-- reportExecutor (CallerRunsPolicy): caller thread = [main]
  report #1 running on [report-1]
  report #3 running on [main]
  report #2 running on [report-1]
  mail #3 running on [mail-1]
  mail #4 running on [mail-2]
  report #4 running on [report-1]
  mail #5 running on [mail-1]

What you see: the first line lists the executor beans: only mailExecutor and reportExecutor. Mail tasks 1 to 5 were accepted (mail-1 and mail-2 run two at a time, three wait). Submits 6 and 7 failed at once with TaskRejectedException, thrown to the caller. For reports, task 3 ran on thread main: the pool was full, so the caller did the work itself.

Why the first line matters: Boot creates applicationTaskExecutor only when no other executor bean exists. The moment you declare your own, the default disappears. An @Async method with no name then has to choose among your executors. Spring looks for a single TaskExecutor or one named taskExecutor, and otherwise falls back to a simple executor that starts a new thread per task (check the reference for your version). The safe habit is to name the executor on every @Async in a codebase that has more than one.

Bridge: void or CompletableFuture?

An @Async method may return void or a CompletableFuture. (A plain Future works too, and Java's CompletableFuture is covered in E21.) The choice decides who can learn about the result and the failure.

Return types for @Async
Return typeCaller getsIf the method throws
voidNothing. Fire and forget.Nobody is waiting, so the exception goes to an uncaught-exception handler. The default handler writes it to the log.
CompletableFuture<T>A handle: join(), thenApply(...), exceptionally(...)The future completes with the failure. join() rethrows it, wrapped in CompletionException.
run --demo=types · Boot 4.2 (log line trimmed)runs offline
-- void method that throws (default handler):
ERROR 1791031 --- [async-demo] [         task-1] .a.i.SimpleAsyncUncaughtExceptionHandler : Unexpected exception occurred invoking async method: public void com.quickbite

java.lang.IllegalStateException: SMTP 550 mailbox full for asha@example.com

-- CompletableFuture method that throws:
  join() threw CompletionException caused by java.lang.IllegalStateException: SMTP 550 mailbox full for asha@example.com
  isCompletedExceptionally = true
-- CompletableFuture method that works:
  sent to asha@example.com on [task-3]

What you see: for the void method, the caller saw nothing. The only record is the line from SimpleAsyncUncaughtExceptionHandler, a log entry at ERROR level with the stack trace (removed here to save space). For the CompletableFuture method, join() threw CompletionException whose cause is the original error, and isCompletedExceptionally is true.

So in this version the failure of a void method is not completely lost: the default handler logs it. It is lost to the program. Nothing counts it in a metric, nothing alerts on it, and no code can react. In many teams the log level or the log search makes it effectively invisible too. If the result matters at all, return a future and handle it. If it is truly fire-and-forget, install your own handler.

Idiom: install an AsyncUncaughtExceptionHandler

The problem: a void @Async method fails, and the only trace is a log line in the default format. No metric moves, no alert fires, and the customer never gets the email.

How it works: a configuration class implements AsyncConfigurer and returns your own handler. Spring calls it with the exception, the method and the arguments. There you do what the failure needs: count it, alert, save the work for retry.

  1. Implement AsyncConfigurer: override getAsyncUncaughtExceptionHandler() only. Leave getAsyncExecutor() alone so Boot's executor selection still applies.
  2. Record, do not swallow: increment a Micrometer counter, log with the method name and arguments, and write a row to a "failed jobs" table if the work can be retried.
  3. Do not rely on it for results: it covers void methods only. A future carries its own error.
ExecutorsConfig.java (handler) · Boot 4.2runs offline
@Configuration
static class Handler implements AsyncConfigurer {
    @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> System.out.println("  HANDLER caught "
            + ex.getClass().getSimpleName() + ": " + ex.getMessage()
            + "  in " + method.getName() + "(" + params[0] + ")");
    }
}
run --demo=handler --demo.handler=true · Boot 4.2runs offline
  HANDLER caught IllegalStateException: SMTP 550 mailbox full for asha@example.com  in sendFailing(asha@example.com)

What you see now: one line, produced by our handler, naming the exception, the message, the method and the argument (the email address). In a real service this is where the counter and the alert go.

Bridge: the user and the request id do not follow the work

Spring Security keeps "who is logged in" in a ThreadLocal: a variable that every thread has its own private copy of. Logging does the same with the MDC (Mapped Diagnostic Context), the place where you put a request id so every log line can carry it. A ThreadLocal belongs to one thread. A worker thread starts with empty ones. Figure 22.8 showed them staying behind.

The program puts user alice and request id req-42 on the caller thread, calls an @Async method, and prints the same two values from both threads.

Broken

Default executor. The worker thread has an empty context.

run --demo=context · Boot 4.2runs offline
caller [main] user=alice  requestId=req-42
async  [task-1] user=anonymous  requestId=null

Fixed

A TaskDecorator copies both to the worker.

run --demo=context --demo.decorator=trueruns offline
caller [main] user=alice  requestId=req-42
async  [task-1] user=alice  requestId=req-42

The shift: context must be copied at the moment of submission, because by the time the worker runs, the caller's thread may be doing something else.

What you see: on the left the audit code would write "anonymous" and the log lines would have no request id. On the right the worker sees alice and req-42. The word "anonymous" is what our printing code shows for a missing authentication; a real audit table shows whatever your code does with null.

Idiom: copy context with a TaskDecorator

The problem: anything stored in a ThreadLocal (the security context, the MDC, a tenant id, a locale) is invisible on the worker thread. The symptoms are quiet: an audit row for "anonymous", log lines you cannot join by request, a query run for the wrong tenant, an @PreAuthorize that denies a call that worked a moment earlier.

How it works: a TaskDecorator receives each task at the moment it is submitted, on the caller's thread. It reads the context there and returns a new task that restores the context on the worker, runs the original task, and cleans up in a finally.

  1. Capture on submit: inside decorate(task), copy the MDC map and the authentication now.
  2. Restore on the worker: set them, run the task.
  3. Always clean up: clear them in finally. Pool threads are reused, and a leftover user would leak into the next task, which is a security bug.
ExecutorsConfig.java (decorator) · Boot 4.2runs offline
@Bean TaskDecorator contextDecorator() {
    return task -> {
        Map<String, String> mdc = MDC.getCopyOfContextMap();          // on the caller
        SecurityContext copy = SecurityContextHolder.createEmptyContext();
        copy.setAuthentication(SecurityContextHolder.getContext().getAuthentication());
        return () -> {                                                // on the worker
            try {
                if (mdc != null) MDC.setContextMap(mdc);
                SecurityContextHolder.setContext(copy);
                task.run();
            } finally {
                MDC.clear();
                SecurityContextHolder.clearContext();
            }
        };
    };
}

Notice what is not in the code: we never told the executor about the decorator. Spring Boot 4.2 found the TaskDecorator bean and applied it to applicationTaskExecutor by itself (the output above proves it). For an executor you build yourself, call setTaskDecorator on it.

Spring Security also ships a ready-made wrapper that copies only the security context. We ran it on a separate executor. In the Security 7.2 jar we used, the class that fits Spring's executor interface is DelegatingSecurityContextSchedulingTaskExecutor (the Async variant of earlier versions was not in that jar, so check your version).

run --demo=context --demo.executors=secure · Boot 4.2runs offline
caller [main] user=alice  requestId=req-42
  async  [secure-1] user=alice  requestId=null

What you see: the user came across (alice), but the request id is null. The wrapper knows only about security. MDC needs a decorator on the pool, so a service with both needs the decorator, or a decorator plus the wrapper.

Bridge: @Async and @Transactional together

Both annotations are advice on the same proxy. Part A measured their order on Boot 4.2: the async advice is the outermost, so the hand-off happens first and the transaction begins on the worker thread (the order is explained in the interceptor chain). Two consequences follow, and the demo shows both.

  1. The caller's transaction does not follow the work. The worker runs in its own, brand-new transaction, with its own database session.
  2. Entities from the caller are detached on the worker. A lazily loaded collection (one that is loaded from the database only when first touched) cannot be read, because the session that would load it is a different one, or already closed.
MailService.java (@Async @Transactional) · Boot 4.2runs offline
@Async @Transactional
public CompletableFuture<Integer> countLinesOfEntity(OrderEntity order) {
    return CompletableFuture.completedFuture(order.getLines().size());   // lazy collection
}

@Async @Transactional
public CompletableFuture<Integer> countLinesById(long id) {
    return CompletableFuture.completedFuture(
            orders.findById(id).orElseThrow().getLines().size());
}

The runner saves an order with two lines, loads it back after the transaction ended (so it is detached), and then tries both ways. After that it starts a worker inside an open, uncommitted transaction of the caller.

run --demo=tx · Boot 4.2 (H2, JPA)runs offline
-- pass the ENTITY to an @Async @Transactional method:
  org.hibernate.LazyInitializationException: Cannot lazily initialize collection of role 'com.quickbite.async.OrderEntity.lines' with key '1' (no session)
-- pass the ID:
  lines = 2
-- worker started INSIDE the caller's open transaction, before commit:
  caller [main] tx active=true
  worker [task-3] tx active=true tx name=com.quickbite.async.MailService.txInfo sees order 2? false

What you see: passing the entity failed with LazyInitializationException ... (no session). Passing the id worked and returned 2 lines. In the last case the caller's transaction was active on main, the worker had a transaction of its own named after MailService.txInfo, and the worker could not see the order that the caller had saved but not yet committed (sees order 2? false).

Why: the order of the two events is a race you lose. The worker starts as soon as it can; the caller commits later. If the worker looks for a row the caller has not committed, it finds nothing, and the error looks like a flaky test. The fix is to start the async work after the commit. Spring has a tool for that, @TransactionalEventListener(phase = AFTER_COMMIT), in the events part of the scheduling section.

The working rule is short: pass ids and plain values to an async method, never entities, and let the method load what it needs in its own transaction. See also E5 on lazy loading.

Bridge: virtual threads

Since Spring Boot 3.2 a single property switches Boot's executors from pools of platform threads to virtual threads: very cheap threads that the JVM, not the operating system, schedules (E21 builds them from zero). We run the same two tasks with the property off and on, and print the executor's class and whether each thread is virtual.

run --demo=virtual · Boot 4.2 (property off)runs offline
applicationTaskExecutor is a org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
  task 1 started on [task-1] virtual=false
  task 2 started on [task-2] virtual=false
  task 1 FINISHED
  task 2 FINISHED
run --demo=virtual --spring.threads.virtual.enabled=trueruns offline
applicationTaskExecutor is a org.springframework.core.task.SimpleAsyncTaskExecutor
  task 2 started on [task-2] virtual=true
  task 1 started on [task-1] virtual=true
  task 1 FINISHED
  task 2 FINISHED

What you see: with the property off, applicationTaskExecutor is the familiar ThreadPoolTaskExecutor and the threads are not virtual. With it on, the executor is a SimpleAsyncTaskExecutor and each task ran on a virtual thread, still named task-1, task-2.

What changes: there is no pool size and no queue. Each task gets a new virtual thread, so nothing waits in a queue and the settings from the property table (core size, queue capacity) no longer apply. That is good for tasks that spend their time waiting on I/O. It is dangerous for anything that needs a limit. A flood of 100,000 tasks makes 100,000 virtual threads, and they will all try to use a database pool of 10 connections or a mail server that allows 2 sessions.

So virtual threads remove the need for thread-pool sizing but not for limits. Put the limit on the resource: a semaphore, a bounded connection pool, or Spring Framework 7's @ConcurrencyLimit, which is covered in the resilience section.

Bridge: shutdown, what happens to work in flight

On a deploy, Kubernetes sends the old pod a stop signal. Spring closes the application context, and closing the context shuts the executors down. What happens to a task that is running at that moment? We measured, with three tasks of 3 seconds each, and the context closed after 0.3 seconds. The three runs differ only in settings.

run --demo=shutdown (three settings)runs offline
$ run A: defaults
runner done; closing the context now
  task 1 FINISHED
  task 3 FINISHED
  task 2 FINISHED
total wall 7.54 s

$ run B: --spring.lifecycle.timeout-per-shutdown-phase=1s
runner done; closing the context now
  task 3 INTERRUPTED
  task 1 INTERRUPTED
  task 2 INTERRUPTED
total wall 5.77 s

$ run C: B plus await-termination=true, period=10s
runner done; closing the context now
  task 3 FINISHED
  task 2 FINISHED
  task 1 FINISHED
total wall 9.83 s

What you see:

The settings for run C are these two properties.

application.properties · Boot 4.2runs offline
spring.task.execution.shutdown.await-termination=true
spring.task.execution.shutdown.await-termination-period=30s

Why: a graceful shutdown has two clocks. One belongs to the lifecycle (how long the whole context may take to stop). One belongs to the executor (how long it waits for its tasks). Make the executor's period shorter than the lifecycle's, and shorter than Kubernetes' terminationGracePeriodSeconds (30 seconds unless you change it), or the process is killed before the waiting ends. And remember the limit of all this: it protects tasks that are running during a polite stop (we did not test queued ones). It does nothing for a crash.

Bridge: @Async is not durable

The third hidden cost is the hardest to accept. An @Async task is an object in the memory of one process. It exists on a queue inside the executor. If that process stops without finishing, the task is gone, and nothing remembers that it ever existed. A polite shutdown (above) can wait. A crash, an out-of-memory kill, a node failure, or a deploy that exceeds its grace period cannot.

We simulate the worst case with Runtime.halt, which ends the JVM at once with no shutdown hooks, as kill -9 would. Six emails are queued on a single worker (1 second each). The process is killed at 2.5 seconds.

run --demo=lost --demo.executors=single · Boot 4.2runs offline
$ run 1: @Async on a single worker
6 emails queued; the process is killed at t=2.5 s
  email #1 sent
  email #2 sent
*** kill -9 ***

What you see: emails 1 and 2 were sent. Emails 3 to 6 were in the queue when the process died, and no copy of them exists anywhere. After the restart, nothing knows that four customers are waiting for a confirmation.

The cure is to write down what must happen before doing it, in storage that survives a crash. The simplest form is an outbox: a database table of work to do. Your code inserts a row (in the same transaction as the order, so the order and its email request are saved together or not at all). A worker reads pending rows, does the work, and marks each row as sent. The same kill, with an outbox table in a file database:

DemoRunner.java (outbox loop) · Boot 4.2runs offline
for (Integer id : jdbc.sql("select id from outbox where status='PENDING' order by id")
                      .query(Integer.class).list()) {
    MailService.sleep(1000);                              // pretend: send the email
    jdbc.sql("update outbox set status='SENT' where id=?").param(id).update();
    System.out.println("  email #" + id + " sent, row marked SENT");
}
run --demo=outbox (kill at 2.5 s, then restart) · Boot 4.2runs offline
$ run 1: write to the outbox table, send from it
6 emails written to the outbox table as PENDING
  email #1 sent, row marked SENT
  email #2 sent, row marked SENT
*** kill -9 ***

$ run 2: restart the process
restart: pending rows = 4
  email #3 sent, row marked SENT
  email #4 sent, row marked SENT
  email #5 sent, row marked SENT
  email #6 sent, row marked SENT
outbox now: SENT=6 PENDING=0

What you see now: the first process sent emails 1 and 2 and was killed. The second process started, found 4 pending rows, and sent emails 3 to 6. Final state: 6 sent, 0 pending. Nothing was lost.

Why one more thing to know: an outbox gives at-least-once delivery. If a crash comes after the email was sent and before the row was marked, the restart sends it again. The receiving side must tolerate a duplicate, or each message needs an idempotency key. Idempotency is covered in E20, and the outbox pattern in E7. With a message broker such as Kafka, the same idea is built in (E17).

Idiom: use a durable queue for anything that must happen

The problem: a payment confirmation, an invoice, a shipment request or an audit entry is put on an in-memory executor. A deploy, a crash or a full queue loses it, and nobody finds out until a customer complains.

How it works: split "decide that the work is needed" from "do the work". Deciding is written to durable storage (an outbox table, a message broker) in the same transaction as the business change. Doing is a separate worker that reads from that storage and can be restarted, retried and scaled.

  1. Classify the work: "nice to have, can be lost" (cache warm-up, a metrics push) may stay @Async. "Must happen" may not.
  2. Write first: insert the outbox row or publish to the broker inside the transaction.
  3. Worker with retry: take pending work, do it, mark it done. Use an idempotency key so a repeat is harmless.
  4. Watch the backlog: the number of pending rows is a metric. A growing number means the worker is stuck.

Which background tool? The stack table

Choosing a way to run work later
OptionPick it whenCost or catch
@Async on the default executorQuick, best-effort work, small volume.8 threads, unbounded queue, not durable, context is lost.
@Async("name") or CompletableFuture on your own executorYou need isolation, a bounded queue, a result, or composition of several async steps.Still in memory. You own sizing, rejection and shutdown settings.
Message broker (Kafka, RabbitMQ) or an outbox tableWork that must survive restarts, retry, or be spread over several pods.Another system or table, at-least-once delivery, duplicates to handle.
Spring BatchLarge, restartable jobs with chunked reads and writes and a record of progress.Heavier setup; meant for jobs, not single messages.
@Scheduled or a schedulerWork that happens at a time, not in reaction to an event.Runs on every pod unless you add a lock (see scheduling).

Switch up the table when the answer to "what if this task disappears?" changes from "nobody notices" to "a customer notices". Switch down when you have a broker for a workload that is really best-effort and its operational cost is not paying for itself.

A review checklist for any new @Async

The same exercise for background work. Five questions, each answered by a demo above.

  1. Which executor runs it, and is it bounded? The default has eight threads and a queue that never fills. Name an executor for the workload and give it a queue limit.
  2. What happens when it is full? A rejection reaches the caller. Decide whether the caller catches it, runs the task itself, or records it for later.
  3. Where does a failure go? A void method needs a handler that counts and alerts. A method whose result matters returns a future.
  4. Which context does it need? User, request id, tenant: copy them with a TaskDecorator. Pass ids, not entities, and expect a new transaction.
  5. What if the process dies now? If that is a problem, the work belongs in an outbox or a broker, and shutdown settings only help with polite stops.

Notice that none of the five is about making the code faster. That part worked on the first try, in 3 ms. Everything that follows is about the guarantees you gave up in exchange, and about writing them back in on purpose. For how retries, limits and breakers fit around calls that fail, continue with the next section.

06 · Retry, concurrency limits and circuit breakersRetry, Concurrency Limits and Circuit Breakers

A remote call fails for boring reasons: a blip, a restart, a slow server. A retry gives the call another chance, a concurrency limit stops one slow dependency from eating every thread, and a circuit breaker stops calling a dependency that is clearly down. Spring Framework 7 now ships retry and the concurrency limit in the core; Resilience4j adds the circuit breaker. This section runs all three against a fake gateway whose failures we control, so every number below is repeatable.

QuickBite sends every card payment to an outside payment gateway. About 2 percent of the calls came back with HTTP 503 (Service Unavailable), usually for a second or two. The first fix was a hand-written loop: if the call fails, call again, up to five times, with no pause.

That loop caused two incidents. In the first, the charge call had already taken the customer's money when the reply was lost on the way back. The loop saw an error, called again, and charged the card a second time. 31 customers were double-charged before support noticed.

In the second, the gateway went down for 10 minutes. Every request thread waited 30 seconds for a timeout, then retried five times. With 200 request threads in the Tomcat pool, all 200 were stuck inside payment calls within a minute, and the menu pages (which never touch the gateway) stopped answering too. One sick dependency took the whole shop down.

This section fixes both. It answers four questions in order: how to retry safely, how to cap the damage, how to stop calling something that is down, and which timeout comes first. Everything runs on Spring Boot 4.2.0 and Java 25 with the same fake gateway, which fails on command.

The fake gateway used in every demo

The gateway is a plain Spring bean. It counts calls, prints the time of each call, and fails with an IOException ("503 Service Unavailable") for as many calls as we tell it to. A second method, charge, takes the money first and then loses the reply on the first call, which is the double-charge accident in miniature.

Resilience.java · Boot 4.2runs offline
package com.quickbite;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.stereotype.Component;

@Configuration
@EnableResilientMethods
class ResilienceConfig { }

/** A fake payment gateway with scripted, deterministic failures. */
@Component
class FakeGateway {
    volatile long t0 = System.nanoTime();
    final AtomicInteger calls = new AtomicInteger();
    final AtomicInteger charges = new AtomicInteger();          // money actually taken
    final Map<String, String> byKey = new ConcurrentHashMap<>();
    volatile int failFirst = 0;                                  // fail the first N calls
    volatile boolean down = false;

    long ms() { return (System.nanoTime() - t0) / 1_000_000; }

    void reset(int failFirst) { t0 = System.nanoTime(); calls.set(0); charges.set(0); byKey.clear(); this.failFirst = failFirst; down = false; }

    /** Fails with 503 for the first failFirst calls, otherwise returns OK. */
    String authorize(String what) throws IOException {
        int n = calls.incrementAndGet();
        System.out.printf("  call %d at %4d ms (%s)%n", n, ms(), what);
        if (down || n <= failFirst) throw new IOException("503 Service Unavailable");
        return "OK";
    }

    /** Takes the money, then the reply is "lost" on the first call. */
    String charge(String orderId, String idempotencyKey) throws IOException {
        int n = calls.incrementAndGet();
        if (idempotencyKey != null && byKey.containsKey(idempotencyKey)) {
            System.out.printf("  call %d: key %s seen before, returning the old result%n", n, idempotencyKey);
            return byKey.get(idempotencyKey);
        }
        int total = charges.incrementAndGet();
        String receipt = "receipt-" + total;
        if (idempotencyKey != null) byKey.put(idempotencyKey, receipt);
        System.out.printf("  call %d: charged order %s (total charges so far = %d)%n", n, orderId, total);
        if (n == 1) throw new IOException("read timeout after the charge was made");
        return receipt;
    }
}

Two lines matter. @Configuration @EnableResilientMethods switches on the retry and concurrency-limit annotations; without it they are silently ignored, like @Async without @EnableAsync. And reset(n) makes the gateway fail its first n calls, so a demo can say "fail twice, then work" and always get that.

Bridge: Spring Framework 7 @Retryable, one level down

A retry means calling the same operation again after it failed, hoping the cause was temporary. The annotation @Retryable (package org.springframework.resilience.annotation) puts a retry loop around a method. It works exactly like @Cacheable or @Async: Spring wraps the bean in a proxy, and the proxy runs the loop (see 02 · Spring AOP from zero). That means the same rules apply: the call must come from another bean, and a method called through this is not retried.

Before Framework 7 you needed the separate Spring Retry library for this. The core now has its own version in the package org.springframework.core.retry and org.springframework.resilience. The library is still around, and the decision table later in this section says when you might still want it.

Make the invisible visible: what a bare @Retryable does. The gateway is down for good. We print the time of every call.

RetryServices.java (excerpt) · Boot 4.2runs offline
@Service
public class RetryServices {
    private final FakeGateway gw;
    RetryServices(FakeGateway gw) { this.gw = gw; }

    @Retryable                                   // all defaults
    public String defaults() throws IOException { return gw.authorize("defaults"); }
run --demo=retry · Boot 4.2 (first part)runs offline
# measured on the course machine (12 cores); your numbers will differ
--- 1. all defaults, gateway always down ---
  call 1 at   15 ms (defaults)
  call 2 at 1021 ms (defaults)
  call 3 at 2022 ms (defaults)
  call 4 at 3022 ms (defaults)
defaults() -> threw java.io.IOException: 503 Service Unavailable

What you see: four calls, one second apart, and then the caller gets the original IOException. The defaults are therefore 3 retries after the first call, with a fixed delay of 1 second.

Why: maxRetries counts the extra tries, not the total. One first call plus three retries makes four calls, and four calls with three one-second pauses is about three seconds of waiting. When the last retry fails, the proxy rethrows the last exception, so your own catch blocks and exception handlers keep working.

maxRetries is not maxAttempts

If you used Spring Retry, you wrote maxAttempts = 3 and got three calls in total, the first call included. The new annotation counts differently. This is the one change that quietly alters behaviour when you migrate, so look at it side by side.

Spring Retry

The number counts every call, the first one too.

snippet · spring-retry (illustrative)illustrative
@Retryable(maxAttempts = 3)
String pay() { ... }
// call 1, call 2, call 3
// then it gives up

Spring Framework 7

The number counts only the retries.

snippet · Boot 4.2runs offline
@Retryable(maxRetries = 2)
String pay() { ... }
// call 1, retry 1, retry 2
// then it gives up

The shift: to keep three calls in total, write maxRetries = 2, and the default of 3 retries means 4 calls.

The right-hand side is not just a claim. We ran maxRetries = 2 against the always-down gateway, with a 50 ms delay so the output is quick to read.

run --demo=retry · Boot 4.2 (third part)runs offline
--- 3. maxRetries = 2, always down ---
  call 1 at    0 ms (maxRetries=2)
  call 2 at   51 ms (maxRetries=2)
  call 3 at  102 ms (maxRetries=2)
twoRetries() -> threw java.io.IOException: 503 Service Unavailable

Three calls, 51 ms apart. Moving to Framework 7 and keeping your old numbers would therefore have added one extra call to every retry loop. At a gateway that already struggles, that is one more call on every failing request.

Backoff, multiplier, maxDelay and jitter

A fixed pause is a poor way to retry. If the gateway is overloaded, all clients retry at the same second and make it worse. Three attributes fix that.

Here is the configuration we use for the payment call, followed by Figure 22.9, which shows the schedule it produces.

RetryServices.java (excerpt) · Boot 4.2runs offline
@Retryable(maxRetries = 3, delay = 200, multiplier = 2, maxDelay = 1000, jitter = 50)
public String backoff() throws IOException { return gw.authorize("backoff"); }
One @Retryable call that fails three times (nominal times; the bands are the jitter) 0 200 600 1000 1400 milliseconds since the first call call 1 (t = 0) fails wait 200 ms, jitter band 150 to 250 call 2 (about 200) fails wait 400 ms, band 300 to 500 call 3 (about 600) fails wait 800 ms, band 600 to 1000 (maxDelay = 1000 caps it) call 4 (about 1400) the last retry: maxRetries = 3
Fig. 22.9 — Backoff and jitter. The plain bars are the nominal waits (200, 400, 800 ms). The coloured bands are where the jitter can move the end of each wait. The bands widen with every retry, which is what we measured in four runs (below).

Now the real numbers. We ran the call four times against a gateway that fails three times and then works, so each run makes all four calls.

run --demo=jitter · Boot 4.2runs offline
# measured on the course machine (12 cores); your numbers will differ
run 1
  call 1 at   21 ms (backoff)
  call 2 at  255 ms (backoff)
  call 3 at  596 ms (backoff)
  call 4 at 1473 ms (backoff)
backoff() -> OK
run 2
  call 1 at    0 ms (backoff)
  call 2 at  209 ms (backoff)
  call 3 at  693 ms (backoff)
  call 4 at 1642 ms (backoff)
backoff() -> OK
run 3
  call 1 at    0 ms (backoff)
  call 2 at  212 ms (backoff)
  call 3 at  555 ms (backoff)
  call 4 at 1191 ms (backoff)
backoff() -> OK
run 4
  call 1 at    0 ms (backoff)
  call 2 at  238 ms (backoff)
  call 3 at  541 ms (backoff)
  call 4 at 1351 ms (backoff)
backoff() -> OK

What you see: the first gap was 234, 209, 212 and 238 ms. The second was 341, 484, 343 and 303 ms. The third was 877, 949, 636 and 810 ms. The nominal gaps are 200, 400 and 800 ms.

Why: the random part grows with each retry. All 12 gaps stayed inside 150 to 250, 300 to 500 and 600 to 1000 ms respectively, which fits a jitter that is scaled by the multiplier at every step (50, then 100, then 200 ms).

That is our reading of 12 measurements; the Javadoc of @Retryable in your version is the authority. What matters in practice: two clients that fail at the same moment will not retry at the same moment, and the later the retry, the more spread out they are.

includes and excludes: retry only what can recover

Not every exception deserves another try. A timeout or a 503 may succeed next time. An invalid card number will fail exactly the same way every time, and retrying it only wastes the caller's time. The attributes includes and excludes list the exception types to retry and to skip.

RetryServices.java (excerpt) · Boot 4.2runs offline
@Retryable(includes = IOException.class, excludes = IllegalArgumentException.class,
           maxRetries = 3, delay = 50)
public String excluded(String what) throws IOException {
    System.out.println("  call " + gw.calls.incrementAndGet() + " (" + what + ")");
    if (what.equals("bad-card")) throw new IllegalArgumentException("card number is invalid");
    throw new IOException("503");
}
run --demo=retry · Boot 4.2 (last part)runs offline
--- 4. includes IOException, excludes IllegalArgumentException ---
  call 1 (bad-card)
excluded(bad-card) -> threw java.lang.IllegalArgumentException: card number is invalid
  call 1 (timeout)
  call 2 (timeout)
  call 3 (timeout)
  call 4 (timeout)
excluded(timeout) -> threw java.io.IOException: 503

The bad card was tried once and the error went straight back. The 503 was tried four times. Make this the habit: name the exceptions you retry. A bare @Retryable retries every exception, including the bugs.

Where retry sits in the interceptor chain

A method can carry several annotations at once, and each one is a layer of the same proxy. Spring Framework 7 puts the retry layer outside @Transactional and outside @Cacheable, whatever order you configure. That is what you want. Each retry then opens a fresh transaction, instead of reusing a transaction that the first failure already marked "rollback only". Section 03 shows the chain printed from a running app, and the idiom there explains the reason.

Part A measured the full default order on Boot 4.2.0: the retry advisor first, then the exposure interceptor, then caching, then the transaction, then any custom aspect, then your method. Even an aspect marked @Order(HIGHEST_PRECEDENCE) runs inside the retry, once per attempt. We saw the same thing on this machine: a method that failed twice made the logging aspect print three times, because the retry wraps the aspect.

Idiom: retry only idempotent operations, or send an idempotency key

The problem: an idempotent operation gives the same result however often you run it. "Read the price of a biryani" is idempotent. "Charge this card" is not: every run takes money again. A retry cannot tell whether the first call failed before or after the side effect. A timeout means "I do not know".

How it works: the client creates a unique idempotency key for the business action (one key per order, not per call) and sends it with every attempt. The server stores the result under that key. When the same key comes again, the server returns the stored result and does not repeat the action. E20 builds the server side with a database table (idempotency key), and E7 explains the same trick for message consumers.

  1. Safe to retry as is: reads, PUT and DELETE by id, and anything that checks "already done?" first.
  2. Not safe without a key: charges, transfers, "send SMS", "create order".
  3. Generate the key before the first call: one per order. Generating it inside the retried method makes a new key per attempt and defeats the whole idea.

Make the invisible visible: the same retry-annotated charge method twice. The fake gateway takes the money on the first call, then loses the reply. Run one has no key. Run two sends key-o-1001.

RetryServices.java (excerpt) · Boot 4.2runs offline
@Retryable(maxRetries = 3, delay = 50)
public String charge(String order, String key) throws IOException { return gw.charge(order, key); }
run --demo=idempotent · Boot 4.2runs offline
--- retry WITHOUT an idempotency key ---
  call 1: charged order o-1001 (total charges so far = 1)
  call 2: charged order o-1001 (total charges so far = 2)
charge -> receipt-2
money taken: 2 time(s)
--- retry WITH an idempotency key ---
  call 1: charged order o-1001 (total charges so far = 1)
  call 2: key key-o-1001 seen before, returning the old result
charge -> receipt-1
money taken: 1 time(s)

What you see: without a key the card was charged twice (receipt-2) and the customer paid double. With the key the second call was recognised, the stored receipt came back, and the money was taken once.

Why: the retry did exactly what it was told. The bug was that "charge" was retried at all without a way for the server to say "I already did this". The 31 double charges of our incident came from this missing key, not from the retry loop itself.

Bridge: RetryTemplate, a retry you write in code

An annotation retries a whole method. Sometimes you want to retry three lines in the middle of one, or the retry settings are only known at run time (a value from the database, a different policy per customer). For that, Framework 7 has RetryTemplate in the core, and it works without any proxy and without @EnableResilientMethods.

You build a RetryPolicy (how many retries, how long to wait), give it to a template, and pass a lambda to execute. The lambda is the code to retry.

RetryServices.java (excerpt) · Boot 4.2runs offline
public String withTemplate() throws Exception {
    RetryPolicy policy = RetryPolicy.builder().maxRetries(3).delay(Duration.ofMillis(100)).build();
    RetryTemplate template = new RetryTemplate(policy);
    return template.execute(() -> gw.authorize("RetryTemplate"));
}
run --demo=template · Boot 4.2runs offline
# the gateway fails twice, then works
  call 1 at   13 ms (RetryTemplate)
  call 2 at  120 ms (RetryTemplate)
  call 3 at  221 ms (RetryTemplate)
result: OK

Two failures, then success on call 3, about 100 ms apart. Both tools use the same engine, so the settings mean the same thing. When all tries fail, the template reports that the retries were exhausted; the Javadoc of RetryTemplate in your version lists the exact exception type and how the last failure is attached to it.

Pick the annotation when the whole method is the unit to retry, which is most of the time. Pick the template when only part of a method should be retried, or when a self-invocation would bypass the proxy anyway.

Bridge: @ConcurrencyLimit, a door that lets only N callers in

Retries make an overload worse, because they add traffic exactly when the dependency is struggling. A concurrency limit puts an upper bound on how many callers are inside a method at the same moment. The rest wait outside. It is the same idea as a Semaphore (a counter of permits, see E21 on executors), packaged as an annotation.

Think of a restaurant with 10 tables. The 11th group waits at the door. The kitchen is never asked for more than 10 orders at once, and nobody is thrown out.

Idiom: @ConcurrencyLimit to protect a slow dependency

The problem: the payment gateway is contracted for 10 simultaneous requests. QuickBite has 200 request threads, or with virtual threads (see E21) effectively unlimited callers. With no limit, a rush of orders sends 200 requests and the gateway answers many of them with errors.

How it works: the annotation @ConcurrencyLimit(10) on a bean method adds one more layer to the proxy. Each call must get one of 10 permits before it enters the method, and gives it back when the method returns or throws. A caller that finds no permit waits until one is free.

  1. Put it on the method that touches the scarce thing: the gateway client, not the whole service.
  2. Pick the number from the contract or a load test: the limit of the dependency, not of your own machine.
  3. Combine with a timeout on the call: a waiting caller still holds a thread, so waiting forever just moves the pile-up.

Make the invisible visible: 50 callers on virtual threads, each calling a method that takes 100 ms. We track how many are inside at once. One method has the annotation, the other does not.

RetryServices.java (excerpt) · Boot 4.2runs offline
@ConcurrencyLimit(10)
public void limited() { work(); }

public void unlimited() { work(); }

private void work() {
    int now = inFlight.incrementAndGet();               // callers inside right now
    maxInFlight.accumulateAndGet(now, Math::max);       // remember the highest value
    try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    inFlight.decrementAndGet();
}
run --demo=limit · Boot 4.2runs offline
# measured on the course machine (12 cores); your numbers will differ
unlimited 50 callers: max in flight = 50, total 124 ms
limited   50 callers: max in flight = 10, total 519 ms

What you see: without the annotation all 50 callers were inside at once and the whole batch took 124 ms. With it, never more than 10 were inside, and the batch took 519 ms.

Why: 50 callers through 10 permits is five waves, and five waves of 100 ms is about 500 ms. The limit did not reject anyone. It slowed them down so that the dependency saw 10 requests at a time instead of 50. This is the price: a limit trades latency for protection.

Bridge: Resilience4j and the circuit breaker, one level down

Retries help with a blip. They hurt during an outage, because every caller keeps trying a dependency that is down. A circuit breaker notices the failures and stops sending calls for a while. The name comes from the electrical box in your house: when too much current flows, the breaker trips and cuts the line, so the wires do not burn. You fix the fault, then switch it back on.

The software version has three states. Closed is normal: calls go through, and the breaker counts successes and failures. Open means "stop": calls are not made at all, and the caller gets an error or a fallback straight away. Half-open is a careful test: after a wait, the breaker lets a few calls through. If they work, it closes again. If they fail, it opens again.

Spring Framework 7 has no circuit breaker of its own. The usual choice is Resilience4j, a library of small resilience tools. Version 2.4.0 has a Boot 4 starter, resilience4j-spring-boot4, which turns on its annotations and reads its settings from application.yml. The annotations need the AspectJ starter you already have from section 02.

pom.xml (excerpt) · Boot 4.2runs offline
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot4</artifactId>
    <version>2.4.0</version>
</dependency>

The settings are the heart of it, so read them slowly. This is the whole configuration of the breaker named payment.

application.yml · Boot 4.2runs offline
resilience4j:
  circuitbreaker:
    instances:
      payment:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 6
        minimum-number-of-calls: 4
        failure-rate-threshold: 50
        wait-duration-in-open-state: 1s
        permitted-number-of-calls-in-half-open-state: 2
        register-health-indicator: true

The service is short. The annotation names the breaker, and fallbackMethod names a method to call instead when the call fails or the breaker is open. A fallback has the same parameters as the original, plus one extra Throwable at the end. To follow the transitions we also register a listener that prints every state change with its time.

Breaker.java · Boot 4.2runs offline
package com.quickbite;

import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import java.io.IOException;
import org.springframework.stereotype.Service;

@Service
public class Breaker {
    private final FakeGateway gw;
    Breaker(FakeGateway gw, CircuitBreakerRegistry registry) {
        this.gw = gw;
        registry.circuitBreaker("payment").getEventPublisher().onStateTransition(e ->
            System.out.printf("  >>> state %s at %d ms%n", e.getStateTransition(), gw.ms()));
    }

    @io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker(name = "payment", fallbackMethod = "queueForLater")
    public String pay(String order) throws IOException { return gw.authorize("pay " + order); }

    String queueForLater(String order, Throwable why) {
        String kind = why instanceof CallNotPermittedException ? "breaker open, call skipped" : why.getMessage();
        return "QUEUED (" + kind + ")";
    }
}

Make the invisible visible: the gateway is down. We make 7 payments, wait 1.2 seconds (longer than the 1 s open wait) while the gateway recovers, then make 4 more. Each gateway call prints a line, so a skipped call is easy to spot: it has no call N line.

run --demo=breaker · Boot 4.2runs offline
# measured on the course machine (12 cores); your numbers will differ
--- gateway is DOWN ---
  call 1 at   26 ms (pay o-1)
pay #1 -> QUEUED (503 Service Unavailable)
  call 2 at   39 ms (pay o-2)
pay #2 -> QUEUED (503 Service Unavailable)
  call 3 at   41 ms (pay o-3)
pay #3 -> QUEUED (503 Service Unavailable)
  call 4 at   46 ms (pay o-4)
  >>> state State transition from CLOSED to OPEN at 55 ms
pay #4 -> QUEUED (503 Service Unavailable)
pay #5 -> QUEUED (breaker open, call skipped)
pay #6 -> QUEUED (breaker open, call skipped)
pay #7 -> QUEUED (breaker open, call skipped)
--- gateway recovers; waiting 1.2 s (open wait is 1 s) ---
  >>> state State transition from OPEN to HALF_OPEN at 1268 ms
  call 5 at 1269 ms (pay o-8)
pay #8 -> OK
  call 6 at 1271 ms (pay o-9)
  >>> state State transition from HALF_OPEN to CLOSED at 1272 ms
pay #9 -> OK
  call 7 at 1273 ms (pay o-10)
pay #10 -> OK
  call 8 at 1273 ms (pay o-11)
pay #11 -> OK
The three states of the payment breaker and what moves it CLOSED calls go through OPEN calls skipped, fallback HALF_OPEN 2 trial calls allowed failure rate 50% or more in the last 6 calls, and at least 4 calls seen (measured: after call 4) after the 1 s wait, on the next call both trial calls succeed (measured: 1272 ms) trial calls fail The breaker does not wake itself: OPEN becomes HALF_OPEN when a call arrives after the wait.
Fig. 22.10 — The breaker as a state machine, with the numbers of our configuration. In the run above, state changes were logged at 55 ms (CLOSED to OPEN), 1268 ms (OPEN to HALF_OPEN) and 1272 ms (HALF_OPEN to CLOSED).

What you see: payments 1 to 4 each reached the gateway and failed, and the fallback answered "QUEUED". Right after call 4 the breaker went from CLOSED to OPEN. Payments 5, 6 and 7 never reached the gateway: there is no call 5 line before the wait, and the fallback answered "breaker open, call skipped". After the 1.2 s pause, payment 8 triggered OPEN to HALF_OPEN and was the first test call. Payment 9 was the second, and the breaker closed.

Why: at call 4 the window held 4 failed calls, which met the minimum of 4 and gave a failure rate of 100 percent, above 50. While open, the breaker answers by itself in microseconds, so no thread waits and the gateway gets a quiet period to recover. After the wait, it risked 2 test calls, not a flood. Both worked, so it trusted the gateway again.

Idiom: a circuit breaker with a cheap, honest fallback

The problem: a breaker alone only changes the error. Instead of a slow failure, the caller gets a fast failure. For a customer who is paying, that is still a failed order unless the fallback does something useful.

How it works: the fallback method runs in place of the real call when the call fails or the breaker is open. It gets the original arguments and the exception, so it can tell a real failure from "call skipped" (CallNotPermittedException). A good fallback is local and fast.

  1. Choose what "degraded" means for this call: queue the payment for a later retry (our choice), show a cached price, or return an empty recommendation list.
  2. Keep it local: a fallback that calls another remote service has its own failure modes and can fail the same way. A database insert into a "pending payments" table is fine.
  3. Be honest: tell the customer "we will confirm your payment shortly". Never answer "paid" from a fallback.
  4. Watch the state: alert when a breaker opens. An open breaker with a quiet fallback hides an outage.

The code above is that idiom. The fallback queueForLater returns a QUEUED marker, which a real service would write to a table that a scheduled job (the next section) drains.

Seeing the breaker from outside: Actuator

With register-health-indicator: true and the endpoint circuitbreakers exposed, you can look at every breaker over HTTP, which is how a dashboard or an alert reads them. We made 5 failing payments in a web-enabled run, then called the two endpoints. The JSON is reformatted for reading, and the one noisy log line is left out.

curl /actuator/circuitbreakers · Boot 4.2runs offline
{
  "circuitBreakers": {
    "payment": {
      "bufferedCalls": 4,
      "failedCalls": 4,
      "failureRate": "100.0%",
      "failureRateThreshold": "50.0%",
      "notPermittedCalls": 1,
      "slowCallRate": "0.0%",
      "slowCallRateThreshold": "100.0%",
      "slowCalls": 0,
      "slowFailedCalls": 0,
      "state": "OPEN"
    }
  }
}
curl /actuator/health/circuitBreakers · Boot 4.2runs offline
{
  "details": {
    "payment": {
      "details": {
        "failureRate": "100.0%",
        "failureRateThreshold": "50.0%",
        "slowCallRate": "0.0%",
        "slowCallRateThreshold": "100.0%",
        "bufferedCalls": 4,
        "slowCalls": 0,
        "slowFailedCalls": 0,
        "failedCalls": 4,
        "notPermittedCalls": 1,
        "state": "OPEN"
      },
      "status": "CIRCUIT_OPEN"
    }
  },
  "status": "UNKNOWN"
}

What you see: the state is OPEN, 4 calls failed (100 percent), and 1 call was refused without being tried (notPermittedCalls). The health group reports the breaker's own status as CIRCUIT_OPEN, but the overall status is UNKNOWN.

Why: Boot's health aggregation only knows UP, DOWN, OUT_OF_SERVICE and UNKNOWN, so a custom status such as CIRCUIT_OPEN maps to UNKNOWN. The HTTP status stayed 200, so a Kubernetes probe does not restart the pod because one dependency is down, which is usually what you want. If you want the opposite, map the status with management.endpoint.health.status.order (check the reference for your version).

The other Resilience4j annotations, briefly

The same starter gives four more annotations. We did not run them, because each needs its own page of settings; the point here is to know what exists and which problem each solves. Their names, and the exact attributes, are in the Resilience4j documentation for version 2.4.

AnnotationWhat it doesUse it when
@CircuitBreakerStops calls after too many failures, with a fallbackA dependency can be down for minutes
@RateLimiterAllows at most N calls per time period; extra callers wait a little or are refusedThe other side has a quota, such as 100 calls per second
@BulkheadLimits concurrent calls, with a short or zero wait; can also use a separate thread poolYou want "refuse at once" instead of the queueing of @ConcurrencyLimit
@TimeLimiterCancels an asynchronous call (one that returns a CompletableFuture) after a timeThe client library has no timeout setting of its own
@RetryThe library's own retryYou need its metrics and event stream and already use Resilience4j

When you combine several on one method, the order of their layers matters just as it does for the Spring annotations in section 03. The Resilience4j documentation lists a default order (retry outermost, then circuit breaker, rate limiter, time limiter and bulkhead innermost) and a setting to change it. Read that page before stacking more than two.

Which tool when

You now have four places where a retry or a breaker can live. The choice is a stack decision, so here it is with the usual three columns.

OptionPick it whenCost or catch
Spring Framework 7 @Retryable, @ConcurrencyLimit, RetryTemplateYou want retry and a concurrency cap with no extra library. Most services start here.No circuit breaker, rate limiter or built-in metrics. The retry counts differently from Spring Retry.
Spring Retry (the older library)You have a large codebase on maxAttempts and @Recover and no reason to touch it.Its features moved into the core in Framework 7, and the project is in maintenance mode (check the project page for the current status). New code should not start here.
Resilience4j 2.4You need a circuit breaker, a rate limit, a bulkhead, or per-dependency metrics and events.One more dependency and a page of YAML. State is per JVM: six pods have six independent breakers.
Retries and breaking in the platform (service mesh, ingress, API gateway)Many services in different languages need the same policy, and you run Kubernetes (see E10).The platform does not know your business: it cannot send an idempotency key or choose a fallback. Retries in the mesh multiply with retries in the app (3 times 3 is 9 calls).

A good default for QuickBite: Framework 7 @Retryable with includes for the transient errors, an idempotency key on the charge, @ConcurrencyLimit on the client, and one Resilience4j breaker around the gateway. Decide in one place whether the mesh also retries, and turn one of the two layers off.

Timeouts first

Everything above assumes a failing call comes back as an error. A call that never comes back is worse. If the gateway accepts the connection and then says nothing, a retry never starts, a breaker never counts a failure, and the thread waits forever (or until a 30-second default). That was our second incident. The rule is simple: every remote call gets a timeout before it gets a retry.

There are two timeouts. The connect timeout limits how long to wait for the connection to be set up. The read timeout limits how long to wait for the reply once connected. In Boot 4 the HTTP client settings are properties, and they apply to every auto-configured RestClient.Builder. (RestClient is the modern HTTP client that replaces RestTemplate, see section 11.)

application.properties (excerpt) · Boot 4.2runs offline
spring.http.clients.connect-timeout=300ms
spring.http.clients.read-timeout=500ms

Make the invisible visible: a tiny local HTTP server that waits 3 seconds before answering, and a RestClient built from the auto-configured builder. We time the failure.

Runner.java (excerpt) · Boot 4.2runs offline
    static void timeout(RestClient.Builder builder) throws Exception {
        HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        slow.createContext("/pay", ex -> {
            try { Thread.sleep(3000); } catch (InterruptedException e) { }
            byte[] ok = "OK".getBytes();
            try { ex.sendResponseHeaders(200, ok.length); ex.getResponseBody().write(ok); } catch (Exception e) { }
            ex.close();
        });
        slow.setExecutor(Executors.newCachedThreadPool());
        slow.start();
        String url = "http://127.0.0.1:" + slow.getAddress().getPort() + "/pay";
        RestClient client = builder.build();
        long t0 = System.nanoTime();
        try { System.out.println(client.get().uri(url).retrieve().body(String.class)); }
        catch (Exception e) {
            System.out.printf("after %d ms: %s: %s%n", (System.nanoTime() - t0) / 1_000_000, e.getClass().getSimpleName(), e.getMessage());
            Throwable root = e; while (root.getCause() != null) root = root.getCause();
            System.out.println("root cause: " + root.getClass().getName());
        }
        slow.stop(0);
    }
run --demo=timeout · Boot 4.2runs offline
# measured on the course machine (12 cores); your numbers will differ
after 590 ms: ResourceAccessException: I/O error on GET request for "http://127.0.0.1:37941/pay": Request cancelled
root cause: java.net.http.HttpTimeoutException

What you see: the call gave up after 590 ms, not 3 seconds, with a ResourceAccessException whose root cause is Java's HttpTimeoutException.

Why: the 500 ms read timeout fired while the server was still sleeping. Now the failure is an exception like any other, so @Retryable can retry it, the breaker can count it, and the thread is free after half a second. Choose the numbers from the dependency's real speed: a little above its normal 99th percentile, not the 30 seconds nobody remembers setting.

07 · @Scheduled, events, method security, validation and metrics annotations@Scheduled, Events, Method Security, Validation and Metrics Annotations

This section covers the annotations that sit on a method and quietly change when, where and whether it runs. @Scheduled runs it on a timer, @TransactionalEventListener runs it after a commit, @PreAuthorize and @Validated refuse bad callers and bad input, @Observed and @Timed measure it, and @Lazy and @Profile decide whether the bean exists at all. Each one is a layer of the proxy you met in section 02, and each has one trap that this section runs and shows.

QuickBite generates customer invoices every night at 02:00. The job was a method with @Scheduled(cron = "0 0 2 * * *"), and it worked for a year on one server. Then the service moved to Kubernetes with 6 pods. At 02:00 all 6 pods woke up, each generated the same invoices, and every customer received 6 emails and 6 invoices.

The same week, a second job, a report that was meant to start every 60 seconds with fixedRate = 60000, started taking 90 seconds on a heavy day. Runs piled up behind each other, and an unrelated job, the payment-queue drain, did not start for several minutes. Nobody had configured how many threads the scheduler has, so nobody knew it had exactly one.

This section reproduces both problems in miniature, fixes them, and then walks through five more annotations that usually go wrong at 02:00 or in production only. Each demo is a small Spring Boot 4.2 project in code/e22-spring-in-depth/C/scheduling; the outputs are pasted from real runs.

Bridge: @Scheduled, one level down

A scheduled task is a method that Spring calls by itself, on a timer, with nobody calling it. You switch it on with @EnableScheduling on a configuration class. Spring then looks for @Scheduled methods on every bean (the same bean post-processor idea as @Async and @Cacheable) and registers each one with a task scheduler: an object that holds a small pool of threads and a clock, and starts tasks when they are due.

There are three ways to say "when", and they differ in a way that matters the moment the task is slow.

A fourth attribute, initialDelay, waits before the very first run, which is useful so the job does not run while the application is still starting. Now the test that matters: what happens when the task takes longer than its period? We use a task that sleeps 1500 ms (or 3000 ms for cron) and prints when it starts and ends.

Make the invisible visible: three jobs with a slow body, run one at a time. The first is fixedRate.

SchedDemos.java (excerpt) · Boot 4.2runs offline
@Configuration
@EnableScheduling
class SchedConfig { }

@Component @ConditionalOnProperty(name = "demo", havingValue = "rate")
class RateJob {
    @Scheduled(fixedRate = 1000)                        // start a run every 1 s
    void invoices() { Util.log("start invoices"); Util.sleep(1500); Util.log("  end invoices (took 1500)"); }
}
run --demo=rate --seconds=7 · Boot 4.2runs offline
# measured on the course machine (12 cores); your numbers will differ
    0 ms [scheduling-1] start invoices
 1501 ms [scheduling-1]   end invoices (took 1500)
 1504 ms [scheduling-1] start invoices
 3004 ms [scheduling-1]   end invoices (took 1500)
 3005 ms [scheduling-1] start invoices
 4505 ms [scheduling-1]   end invoices (took 1500)

What you see: the job was meant to start every second, but a run takes 1.5 seconds. Each new run starts as soon as the previous one ends (at 1504, 3005 and 4507 ms). Runs never overlap, and they never get a pause between them.

Why: there is only one scheduler thread (the name is scheduling-1 every time). At 1000 ms the run is due, but the only thread is busy, so the run waits for it. When the thread is free, the run starts at once, late. Spring does not start a second copy in parallel, and it does not invent a pile of missed runs; it just stays behind schedule.

Now the same body with fixedDelay, plus an initialDelay of 500 ms.

SchedDemos.java (excerpt) · Boot 4.2runs offline
@Scheduled(fixedDelay = 1000, initialDelay = 500)   // wait 1 s AFTER each run ends
void invoices() { Util.log("start invoices"); Util.sleep(1500); Util.log("  end invoices (took 1500)"); }
run --demo=delay --seconds=8 · Boot 4.2runs offline
    0 ms [scheduling-1] start invoices
 1502 ms [scheduling-1]   end invoices (took 1500)
 2510 ms [scheduling-1] start invoices
 4011 ms [scheduling-1]   end invoices (took 1500)
 5013 ms [scheduling-1] start invoices
 6516 ms [scheduling-1]   end invoices (took 1500)

Every run ends, then there is a pause of one second (1502 to 2510, 4011 to 5013), then the next starts. The gap is a promise you can rely on: the job never starts right on the heels of itself. The first run printed 0 ms because our log clock starts at the first message, not because the 500 ms was ignored.

Last, cron, with a body that takes 3 seconds and a cron that fires every second second.

SchedDemos.java (excerpt) · Boot 4.2runs offline
@Scheduled(cron = "*/2 * * * * *", zone = "Asia/Kolkata")   // every 2nd second
void invoices() { Util.log("start invoices"); Util.sleep(3000); Util.log("  end invoices (took 3000)"); }
run --demo=cron --seconds=9 · Boot 4.2runs offline
    0 ms [scheduling-1] start invoices
 3003 ms [scheduling-1]   end invoices (took 3000)
 3992 ms [scheduling-1] start invoices
 6993 ms [scheduling-1]   end invoices (took 3000)
 7990 ms [scheduling-1] start invoices
10991 ms [scheduling-1]   end invoices (took 3000)

The first run started on an even second, and ran for 3 seconds. The cron expression says an even second again at +2, but the thread was busy, and the next start was at 3992 ms, which is the next even second after the run ended (+4 s). The ticks at +2, +6 and +10 s were skipped, not queued. A cron job never catches up.

The same slow task under three schedules (one scheduler thread) fixedRate = 1 s task takes 1.5 s fixedDelay = 1 s task takes 1.5 s cron every 2 s task takes 3 s Dashed line = a planned start. Red line = a planned start that was skipped because the thread was busy. 0 s 2 s 4 s 6 s 8 s 10 s
Fig. 22.11 — Start and end of every run, taken from the three runs above. fixedRate stays behind and runs back to back. fixedDelay keeps a 1 s pause after each run. cron skips the ticks that fall inside a run and waits for the next one.

Idiom: fixedDelay for jobs that must not pile up

The problem: a job that is sometimes slower than its period falls behind. With fixedRate it runs back to back and never rests, so a 90-second run of a 60-second job keeps the thread busy for good. And if more than one thread is available, it can even run twice at the same time.

How it works: fixedDelay measures from the end of a run, so the next start is always delay after the last finish. There is by definition no overlap with itself, and the system gets a rest between runs.

  1. Is the job a periodic "drain" or "sync"? Draining a queue, syncing a table, polling an inbox: use fixedDelay.
  2. Must it start at a clock time? Use cron with a zone, and make sure it can survive being skipped or run twice.
  3. Must it keep a steady beat, like a heartbeat or a metric sample? Only then use fixedRate, and keep the body well under the period.

We just saw the three schedules with one scheduler thread. The next question is what happens when there are two different jobs, which is our second incident.

One scheduler thread: two jobs block each other

Make the invisible visible: a slow report that takes 3 seconds, and a heartbeat that prints one line. Both are fixedRate = 1000.

SchedDemos.java (excerpt) · Boot 4.2runs offline
@Component @ConditionalOnProperty(name = "demo", havingValue = "twojobs")
class TwoJobs {
    @Scheduled(fixedRate = 1000) void slowReport() {
        Util.log("slowReport start (virtual=" + Thread.currentThread().isVirtual() + ")");
        Util.sleep(3000);
        Util.log("slowReport end");
    }
    @Scheduled(fixedRate = 1000) void heartbeat() { Util.log("heartbeat"); }
}
run --demo=twojobs --seconds=7 · Boot 4.2 (default: 1 thread)runs offline
    0 ms [scheduling-1] heartbeat
    5 ms [scheduling-1] slowReport start (virtual=false)
 3006 ms [scheduling-1] slowReport end
 3011 ms [scheduling-1] heartbeat
 3016 ms [scheduling-1] slowReport start (virtual=false)
 6018 ms [scheduling-1] slowReport end
 6020 ms [scheduling-1] heartbeat
 6022 ms [scheduling-1] slowReport start (virtual=false)

What you see: the heartbeat should print every second. It printed at 0 ms, then not until 3011 ms, then 6020 ms. During the three seconds of the report, nothing else ran at all.

Why: Spring's default task scheduler has a pool size of 1. All @Scheduled methods of the whole application share that one thread. A slow job does not only delay itself, it delays every other job, including ones that have nothing to do with it. This is how the payment-queue drain stopped.

The setting is spring.task.scheduling.pool.size. Here it is set to 2, for the same two jobs.

run --demo=twojobs --seconds=5 --spring.task.scheduling.pool.size=2 · Boot 4.2runs offline
    0 ms [scheduling-2] slowReport start (virtual=false)
    1 ms [scheduling-1] heartbeat
  976 ms [scheduling-1] heartbeat
 1975 ms [scheduling-1] heartbeat
 2975 ms [scheduling-1] heartbeat
 3001 ms [scheduling-2] slowReport end
 3002 ms [scheduling-2] slowReport start (virtual=false)
 3975 ms [scheduling-1] heartbeat
 4978 ms [scheduling-1] heartbeat
 6003 ms [scheduling-2] slowReport end

Now the heartbeat prints every second, on scheduling-1, and the report runs on scheduling-2. Each job has a thread. Size the pool by counting the jobs that can overlap, plus one. If you have 8 scheduled methods, a pool of 2 is still easy to exhaust, and the answer is not a huge pool but short tasks: a scheduled method should hand heavy work to an executor (see 05 · @Async) and return.

What changes with virtual threads

Since Spring Boot 3.2, the property spring.threads.virtual.enabled=true switches many things to virtual threads (cheap threads managed by the JVM, see E21), including the scheduler. We tried both annotations.

run --demo=twojobs --seconds=5 --spring.threads.virtual.enabled=true · Boot 4.2runs offline
    0 ms [scheduling-2] heartbeat
    0 ms [scheduling-3] slowReport start (virtual=true)
  967 ms [scheduling-4] heartbeat
  974 ms [scheduling-5] slowReport start (virtual=true)
 1965 ms [scheduling-6] heartbeat
 1974 ms [scheduling-7] slowReport start (virtual=true)
 2971 ms [scheduling-8] heartbeat
 2974 ms [scheduling-9] slowReport start (virtual=true)
 3009 ms [scheduling-3] slowReport end
 3965 ms [scheduling-10] heartbeat
 3974 ms [scheduling-11] slowReport start (virtual=true)
 3976 ms [scheduling-5] slowReport end

The two jobs no longer block each other: the heartbeat prints every second. But look at slowReport: it started at 0, 974, 1974 and 2974 ms. Three copies of the same job are running at the same time, on different virtual threads (scheduling-3, -5, -7, -9). Each started on its schedule and none waited for the earlier one. A fixedRate job that is slow can now overlap with itself.

Next, the same experiment with fixedRate alone and with fixedDelay alone, both with virtual threads on.

run --demo=rate --seconds=5 --spring.threads.virtual.enabled=true · Boot 4.2runs offline
    0 ms [scheduling-2] start invoices
  977 ms [scheduling-3] start invoices
 1501 ms [scheduling-2]   end invoices (took 1500)
 1975 ms [scheduling-4] start invoices
 2478 ms [scheduling-3]   end invoices (took 1500)
 2976 ms [scheduling-5] start invoices
 3476 ms [scheduling-4]   end invoices (took 1500)
 3975 ms [scheduling-6] start invoices
 4477 ms [scheduling-5]   end invoices (took 1500)
 4976 ms [scheduling-7] start invoices
run --demo=delay --seconds=7 --spring.threads.virtual.enabled=true · Boot 4.2runs offline
    0 ms [scheduling-1] start invoices
 1502 ms [scheduling-1]   end invoices (took 1500)
 2505 ms [scheduling-1] start invoices
 4006 ms [scheduling-1]   end invoices (took 1500)
 5007 ms [scheduling-1] start invoices
 6509 ms [scheduling-1]   end invoices (took 1500)

With fixedRate the runs overlap (starts at 0, 977 and 1975 ms while the first is still running until 1501). With fixedDelay the runs stay one after the other (0, 2505, 5007 ms), because the next run is only scheduled when the last one is done. So the idiom matters more with virtual threads, not less.

Bridge: running once across six pods, with ShedLock

The first incident is a different problem. @Scheduled is a feature of one JVM. It knows nothing about the other 5 pods, so every pod runs the job. The tool for this is ShedLock, a small library that uses a shared place, usually a database table, as a lock. Before the job body runs, the pod tries to write a row "I hold the lock named nightlyInvoice until 02:00:30". If the row is already held by someone else, the pod skips the run silently.

ShedLock does not schedule anything. @Scheduled still decides when every pod wakes up. ShedLock decides which one of them is allowed to do the work.

You need three pieces. First, a lock table that you create yourself (Flyway or schema.sql). Second, a LockProvider bean that knows how to talk to that table, and @EnableSchedulerLock to switch the aspect on. Third, the annotation @SchedulerLock on each job.

schema.sql · Boot 4.2runs offline
CREATE TABLE IF NOT EXISTS shedlock (
  name VARCHAR(64) NOT NULL PRIMARY KEY,
  lock_until TIMESTAMP(3) NOT NULL,
  locked_at TIMESTAMP(3) NOT NULL,
  locked_by VARCHAR(255) NOT NULL);
ShedLockDemo.java · Boot 4.2runs offline
package com.quickbite;

import javax.sql.DataSource;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Configuration
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
@ConditionalOnProperty(name = "demo", havingValue = "shedlock")
class ShedLockConfig {
    @Bean LockProvider lockProvider(DataSource ds) {
        return new JdbcTemplateLockProvider(JdbcTemplateLockProvider.Configuration.builder()
                .withJdbcTemplate(new JdbcTemplate(ds)).usingDbTime().build());
    }
}

@Component @ConditionalOnProperty(name = "demo", havingValue = "shedlock")
class InvoiceJob {
    @Value("${instance.id}") String me;

    @Scheduled(cron = "*/3 * * * * *")
    void unsafe() { System.out.printf("%s  %-5s UNSAFE invoices generated%n", java.time.LocalTime.now().withNano(0), me); }

    @Scheduled(cron = "*/3 * * * * *")
    @SchedulerLock(name = "nightlyInvoice", lockAtMostFor = "PT10S", lockAtLeastFor = "PT2S")
    void safe() { System.out.printf("%s  %-5s SAFE   invoices generated%n", java.time.LocalTime.now().withNano(0), me); }
}

Read the attributes of @SchedulerLock. The name is the row in the table, so it must be unique per job and identical on every pod. lockAtMostFor is the safety net: if the pod dies in the middle of the job and never releases the lock, the lock expires after 10 seconds anyway.

It must be longer than the job's real run time, or a second pod can start while the first is still working. lockAtLeastFor is the opposite protection: even if the job finishes in 5 ms, the lock is held for 2 seconds, so a pod whose clock is a little behind does not run the same tick again. usingDbTime() makes the database clock the single clock for all pods, so clock differences between pods stop mattering.

To see it work, we need two pods. To keep one small machine light, we run two Spring contexts in one JVM, and that is what App.main does: it starts one application context with instance.id=pod-A, then another with pod-B, and both use the same H2 database file (jdbc:h2:file:./target/shedlockdb).

Two contexts are two separate sets of beans with two schedulers and two connection pools, so for ShedLock this is equivalent to two pods, except that the clocks are the same. Each instance has two jobs on the same cron, every 3 seconds. The UNSAFE job has no lock, the SAFE job has.

App.java (excerpt) · Boot 4.2runs offline
String db = "--spring.datasource.url=jdbc:h2:file:./target/shedlockdb;AUTO_SERVER=TRUE";
ConfigurableApplicationContext a = new SpringApplicationBuilder(App.class)
        .run(args[0], "--instance.id=pod-A", db);
Thread.sleep(700);
ConfigurableApplicationContext b = new SpringApplicationBuilder(App.class)
        .run(args[0], "--instance.id=pod-B", db);
Thread.sleep(10000);                                  // let 4 ticks happen
b.close(); a.close();
run --demo=shedlock · Boot 4.2runs offline
# time is the wall clock; a tick is every 3 seconds
00:42:33  pod-A SAFE   invoices generated
00:42:33  pod-A UNSAFE invoices generated
00:42:33  pod-B UNSAFE invoices generated
00:42:36  pod-B SAFE   invoices generated
00:42:36  pod-A UNSAFE invoices generated
00:42:36  pod-B UNSAFE invoices generated
00:42:39  pod-B UNSAFE invoices generated
00:42:39  pod-A SAFE   invoices generated
00:42:39  pod-A UNSAFE invoices generated
00:42:42  pod-A UNSAFE invoices generated
00:42:42  pod-B UNSAFE invoices generated
00:42:42  pod-B SAFE   invoices generated

What you see: at every one of the four ticks (:33, :36, :39, :42) both pods printed UNSAFE, so the unprotected job ran twice per tick, 8 times in total. The SAFE job ran exactly once per tick, 4 times in total, and the winner changed: A, B, A, B.

Why: at each tick both pods tried to insert or update the row nightlyInvoice in the same database table, inside one atomic statement. The database let one of them in and told the other that the lock was taken. The loser did not wait or retry. It skipped that tick. This happens in the database, so it does not matter whether the two pods are in the same JVM, on the same machine or in different data centres, as long as they share the database.

Idiom: ShedLock, one execution per tick across all instances

The problem: every instance of a scaled-out service runs every @Scheduled method. For a nightly invoice job, that means six times the invoices.

How it works: a shared lock table, one row per job name. A pod takes the lock by updating the row when the lock has expired. If the update changes no row, the lock is taken and the job is skipped.

  1. Create the table and a LockProvider bean pointing at your database (or Redis, or another store ShedLock supports).
  2. Add @EnableSchedulerLock and give every job @SchedulerLock with a name and both time limits.
  3. Make the body idempotent anyway. The lock removes duplicates in the normal case. A crash after half the work, or a lockAtMostFor that is too short, can still run a job twice.

ShedLock is the lightest answer, not the only one. Here are the others, in the stack format.

OptionPick it whenCost or catch
ShedLock (@Scheduled plus a lock row)A few periodic jobs inside a scaled-out service that has a database or Redis.All pods wake up and compete. No job history, no retry, no sharding of work. You must size lockAtMostFor.
Kubernetes CronJob (see E10)The job is a separate batch of work with its own resources, logs and failure handling.A separate deployable and image. Cluster-specific. Overlap and missed-run policy are yours to set (concurrencyPolicy).
Quartz in cluster modeMany jobs, dynamic schedules, misfire rules, job history, schedules changed at run time.Its own tables and configuration, a heavier model. More than you need for "run at 02:00".
Leader election (a Kubernetes lease, or Spring Integration)You want exactly one active pod for a whole set of leader-only duties, not per-job locks.You must handle the leader dying and the handover time, and test it.

Bridge: application events, one level down

An application event is a message that one bean publishes inside the application, and any number of other beans can listen. The publisher does not know who listens. This keeps OrderService from knowing about e-mail, SMS, loyalty points and analytics: it says "an order was placed" and moves on.

The pieces are small. An event is any plain object (a record is perfect). You publish it with ApplicationEventPublisher.publishEvent(...). A listener is a method with @EventListener whose parameter type is the event. By default, publishing is synchronous: publishEvent calls every listener on the same thread, one after another, and only returns when they are all done. That means the listeners run inside the publisher's transaction.

That last sentence is the source of a classic bug. QuickBite's OrderService.place saves the order and publishes OrderPlaced. A plain listener sent the confirmation e-mail. Then a payment check failed after the publish, the transaction rolled back, the order never existed, and the customer still got an e-mail saying "Order o-2 confirmed". We reproduce exactly this.

Events.java (excerpt) · Boot 4.2runs offline
record OrderPlaced(String orderId) { }

@Service
class OrderService {
    // jdbc and events are injected through the constructor
    @Transactional
    public void place(String id, boolean fail) {
        jdbc.update("INSERT INTO orders(id, status) VALUES (?, 'NEW')", id);
        System.out.println("  [service] row inserted, publishing OrderPlaced(" + id + ")");
        events.publishEvent(new OrderPlaced(id));
        System.out.println("  [service] publishEvent returned");
        if (fail) throw new IllegalStateException("payment declined");
    }
}

Now the listeners. The first is a plain @EventListener. The others use @TransactionalEventListener, which waits for a phase of the transaction before it runs. The phase is the attribute phase, and the default is AFTER_COMMIT.

Events.java (excerpt) · Boot 4.2runs offline
@EventListener
void plain(OrderPlaced e) {
    System.out.println("  [@EventListener] on " + Thread.currentThread().getName()
            + ", tx active = " + TransactionSynchronizationManager.isActualTransactionActive()
            + " -> SENDING EMAIL for " + e.orderId());
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void afterCommit(OrderPlaced e) {
    System.out.println("  [AFTER_COMMIT]   -> SENDING EMAIL for " + e.orderId());
    // ... audit writes, shown further down
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
void afterRollback(OrderPlaced e) {
    System.out.println("  [AFTER_ROLLBACK] -> cleaning up for " + e.orderId());
}

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
void fallback(OrderPlaced e) {
    System.out.println("  [fallbackExecution=true] ran for " + e.orderId()
            + " (tx active = " + TransactionSynchronizationManager.isActualTransactionActive() + ")");
}

Make the invisible visible: three cases. Case 1: the order commits. Case 2: place throws after publishing, so the transaction rolls back. Case 3: the event is published with no transaction at all. After cases 1 and 2 we also print what is in the database. The lines about auditing come from code we look at in a moment.

run --demo=events · Boot 4.2runs offline
--- 1. commit ---
  [service] row inserted, publishing OrderPlaced(o-1)
  [@EventListener] on main, tx active = true -> SENDING EMAIL for o-1
  [service] publishEvent returned
  [fallbackExecution=true] ran for o-1 (tx active = true)
  [AFTER_COMMIT]   -> SENDING EMAIL for o-1
  JPA write without a new transaction FAILED: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
  orders=1 jdbc-audit=[emailed o-1, emailed-new-tx o-1] jpa-audit=[jpa-new-tx o-1]
--- 2. rollback ---
  [service] row inserted, publishing OrderPlaced(o-2)
  [@EventListener] on main, tx active = true -> SENDING EMAIL for o-2
  [service] publishEvent returned
  [AFTER_ROLLBACK] -> cleaning up for o-2
  caught: payment declined
  orders=0 jdbc-audit=[] jpa-audit=[]
--- 3. no transaction at all ---
  [fallbackExecution=true] ran for o-3 (tx active = false)
  [@EventListener] on main, tx active = false -> SENDING EMAIL for o-3

What you see: in case 2 the plain @EventListener "sent the e-mail" for o-2, and then the transaction rolled back and the database has 0 orders. The e-mail was sent for an order that does not exist. In case 1 the plain listener also ran inside the transaction (tx active = true), before publishEvent returned, and before the commit. The AFTER_COMMIT listener ran only in case 1, and the AFTER_ROLLBACK listener only in case 2.

Why: a plain listener is just a method call made from inside publishEvent. It runs at that moment, in that transaction, with no idea what comes later. A transactional listener is different: Spring does not call it. It registers a callback with the transaction, and calls it when the chosen phase arrives. If the phase never arrives (no commit), the listener never runs. Figure 22.12 shows the phases.

plain @EventListener runs NOW inside the transaction BEGIN INSERT row orders table publishEvent OrderPlaced COMMIT AFTER_COMMIT send the email if the method then throws exception payment declined ROLLBACK AFTER_ROLLBACK clean up, no email No transaction at all: an AFTER_COMMIT listener is skipped, unless fallbackExecution = true (case 3 above).
Fig. 22.12 — The phases of one transaction. A plain listener runs inside publishEvent, before anyone knows how the transaction ends. A transactional listener waits for its phase: AFTER_COMMIT only on the green path, AFTER_ROLLBACK only on the red one. BEFORE_COMMIT and AFTER_COMPLETION (either outcome) also exist.

Case 3 shows the other edge. With no transaction, the plain listener ran at once. The AFTER_COMMIT listener never ran, because there was never a commit. The listener with fallbackExecution = true ran (tx active = false). So @TransactionalEventListener without that flag is silent whenever the publisher forgot @Transactional. That is a common reason for "my listener does not fire".

Idiom: @TransactionalEventListener(AFTER_COMMIT) for side effects

The problem: side effects that cannot be undone (e-mail, SMS, a message to Kafka, a webhook) must only happen when the data really exists. A plain listener fires inside the transaction, before the outcome is known, and so tells the world about things that roll back.

How it works: mark the listener @TransactionalEventListener. Spring defers it until the transaction commits. If the transaction rolls back, the listener is dropped.

  1. Publish inside the transaction (inside the @Transactional method), so the listener can be tied to it.
  2. Listen with the default AFTER_COMMIT for irreversible side effects. Use AFTER_ROLLBACK for cleanup, BEFORE_COMMIT only for work that must succeed together with the data.
  3. Keep database writes out of it, or give them a new transaction (next trap).

The trap. In the AFTER_COMMIT phase the transaction is finished, but its resources are still attached to the thread. Spring's documentation warns that data access done in that moment still joins the old transaction and is not committed. We tried both a JDBC write and a JPA write, each once plainly and once in a method marked @Transactional(propagation = REQUIRES_NEW).

Events.java (excerpt) · Boot 4.2runs offline
audit.plain("emailed " + e.orderId());          // JDBC write in the finished transaction
audit.newTx("emailed-new-tx " + e.orderId());   // JDBC write in REQUIRES_NEW
try { audit.jpaPlain("jpa-plain " + e.orderId()); }   // JPA write in the finished transaction
catch (Exception ex) { System.out.println("  JPA write without a new transaction FAILED: " + ex.getMessage()); }
audit.jpaNewTx("jpa-new-tx " + e.orderId());    // JPA write in REQUIRES_NEW

The result is in the lines of case 1 above: jdbc-audit=[emailed o-1, emailed-new-tx o-1] and jpa-audit=[jpa-new-tx o-1]. The JPA write without a new transaction did not save: it failed with TransactionRequiredException ("No EntityManager with actual transaction available"). Our try/catch printed it. Without the try/catch the framework only logged an ERROR line (TransactionSynchronization.afterCompletion threw exception) and the caller never saw it: the order was committed, and an audit entry quietly went missing.

The plain JDBC write happened to be saved. We believe that is because the connection returned to auto-commit mode when the transaction cleaned up, but that is an accident of the driver, so do not rely on it. The rule is the same for both: a write from an AFTER_COMMIT listener gets its own REQUIRES_NEW transaction.

There is one more way to run a listener: on another thread. Add @Async to the listener and Spring hands it to the task executor, the same executor as in section 05. The publisher no longer waits for it.

run --demo=events-async · Boot 4.2runs offline
  caller thread: main
  publishEvent returned to the caller
  [@Async @EventListener] on task-1 for o-9

The caller continued at once, and the listener ran on task-1. Remember what that costs: an asynchronous listener is not part of the transaction at all, and if the JVM dies before it runs, the event is lost. For events that must survive a crash, Spring Modulith keeps an event publication registry in a database table, and marks each event done when its listener completes (section 10). The same trade-off as the outbox pattern in E7.

Bridge: method security, @PreAuthorize, one level down

Method security means the permission check sits on the service method, not only on the URL. A URL rule such as "only ADMIN may call /admin/**" stops one door. But the same service method can also be called from a scheduled job, a message listener, or a different controller. A check on the method protects every door at once.

It is another layer of the proxy. You switch it on with @EnableMethodSecurity, and you put @PreAuthorize("expression") on a method. Before the method runs, the proxy evaluates the expression with the current user (the Authentication that Spring Security keeps in a thread-bound holder). If the expression is false, the proxy throws AccessDeniedException and the method body never runs. If nobody is logged in at all, it throws AuthenticationCredentialsNotFoundException.

The expression language can look at the roles (hasRole('ADMIN')), at the logged-in name (authentication.name), and at the method's own parameters by name (#customerId). Parameter names work because Spring Boot's parent POM compiles with the -parameters flag. Our rule: an admin can see any invoice, and a customer can see only their own.

Security.java · Boot 4.2runs offline
package com.quickbite;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.stereotype.Service;

@Configuration
@EnableMethodSecurity
class MethodSecurityConfig { }

@Service
class InvoiceAccess {
    @PreAuthorize("hasRole('ADMIN') or #customerId == authentication.name")
    public String invoiceFor(String customerId) { return "invoice of " + customerId; }

    @PreAuthorize("hasRole('ADMIN')")
    public String adminExport() { return "EXPORT of all invoices"; }

    public String viaThis(String customerId) {          // calls its own annotated method
        return this.adminExport();                      // self-invocation: no proxy, no check
    }
}

Notice the third method. viaThis has no annotation, and it calls this.adminExport(), which does. That call goes straight to the real object, not through the proxy, so the check is skipped. This is the self-invocation trap from 02 · Spring AOP from zero, now with a security cost instead of a missing cache.

The best way to test security rules is with a real Spring context and a fake user. The annotation @WithMockUser (from spring-boot-starter-security-test) puts a user with the given name and roles into the security context before each test. Here are the six tests.

SecurityTest.java · Boot 4.2runs offline
package com.quickbite;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;

@SpringBootTest
class SecurityTest {
    @Autowired InvoiceAccess invoices;

    @Test @WithMockUser(username = "asha", roles = "USER")
    void ownerSeesOwnInvoice() { assertThat(invoices.invoiceFor("asha")).isEqualTo("invoice of asha"); }

    @Test @WithMockUser(username = "asha", roles = "USER")
    void otherCustomerIsDenied() {
        assertThatThrownBy(() -> invoices.invoiceFor("ravi")).isInstanceOf(AccessDeniedException.class);
    }

    @Test @WithMockUser(username = "boss", roles = "ADMIN")
    void adminSeesAnyone() { assertThat(invoices.invoiceFor("ravi")).isEqualTo("invoice of ravi"); }

    @Test @WithMockUser(username = "asha", roles = "USER")
    void userCannotExport() {
        assertThatThrownBy(invoices::adminExport).isInstanceOf(AccessDeniedException.class);
    }

    @Test @WithMockUser(username = "asha", roles = "USER")
    void selfInvocationBypassesTheCheck() {
        assertThat(invoices.viaThis("asha")).isEqualTo("EXPORT of all invoices");   // a plain USER got the export!
    }

    @Test
    void noLoginAtAll() {
        assertThatThrownBy(() -> invoices.invoiceFor("asha")).isInstanceOf(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException.class);
    }
}
mvn -o test -Dtest=SecurityTest · Boot 4.2runs offline
[INFO] Running com.quickbite.SecurityTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.105 s -- in com.quickbite.SecurityTest
[INFO] BUILD SUCCESS

What you see: all six passed, and the last two are the ones to read twice. userCannotExport passed, so a plain USER calling adminExport() directly is refused. selfInvocationBypassesTheCheck also passed, and what it asserts is the bug: the same plain USER, calling viaThis, received "EXPORT of all invoices".

Why: the test goes through the injected bean, which is the proxy, so the first call is checked. Inside viaThis, the call this.adminExport() uses the real object and skips the proxy. The fixes are the same as for caching and transactions: move the protected method to another bean, or put the check on viaThis too, or switch to AspectJ weaving (see the self-invocation idiom in section 02). E4 Q65 asks this question in interview form (E4 drill).

Bridge: method validation, @Validated, one level down

Bean Validation puts rules on data with annotations: @NotBlank (text with at least one non-space character), @Positive (a number above zero), @Size, @Email. In a controller, @Valid on a request body checks those rules when the request comes in. But a service method is called from many places: controllers, jobs, listeners, tests. If the rules live only in the controller, every other caller can send junk.

Put the annotation @Validated on the service class, and Spring adds yet another proxy layer: it checks the constraint annotations on the method's parameters (and on its return value) and throws a ConstraintViolationException before the body runs. We test two services with identical signatures, one with @Validated and one without.

Validation.java · Boot 4.2runs offline
package com.quickbite;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Positive;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

@Service @Validated
class DiscountService {
    public String apply(@NotBlank String code, @Positive int percent) { return code + " -" + percent + "%"; }
}

@Service
class UncheckedDiscountService {                        // same signature, no @Validated
    public String apply(@NotBlank String code, @Positive int percent) { return code + " -" + percent + "%"; }
}
ValidationTest.java (excerpt) · Boot 4.2runs offline
@Test void validatedServiceRejectsBadInput() {
    try { checked.apply(" ", -5); }
    catch (ConstraintViolationException e) {
        System.out.println("CVE: " + e.getClass().getName());
        e.getConstraintViolations().stream().map(v -> v.getPropertyPath() + " -> " + v.getMessage())
          .sorted().forEach(s -> System.out.println("  " + s));
        System.out.println("  proxy class: " + checked.getClass().getSimpleName());
        return;
    }
    throw new AssertionError("no exception");
}

@Test void withoutValidatedNothingHappens() {
    System.out.println("unchecked.apply(\" \", -5) -> " + unchecked.apply(" ", -5));
}
mvn -o test -Dtest=ValidationTest · Boot 4.2runs offline
[INFO] Running com.quickbite.ValidationTest
CVE: jakarta.validation.ConstraintViolationException
  apply.code -> must not be blank
  apply.percent -> must be greater than 0
  proxy class: DiscountService$$SpringCGLIB$$0
unchecked.apply(" ", -5) ->   --5%
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.142 s -- in com.quickbite.ValidationTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

What you see: the checked service refused the call and named both problems, with the parameter in the path: apply.code and apply.percent. The unchecked service happily answered " --5%": a blank code and a discount of minus 5 percent. The checked bean is a CGLIB proxy (DiscountService$$SpringCGLIB$$0), the same kind of object as in section 02.

Why: constraint annotations are only labels. Something must read them. On a controller parameter, Spring MVC does it. On a service, only the @Validated proxy does, and without it nothing reads the labels, so they give a false feeling of safety.

Idiom: @Validated on the service, not only the controller

The problem: validation that lives only at the web edge does not protect the job that calls the same service at 02:00, or the listener that gets a message with a blank field.

How it works: the class-level @Validated adds a method-validation interceptor. The service keeps its own contract, and any caller breaking it gets a ConstraintViolationException.

  1. Annotate the class with @Validated and the parameters (or return value) with constraints.
  2. Translate the exception once: a @RestControllerAdvice maps ConstraintViolationException to a 400 response with the field names (E4 covers error handling).
  3. Keep controller validation too, so the cheapest check happens first.

For controllers, Spring Framework 6.1 and later (so Boot 4) also validates constraints placed directly on controller method parameters, such as @RequestParam @Positive int page, without a class-level @Validated, and reports failures with HandlerMethodValidationException, which becomes a 400. We did not run that web case here. The exact exception and response body are in the reference documentation for your version; check it before you write an exception handler.

Bridge: metrics annotations, @Timed and @Observed, one level down

A metric is a number that the application keeps about itself, such as "how many times was this method called and how long did it take". Micrometer is the library that stores them, and Actuator shows them at /actuator/metrics. You could measure a method by hand: take the time, call, take the time, record. That is exactly what the timing aspect in section 02 did. Two annotations are ready-made versions of such an aspect.

Both are only labels until an aspect reads them. Here is our service with one of each, and a TimedAspect bean that we declare ourselves, as Micrometer's documentation does (we did not test whether Boot creates it for you).

Metrics.java · Boot 4.2runs offline
package com.quickbite;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.aop.TimedAspect;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.observation.annotation.Observed;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

@Configuration
class MetricsConfig {
    @Bean TimedAspect timedAspect(MeterRegistry registry) { return new TimedAspect(registry); }
}

@Service
class PriceService {
    @Observed(name = "menu.load", contextualName = "load-menu", lowCardinalityKeyValues = {"source", "db"})
    public int load() { Util.sleep(20); return 3; }

    @Timed(value = "menu.price", description = "time to price an item")
    public int price(String item) { Util.sleep(10); return 24900; }

    public int untouched() { return 1; }
}

Make the invisible visible: call each method 3 times, ask the meter registry for the meters, and then read them over HTTP from /actuator/metrics in the same run. First with Boot's defaults.

run --demo=metrics · Boot 4.2 (defaults)runs offline
# JSON trimmed to measurements and tags
menu.load: NO METER
menu.price: count=3 tags=[tag(class=com.quickbite.PriceService), tag(exception=none), tag(method=price)]
menu.* meters: [menu.price]
GET /actuator/metrics/menu.price -> 200
  measurements: [{"statistic": "COUNT", "value": 3.0}, {"statistic": "TOTAL_TIME", "value": 0.031315617}, {"statistic": "MAX", "value": 0.010716936}]
  tags: {"exception": ["none"], "method": ["price"], "class": ["com.quickbite.PriceService"]}
GET /actuator/metrics/menu.load -> 404

What you see: menu.price (the @Timed method) has a timer with count 3 and a total time of about 32 ms. menu.load (the @Observed method) has no meter at all, and the endpoint answers 404.

Why: @Observed only does something when an ObservedAspect exists, and in Boot that aspect is switched off until you turn on one property. Boot 4.2 contains the auto-configuration (ObservationAutoConfiguration has an ObservedAspectConfiguration), which is why the property below is enough. A missing meter with no error is the usual symptom of an annotation whose aspect is off.

application.properties (excerpt) · Boot 4.2runs offline
management.observations.annotations.enabled=true
run --demo=metrics --management.observations.annotations.enabled=true · Boot 4.2runs offline
# JSON trimmed to measurements and tags
menu.load: count=3 tags=[tag(class=com.quickbite.PriceService), tag(error=none), tag(method=load), tag(source=db)]
menu.price: count=3 tags=[tag(class=com.quickbite.PriceService), tag(exception=none), tag(method=price)]
menu.* meters: [menu.load, menu.price]
GET /actuator/metrics/menu.price -> 200
  measurements: [{"statistic": "COUNT", "value": 3.0}, {"statistic": "TOTAL_TIME", "value": 0.031874838}, {"statistic": "MAX", "value": 0.0109713}]
  tags: {"exception": ["none"], "method": ["price"], "class": ["com.quickbite.PriceService"]}
GET /actuator/metrics/menu.load -> 200
  measurements: [{"statistic": "COUNT", "value": 3.0}, {"statistic": "TOTAL_TIME", "value": 0.067735226}, {"statistic": "MAX", "value": 0.026179657}]
  tags: {"method": ["load"], "source": ["db"], "error": ["none"], "class": ["com.quickbite.PriceService"]}

What you see: now menu.load exists, with count 3, a total of about 65 ms, and the tags class, method, error (none) and our own source=db from lowCardinalityKeyValues. The @Timed meter tags the exception as exception; the observation tags it as error.

Why: the same method call now goes through the observation aspect. The name menu.load is the timer's name, and contextualName is the span name if a tracer (section 09 of E4, or the OpenTelemetry starter) is present. A low-cardinality tag has few possible values (db, cache); that is the right kind for a metric tag. Never put an order id or customer id in a tag: every distinct value creates a new time series, and the metrics store grows without bound.

ChoosePick it whenCost or catch
@TimedYou only want a timer on a method, with plain Micrometer.A TimedAspect bean must exist. Timer only, no traces.
@ObservedYou want metrics and traces from one annotation, or already use observations.The property must be on, or nothing is recorded. Tag names differ from @Timed.
Your own @Around aspect (section 02)You need custom tags, sampling, or to log arguments.You write and test it, and you own the pointcut. The annotations above are exactly this, prebuilt.

All three share two limits. They measure calls that go through the proxy, so a self-invocation is invisible. And they time the whole proxied call, including time spent waiting for an @ConcurrencyLimit permit or retry delays if the layers are stacked outside the metric layer, so read the numbers with the stack in mind. Boot also contains an auto-configuration that observes scheduled tasks (ScheduledTasksObservationAutoConfiguration, which is in the jar); we did not run it, so check the reference documentation for the meter name.

Bridge: @Lazy, one level down

Spring creates every singleton bean at startup, in dependency order. That is why configuration errors show up when the app starts and not at 3 a.m. Lazy means "create it later, when someone first needs it". @Lazy can sit in two places, and they do different things.

To see the difference, we print a line in each constructor. EagerCache is normal. ReportEngine is a @Lazy bean. SlowClient is a normal bean that is injected with @Lazy. ChatClient is both.

LazyProfile.java (excerpt) · Boot 4.2runs offline
@Component @Lazy
class ReportEngine {
    ReportEngine() { System.out.println("  creating ReportEngine (@Lazy bean)"); }
}

@Component @Lazy
class ChatClient {
    ChatClient() { System.out.println("  creating ChatClient (@Lazy bean AND @Lazy injection point)"); }
    String hello() { return "hi"; }
}

@Component
class Dashboard {
    Dashboard(@Lazy SlowClient client, @Lazy ChatClient chat) {   // a proxy is injected for each
        this.client = client;
        this.chat = chat;
        System.out.println("  creating Dashboard, client is " + client.getClass().getSimpleName());
    }
}
run --demo=lazy · Boot 4.2runs offline
  creating Dashboard, client is SlowClient$$SpringCGLIB$$0
  creating EagerCache (eager, the default)
  creating SlowClient (heavy)
  context is ready
  Dashboard.show() -> called
  creating ChatClient (@Lazy bean AND @Lazy injection point)
  Dashboard.chat.hello() -> hi
  creating ReportEngine (@Lazy bean)
  ReportEngine.run() -> report built

What you see: Dashboard was created first and got a proxy (SlowClient$$SpringCGLIB$$0), because the real SlowClient did not exist yet. Then EagerCache and SlowClient were created, both before context is ready. ChatClient and ReportEngine were created only after the context was ready, at the first call.

Why: @Lazy on an injection point only delays the lookup. SlowClient is still an ordinary singleton, so Spring creates it during startup like any other. To skip it at startup, the bean itself needs @Lazy, as ChatClient has. This is the common mistake: marking only the injection point and expecting a faster startup.

There is also a global switch, spring.main.lazy-initialization=true, which makes every bean lazy. Same demo with it:

run --demo=lazy --spring.main.lazy-initialization=true · Boot 4.2runs offline
  creating Dashboard, client is SlowClient$$SpringCGLIB$$0
  context is ready
  creating SlowClient (heavy)
  Dashboard.show() -> called
  creating ChatClient (@Lazy bean AND @Lazy injection point)
  Dashboard.chat.hello() -> hi
  creating ReportEngine (@Lazy bean)
  ReportEngine.run() -> report built

Now EagerCache was never created at all (nothing used it), and SlowClient waited for the first call. Dashboard is still created early because the demo's runner needs it as a parameter. The win is a faster start and less memory. The price: errors that used to stop the startup now appear on the first request that needs the bean, in front of a customer, and the first request is slower. Use the global switch for tests and tools, and per-bean @Lazy for a few heavy, rarely used beans.

@Profile or @ConditionalOnProperty?

Both decide whether a bean exists. They answer different questions, and section 08 goes deeper. A profile is a named environment (dev, prod) switched on with spring.profiles.active; @Profile("dev") and @Profile("!dev") pick whole sets of beans for it. @ConditionalOnProperty looks at one property and is the right tool for a single feature flag.

We use both. Two implementations of Sms are chosen by profile: ConsoleSms in dev, GatewaySms everywhere else. A separate SmsFeature bean exists only when the property feature.sms is on.

LazyProfile.java (excerpt) · Boot 4.2runs offline
@Component @Profile("dev")
class ConsoleSms implements Sms { public String send() { return "printed to console"; } }

@Component @Profile("!dev")
class GatewaySms implements Sms { public String send() { return "sent via gateway"; } }

@Component @ConditionalOnProperty(name = "feature.sms", havingValue = "on")
class SmsFeature { SmsFeature() { System.out.println("  SmsFeature bean created (feature.sms=on)"); } }
run --demo=profile (no profile, no flag) · Boot 4.2runs offline
  profiles=[] Sms -> sent via gateway, SmsFeature present=false
run --demo=profile --spring.profiles.active=dev --feature.sms=on · Boot 4.2runs offline
  SmsFeature bean created (feature.sms=on)
  profiles=[dev] Sms -> printed to console, SmsFeature present=true
OptionPick it whenCost or catch
@ProfileA whole environment differs: which database, which SMS client, which security setup.Profiles multiply (dev, test, prod-eu) and combine in surprising ways. Nobody knows which beans a profile really turns on.
@ConditionalOnPropertyOne feature, one flag, with a default (matchIfMissing), switchable per deployment.Many flags make a matrix of untested combinations. The condition is checked at startup only.
Runtime feature flag (a database value or a flag service)You need to switch it while the app runs, or per customer.The bean must exist all the time and check the flag on each call.

A good rule: use a profile to describe where the app runs, and a property for what is switched on. Never use @Profile("prod") to hide a feature that you merely have not finished.

What to remember from sections 06 and 07

AnnotationSwitch it on withThe trap you ran
@Retryable@EnableResilientMethodsRetrying a non-idempotent call double-charged; maxRetries counts retries, not calls
@ConcurrencyLimit@EnableResilientMethodsQueues callers; per JVM, not per cluster
@CircuitBreakerResilience4j starter plus YAMLA fallback that hides the outage; one breaker per pod
@Scheduled@EnableSchedulingOne shared thread; slow fixedRate falls behind or overlaps itself
@SchedulerLock@EnableSchedulerLock plus a lock tablelockAtMostFor shorter than the job
@TransactionalEventListenernothing extra (needs a transaction)Silent without a transaction; writes need REQUIRES_NEW
@PreAuthorize@EnableMethodSecuritySelf-invocation skipped the check
@Validatednothing extra (Boot auto-configures it)Without it the constraints are ignored
@Observedmanagement.observations.annotations.enabled=trueNo meter, no error, until the property is set
@LazynothingOn the injection point alone, the bean is still created at startup

The pattern across both sections is the one from section 02: every annotation here is a layer of a proxy or a post-processor, so each one needs a switch, each one is skipped by a call through this, and each one fails silently when the switch is missing. When something "does nothing", check the switch first, then the call path.

08 · WiringProfiles, Property Precedence, Custom Starters, Lifecycle and Cycles

Spring Boot decides a hundred things before your first line of code runs: which database to use, which beans to create, in what order to start them. This section opens that box. You will learn which setting wins when the same property is set in five places, how profiles switch whole blocks of configuration, how to write a tiny auto-configuration of your own, the exact order of a bean's lifecycle callbacks, and what to do when two beans need each other.

QuickBite ran three pods of the order service. On a Tuesday at 14:05 a new version went out, and for 22 minutes 41 real customer orders were written to the development database. Nothing crashed. The pods were healthy, the health check was green, and the dashboards for the production database showed a strange dip.

The cause was one letter. The deployment file set an environment variable called QUICKBITE_DB_URI. The code read quickbite.db.url. The two names did not match, so Spring ignored the variable and used the default from application.properties, which pointed at the dev database. Spring did exactly what its rules say. Nobody on the team could say what those rules were, in order.

So we start with the rules. Below is one property, quickbite.db.url, set in five different places at once. A small program prints which place won, and then lists every place that defined it. A property source is just one named bag of key-value settings: a file, the environment variables, the command line. Spring keeps a list of these bags and asks them in order.

The setup: five places, one key. The two files live inside the jar. The other three are given when we start the process. The profile prod is what makes Spring read application-prod.properties.

the five places · Boot 4.2runs offline
# 1. src/main/resources/application.properties   (inside the jar)
quickbite.db.url=jdbc:h2:mem:from-application-properties

# 2. src/main/resources/application-prod.properties   (read only when profile "prod" is active)
quickbite.db.url=jdbc:h2:mem:from-profile-file

# 3. an operating-system environment variable, set by Docker or Kubernetes
QUICKBITE_DB_URL=jdbc:h2:mem:from-env-var

# 4. a JVM system property, passed before -jar
-Dquickbite.db.url=jdbc:h2:mem:from-system-property

# 5. a command-line argument, passed after the jar name
--quickbite.db.url=jdbc:h2:mem:from-command-line

Now the program. It is one CommandLineRunner (a bean whose run method Boot calls once the application has started). It asks the Environment for the winner, then walks the list of property sources and prints every one that holds the key.

PrecedenceDemo.java · Boot 4.2runs offline
    @Bean
    CommandLineRunner printWinner(ConfigurableEnvironment env, ApplicationContext ctx) {
        return args -> {
            String key = "quickbite.db.url";
            System.out.println("winner : " + env.getProperty(key));
            System.out.println("sources that define " + key + ", highest first:");
            for (PropertySource<?> ps : env.getPropertySources()) {
                if (ps.getName().equals("configurationProperties")) continue;   // a view over all the others
                Object v = ps.getProperty(key);
                if (v != null) {
                    String name = ps.getName().replace("Config resource 'class path resource ", "file ")
                            .replaceAll("' via location.*", "");
                    System.out.printf("  %-45s -> %s%n", name, v);
                }
            }
            // keep a web app alive so we can curl /actuator/env; exit a plain one
            if (!"servlet".equalsIgnoreCase(env.getProperty("spring.main.web-application-type"))) {
                System.exit(SpringApplication.exit(ctx));
            }
        };
    }

We run it six times. Each run removes the winner of the run before, so you see the next one in line. Every run is a real execution on this machine. The final run is the incident: the variable has the wrong name.

Make the invisible visible: the whole ladder, from the top.

run-precedence.sh · Boot 4.2runs offline
--- all five places set
winner : jdbc:h2:mem:from-command-line
sources that define quickbite.db.url, highest first:
  commandLineArgs                               -> jdbc:h2:mem:from-command-line
  systemProperties                              -> jdbc:h2:mem:from-system-property
  systemEnvironment                             -> jdbc:h2:mem:from-env-var
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the command-line argument
winner : jdbc:h2:mem:from-system-property
sources that define quickbite.db.url, highest first:
  systemProperties                              -> jdbc:h2:mem:from-system-property
  systemEnvironment                             -> jdbc:h2:mem:from-env-var
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the system property
winner : jdbc:h2:mem:from-env-var
sources that define quickbite.db.url, highest first:
  systemEnvironment                             -> jdbc:h2:mem:from-env-var
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the environment variable
winner : jdbc:h2:mem:from-profile-file
sources that define quickbite.db.url, highest first:
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the profile
winner : jdbc:h2:mem:from-application-properties
sources that define quickbite.db.url, highest first:
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- the typo: QUICKBITE_DB_URI instead of QUICKBITE_DB_URL
winner : jdbc:h2:mem:from-application-properties
sources that define quickbite.db.url, highest first:
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties

What you see: with all five set, the command-line argument wins. Remove it and the JVM system property wins. Remove that and the environment variable wins. Remove that and the profile file wins. Remove the profile and application.properties wins. The last run shows the incident: QUICKBITE_DB_URI matched nothing, so the list has one source, the default file, and the default won without a single warning.

Why: Spring Boot builds an Environment, which holds a list of property sources in a fixed order. To read a key it asks each source from the top and stops at the first one that has it. Sources lower down are not consulted. That is why a typo is silent: a name that matches nothing does not raise an error, it is just a key nobody asked for.

Figure 22.13 draws the same ladder as a picture, with who normally puts a value on each rung.

Which source wins: ask from the top, stop at the first that has the key 1 · Command-line arguments --quickbite.db.url=... whoever starts the process 2 · JVM system properties -Dquickbite.db.url=... the launcher script 3 · Operating-system environment QUICKBITE_DB_URL=... Kubernetes, Docker, CI 4 · Profile files application-prod.properties / .yml the team, in the jar 5 · Default files application.properties / .yml the team, in the jar 6 · Defaults written in code record constructor, @Value("${x:5}") the developer wins imported files (spring.config.import) slot in near the top: see the run below
Fig. 22.13 — The property source ladder. Rows 1 to 3 are set when the process starts, which is why they win. Rows 4 and 5 ship inside the jar. The first source that has the key decides, and a key that matches no source simply falls through to the next rung.

The order has a purpose. The things nearest the person running the process (arguments, environment) beat the things baked into the build. That lets one jar run in dev, test and production with no rebuild. The price is the incident above: if you spell a name wrong, you fall back to whatever is baked in.

Idiom: know the ladder, and make a missing value fail loudly

The problem: a safe-looking default in application.properties (a dev URL, a dev password) hides every typo in the real source. The value is wrong, the app is healthy, and the first sign is a data problem.

How it works: bind the settings to a @ConfigurationProperties class with @Validated and @NotBlank, and give the production-only keys no default anywhere. Put dev values in application-dev.properties, which only the dev profile loads. A typo now means a missing value, and a missing value stops the start-up.

  1. Declare: one record per concern (quickbite.payments, quickbite.db), each field annotated with its rule.
  2. Remove the default: the key must not exist in application.properties. Dev values go in a dev-only file or profile.
  3. Validate: add @Validated. Boot then refuses to start when a required value is blank or missing.
  4. Print the winner: for the keys that matter, log the source at start-up, or check /actuator/env/<key> after a deploy.

Without the idiom, the typo from the incident gave a healthy app on the wrong database (the last run above). With the idiom, the same typo looks like this. First the class, then two runs: one with the typo, one with the right name.

RequiredDemo.java · Boot 4.2runs offline
    @Validated
    @ConfigurationProperties(prefix = "quickbite.payments")
    record Payments(@NotBlank String url) { }

    @Bean
    CommandLineRunner show(Payments payments, ConfigurableApplicationContext ctx) {
        return args -> {
            System.out.println("payments gateway = " + payments.url());
            System.exit(SpringApplication.exit(ctx));
        };
    }
run --demo=required · Boot 4.2runs offline
$ QUICKBITE_PAYMENTS_URI=https://pay.example.com java -jar app.jar --demo=required     # typo: URI
WARN s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Erro
ERROR o.s.b.d.LoggingFailureAnalysisReporter   : 
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target com.quickbite.wiring.RequiredDemo$Payments failed:
    Property: quickbite.payments.url
    Value: "null"
    Reason: must not be blank
Action:
Update your application's configuration

$ QUICKBITE_PAYMENTS_URL=https://pay.example.com java -jar app.jar --demo=required
payments gateway = https://pay.example.com

The typo run does not start. It names the key (quickbite.payments.url), the value it saw (null) and the reason. The deploy fails at minute 0 instead of minute 22, and the old pods keep serving. The right name starts normally.

Bridge: how Boot looks at the same list at runtime

You do not need a debugger to see the ladder on a running service. Actuator (the production-monitoring add-on that E4 introduced, see E4 production behaviour) can print one property and the sources behind it. Since Boot 3.0, property values are hidden by default, so the endpoint shows only names. For this demo we switch values on, on a throw-away local port. Do not do this in production without authentication.

We start the same program as a web app, with all five places set, and ask for the key.

curl · Boot 4.2runs offline
$ curl -s localhost:18401/actuator/env/quickbite.db.url
# (trimmed: only the sources that define the key; formatted with python -m json.tool)
response of /actuator/env/quickbite.db.url · Boot 4.2runs offline
{
  "property": {
    "source": "commandLineArgs",
    "value": "jdbc:h2:mem:from-command-line"
  },
  "activeProfiles": [
    "prod",
    "proddb",
    "metrics"
  ],
  "propertySources": [
    {
      "name": "commandLineArgs",
      "value": "jdbc:h2:mem:from-command-line"
    },
    {
      "name": "systemProperties",
      "value": "jdbc:h2:mem:from-system-property"
    },
    {
      "name": "systemEnvironment",
      "value": "jdbc:h2:mem:from-env-var",
      "origin": "System Environment Property \"QUICKBITE_DB_URL\""
    },
    {
      "name": "file [application-prod.properties]",
      "value": "jdbc:h2:mem:from-profile-file",
      "origin": "class path resource [application-prod.properties] - 1:18"
    },
    {
      "name": "file [application.properties]",
      "value": "jdbc:h2:mem:from-application-properties",
      "origin": "class path resource [application.properties] - 6:18"
    }
  ]
}

The answer has three parts. property names the winner and its source. propertySources lists every source that holds the key, in the order Boot asks them. The origin field says which file and line (or which environment variable) a value came from. For the incident, one curl after the deploy would have shown application.properties as the winner and ended the mystery in ten seconds.

Notice also that activeProfiles shows prod, proddb and metrics, although we only asked for prod. That is a profile group, and the next part explains it.

Bridge: relaxed binding, or why one setting has four spellings

A property name has a clean form for files: lowercase words joined by dashes, as in quickbite.limits.order-timeout. Environment variables cannot contain dots or dashes in most shells, so they use capitals and underscores. Relaxed binding is Boot's rule that all these spellings reach the same Java field.

Here is a record with two fields, orderTimeout (a Duration) and maxItems. Each run sets the value in a different spelling. The record has defaults: 30 seconds and 10 items.

RelaxedDemo.java · Boot 4.2runs offline
    @ConfigurationProperties(prefix = "quickbite.limits")
    record Limits(Duration orderTimeout, int maxItems) {
        Limits {
            if (orderTimeout == null) orderTimeout = Duration.ofSeconds(30);   // default
            if (maxItems == 0) maxItems = 10;
        }
    }

    @Bean
    CommandLineRunner show(Limits limits, ApplicationContext ctx) {
        return args -> {
            System.out.println("orderTimeout = " + limits.orderTimeout() + ", maxItems = " + limits.maxItems());
            System.exit(SpringApplication.exit(ctx));
        };
    }
run --demo=relaxed · Boot 4.2runs offline
--- application.properties/yml spelling: quickbite.limits.order-timeout=45s (kebab case)
orderTimeout = PT45S, maxItems = 10
--- camelCase: --quickbite.limits.orderTimeout=40s
orderTimeout = PT40S, maxItems = 10
--- underscore: --quickbite.limits.order_timeout=35s
orderTimeout = PT35S, maxItems = 10
--- env var QUICKBITE_LIMITS_ORDERTIMEOUT=25s
orderTimeout = PT25S, maxItems = 10
--- env var QUICKBITE_LIMITS_ORDER_TIMEOUT=20s
orderTimeout = PT20S, maxItems = 10
--- env var QUICKBITE_LIMITS_MAXITEMS=7
orderTimeout = PT30S, maxItems = 7
--- env var QUICKBITE_LIMITS_MAX_ITEMS=7
orderTimeout = PT30S, maxItems = 7
--- no setting at all
orderTimeout = PT30S, maxItems = 10
--- wrong env var name QUICKBITE_LIMIT_MAXITEMS=7
orderTimeout = PT30S, maxItems = 10
Spellings that reached the same field in the runs above
Where you set itSpellingBound?
Properties or YAML file (preferred)quickbite.limits.order-timeoutYes (kebab case)
Command line or filequickbite.limits.orderTimeout, quickbite.limits.order_timeoutYes
Environment variableQUICKBITE_LIMITS_ORDERTIMEOUT and QUICKBITE_LIMITS_ORDER_TIMEOUTYes, both forms
Environment variable, wrong prefixQUICKBITE_LIMIT_MAXITEMS (missing S)No, silently ignored

Every spelling that matches reaches the field. The last row is the incident again: relaxed binding is generous about form and strict about words. limit and limits are different words. Lists and maps have their own forms in environment variables (an index such as _0 for list items); check the reference documentation for the exact rules for your version before relying on them.

For the full tour of @ConfigurationProperties versus @Value, records, validation and constructor binding, read E4 configuration. We do not repeat it here. The one point to keep: bind a group of related settings to one typed class, and relaxed binding, validation and IDE hints come for free. @Value gets none of the relaxed forms for the environment.

Bridge: spring.config.import and config trees

Sometimes values live outside the jar in a file you do not control. Kubernetes mounts a Secret as a directory, one file per key, and the file name is the key. Boot reads that shape directly with a config tree: optional:configtree:/path/. An ordinary file is imported with optional:file:/path/to/file.properties. The optional: prefix means "do not fail if it is missing".

We make a directory with two one-line files, db.username and db.password, plus an extra properties file with a region. The program prints the username, only the length of the password (never print a secret), and the region.

run --demo=configtree · Boot 4.2runs offline
$ ls /tmp/qb-secrets
db.password
db.username
$ java -jar app.jar --demo=configtree \
    --spring.config.import=optional:configtree:/tmp/qb-secrets/,optional:file:/tmp/qb-extra.properties
db.username = quickbite_app
db.password = 22 characters
quickbite.region = ap-south-1
$ the same without the import
db.username = null
db.password = null
quickbite.region = null

With the import, all three values appear. Without it, all three are null. This is how a Kubernetes Secret mounted at /etc/secrets/ becomes db.password with no code at all. See E10 Kubernetes for how Secrets and ConfigMaps are mounted.

Where does an imported file sit on the ladder? In this run the file was named on the command line, and it beat both application files:

run --demo=precedence --spring.config.import=… · Boot 4.2runs offline
$ java -jar app.jar --demo=precedence --spring.profiles.active=prod --spring.config.import=optional:file:/tmp/qb-extra2.properties
winner : jdbc:h2:mem:from-imported-file
sources that define quickbite.db.url, highest first:
  Config resource 'file [/tmp/qb-extra2.properties] -> jdbc:h2:mem:from-imported-file
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties

The imported file came above application-prod.properties here. If you put spring.config.import inside application.properties instead, the position may differ, so check the reference documentation for your version and use /actuator/env to confirm what you actually get.

Bridge: profiles, one jar for every environment

A profile is a named switch. When it is on, Boot loads extra configuration and creates extra beans. When it is off, they do not exist. QuickBite uses prod in production, dev on laptops and test in tests. The jar is the same in all three.

A profile can change things in four places. We use all four below.

What a profile can switch
MechanismWhere you write itEffect
Profile-specific fileapplication-prod.properties or .ymlLoaded only when prod is active; its values beat the default file.
on-profile documenta block inside one application.yml, split by ---Same effect, but all environments sit in one file.
@Profileon a @Component, @Bean or @ConfigurationThe bean exists only when the profile expression is true ("prod", "!prod").
Profile groupspring.profiles.group.prod=proddb,metricsSwitching on prod also switches on the members.

Here is the YAML. It has four documents separated by ---. The first is always loaded. The other three each carry on-profile, so each is loaded only when that profile is active. The first document also declares a group: turning on prod turns on proddb and metrics too.

application.yml · Boot 4.2runs offline
quickbite:
  greeting: hello from the default document
spring:
  profiles:
    group:
      prod: proddb,metrics        # activating "prod" also activates these two
---
spring:
  config:
    activate:
      on-profile: proddb
quickbite:
  db:
    pool: 20
---
spring:
  config:
    activate:
      on-profile: metrics
quickbite:
  metrics:
    enabled: true
---
spring:
  config:
    activate:
      on-profile: prod
quickbite:
  greeting: hello from the prod document

The program creates one of two mail senders with @Profile, and prints the active profiles and the values it can see. We run it three ways: no profile, prod, and only metrics (through the environment variable, to show that is a profile too).

ProfilesDemo.java · Boot 4.2runs offline
    @Bean @Profile("prod")
    String emailSender() { return "SmtpEmailSender (real mail server)"; }

    @Bean @Profile("!prod")
    String fakeEmailSender() { return "ConsoleEmailSender (prints to the log)"; }

    @Bean
    CommandLineRunner show(Environment env, ApplicationContext ctx, ObjectProvider<String> strings) {
        return args -> {
            System.out.println("active profiles     : " + Arrays.toString(env.getActiveProfiles()));
            System.out.println("default profiles    : " + Arrays.toString(env.getDefaultProfiles()));
            System.out.println("quickbite.greeting  : " + env.getProperty("quickbite.greeting"));
            System.out.println("quickbite.db.pool   : " + env.getProperty("quickbite.db.pool"));
            System.out.println("quickbite.metrics   : " + env.getProperty("quickbite.metrics.enabled"));
            System.out.println("mail bean present   : " + (ctx.containsBean("emailSender") ? ctx.getBean("emailSender")
                    : ctx.getBean("fakeEmailSender")));
            System.exit(SpringApplication.exit(ctx));
        };
    }
}
run --demo=profiles · Boot 4.2runs offline
$ java -jar app.jar --demo=profiles
active profiles     : []
default profiles    : [default]
quickbite.greeting  : hello from the default document
quickbite.db.pool   : null
quickbite.metrics   : null
mail bean present   : ConsoleEmailSender (prints to the log)

$ java -jar app.jar --demo=profiles --spring.profiles.active=prod
active profiles     : [prod, proddb, metrics]
default profiles    : [default]
quickbite.greeting  : hello from the prod document
quickbite.db.pool   : 20
quickbite.metrics   : true
mail bean present   : SmtpEmailSender (real mail server)

$ SPRING_PROFILES_ACTIVE=metrics java -jar app.jar --demo=profiles
active profiles     : [metrics]
default profiles    : [default]
quickbite.greeting  : hello from the default document
quickbite.db.pool   : null
quickbite.metrics   : true
mail bean present   : ConsoleEmailSender (prints to the log)

What you see: with no profile Boot reports an empty active list and one default profile named default. The greeting comes from the first YAML document, and the console mail sender exists. With prod, the active list has three names, because the group added proddb and metrics.

The pool size from the proddb document (20) and the metrics flag appear, the greeting is overridden by the prod document (it comes later, so it wins), and the real SMTP sender replaces the console one. The third run proves that a profile does not need its parent: metrics alone turned on only its own block.

Why: each on-profile document is its own property source. Boot adds the active ones to the list from Fig. 22.13 and the usual first-match rule applies. Among documents of the same file, the later one has priority, which is why the prod document was written last.

Three habits keep profiles from biting you.

  1. Few profiles: one per environment (dev, test, prod) and perhaps a few for optional features. Do not make a profile for every customer or every flag.
  2. No secrets in the jar: a profile file in the jar is not a safe place for passwords. Use environment variables or a mounted secret (the config tree above).
  3. Set it from outside: put SPRING_PROFILES_ACTIVE=prod in the deployment, not in a file. Boot also refuses to start (it throws InvalidConfigDataPropertyException, which we tried) if spring.profiles.active appears inside a profile-specific file, because the file would be chosen by the very setting it contains.

A classic production surprise: a value in application-prod.yml is ignored because the pod never had the prod profile on. The file is never read, so nothing complains. The curl from the earlier bridge shows activeProfiles at once. Drill question Q67 practises exactly this diagnosis.

@Profile and @ConditionalOnProperty look alike. A profile is a coarse, named switch for a whole environment. A property condition is a fine switch for one feature. Section 07 compares them in a short table.

Bridge: a custom auto-configuration and starter

QuickBite has nine services. Each one grew its own AuditLogger: one printed JSON, one printed plain text, one forgot the user name. A regulator asked for "who refunded which order" and four of nine services could not say. The fix was one small library that every service adds as a dependency and that configures itself.

That library is a starter. To understand it, first understand auto-configuration: a normal @Configuration class whose beans are created only when conditions say so. Boot ships hundreds. When you add spring-boot-starter-webmvc, it brings a jar, and that jar lists auto-configuration classes in a text file. Boot reads the file, checks each class's conditions against your classpath and properties, and creates only the beans that make sense. You can write the same thing for your own library.

A starter has four parts. The names are the standard ones.

The four parts of an auto-configuration library
PartExample in our demoJob
Service classAuditLoggerThe thing the library offers.
Properties classAuditProperties (quickbite.audit.*)Typed settings with defaults, see E4.
@AutoConfiguration classQuickbiteAuditAutoConfigurationCreates the service, guarded by conditions.
Imports fileMETA-INF/spring/…AutoConfiguration.importsOne class name per line. Without this line Boot never sees the class.

Chunk one is the service. It records "who did what" to a sink (a function that accepts a line of text). In the real library the sink would write to a table or a log; here it prints.

AuditLogger.java · Boot 4.2runs offline
/** The service the starter offers: record "who did what". */
public class AuditLogger {

    private final String prefix;
    private final Consumer<String> sink;

    public AuditLogger(String prefix, Consumer<String> sink) {
        this.prefix = prefix;
        this.sink = sink;
    }

    public void record(String user, String action) {
        sink.accept(prefix + " user=" + user + " action=" + action);
    }
}

Chunk two is the auto-configuration. Read it from the top: two conditions guard the class, a third guards the bean, and an inner block has a condition of its own.

QuickbiteAuditAutoConfiguration.java · Boot 4.2runs offline
@AutoConfiguration
@ConditionalOnClass(AuditLogger.class)
@ConditionalOnProperty(prefix = "quickbite.audit", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class QuickbiteAuditAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public AuditLogger auditLogger(AuditProperties props) {
        return new AuditLogger(props.getPrefix(), line -> System.out.println("[starter] " + line));
    }

    /** Only when Kafka is on the classpath (it is not in our demo). */
    @org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
    @ConditionalOnClass(name = "org.apache.kafka.clients.producer.KafkaProducer")
    static class KafkaAuditSinkConfiguration {
        @Bean
        String kafkaAuditTopic() { return "audit-events"; }
    }
}

Chunk three is the imports file. Its full path inside the jar is META-INF/spring/ plus a file name that starts with org.springframework.boot.autoconfigure.; the code block header shows it whole.

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsruns offline
com.quickbite.audit.QuickbiteAuditAutoConfiguration

Chunk four is the pom of the library. It depends only on spring-boot-autoconfigure, so it adds almost nothing to the application. A library like this is normally built with the Maven install goal and used like any other dependency.

pom.xml excerpt · Boot 4.2runs offline
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
	</dependencies>
The conditions in the library, and what each one decides
AnnotationQuestion it asksUsed here for
@ConditionalOnClassIs this class on the classpath?Skip everything if the service class is missing. The inner Kafka block checks for KafkaProducer, which our demo does not have.
@ConditionalOnPropertyDoes this property have this value?quickbite.audit.enabled=false turns the whole library off. matchIfMissing = true makes "not set" mean "on".
@ConditionalOnMissingBeanDoes the application already define one?Back off: if the application has its own AuditLogger, do not create ours.
@EnableConfigurationPropertiesNot a condition: registers the properties classMakes quickbite.audit.prefix bindable.

Now the application. It adds the starter as a dependency (the pom lists quickbite-audit-starter version 1.0.0) and has a runner that asks for an AuditLogger. We run it four times. The first is plain. The second adds an application bean with the same type. The third turns the library off. The fourth changes one property.

StarterDemo.java · Boot 4.2runs offline
@Configuration
@ConditionalOnProperty(name = "demo", havingValue = "starter")
class StarterDemo {

    @Bean
    CommandLineRunner use(ObjectProvider<AuditLogger> audit, ConfigurableApplicationContext ctx) {
        return args -> {
            AuditLogger logger = audit.getIfAvailable();
            if (logger == null) {
                System.out.println("AuditLogger bean : absent");
            } else {
                System.out.println("AuditLogger bean : present, defined in "
                        + ctx.getBeanFactory().getBeanDefinition("auditLogger").getResourceDescription());
                logger.record("amy", "refund order 1042");
            }
            System.out.println("kafkaAuditTopic  : " + ctx.containsBean("kafkaAuditTopic"));
            System.exit(SpringApplication.exit(ctx));
        };
    }

    /** The application's own bean: switched on with --own=true. */
    @Configuration
    @ConditionalOnProperty(name = "own", havingValue = "true")
    static class OwnAuditLogger {
        @Bean
        AuditLogger auditLogger() {
            return new AuditLogger("APP-AUDIT", line -> System.out.println("[app] " + line));
        }
    }
}
run --demo=starter · Boot 4.2runs offline
$ java -jar app.jar --demo=starter
AuditLogger bean : present, defined in class path resource [com/quickbite/audit/QuickbiteAuditAutoConfiguration.class]
[starter] AUDIT user=amy action=refund order 1042
kafkaAuditTopic  : false

$ java -jar app.jar --demo=starter --own=true
AuditLogger bean : present, defined in class path resource [com/quickbite/wiring/StarterDemo$OwnAuditLogger.class]
[app] APP-AUDIT user=amy action=refund order 1042
kafkaAuditTopic  : false

$ java -jar app.jar --demo=starter --quickbite.audit.enabled=false
AuditLogger bean : absent
kafkaAuditTopic  : false

$ java -jar app.jar --demo=starter --quickbite.audit.prefix=QB
AuditLogger bean : present, defined in class path resource [com/quickbite/audit/QuickbiteAuditAutoConfiguration.class]
[starter] QB user=amy action=refund order 1042
kafkaAuditTopic  : false

What you see: run 1: the logger bean exists and its definition came from the starter's class. The application never declared it. Run 2: the bean now comes from StarterDemo$OwnAuditLogger, and the output says [app], not [starter]. The starter stepped aside. Run 3: with enabled=false there is no bean at all. Run 4: QB replaced AUDIT, so the properties class works. In every run kafkaAuditTopic is false because Kafka is not on the classpath.

Boot can also tell you why. Starting with --debug prints the condition evaluation report: every auto-configuration, whether it matched, and the reason. Here are the lines for our class in the three situations. The report is long (hundreds of classes), so this is an excerpt.

run --demo=starter --debug · Boot 4.2 (excerpt)runs offline
# 1. default run: "Positive matches" section
   QuickbiteAuditAutoConfiguration matched:
      - @ConditionalOnClass found required class 'com.quickbite.audit.AuditLogger' (OnClassCondition)
      - @ConditionalOnProperty (quickbite.audit.enabled) matched (OnPropertyCondition)

   QuickbiteAuditAutoConfiguration#auditLogger matched:
      - @ConditionalOnMissingBean (types: com.quickbite.audit.AuditLogger; SearchStrategy: all) did not find any beans (OnBeanCondition)

# 2. --own=true: "Negative matches" section
   QuickbiteAuditAutoConfiguration#auditLogger:
      Did not match:
         - @ConditionalOnMissingBean (types: com.quickbite.audit.AuditLogger; SearchStrategy: all) found beans of type 'com.quickbite.audit.AuditLogger' auditLogger (OnBeanCondition)

# 3. --quickbite.audit.enabled=false
   QuickbiteAuditAutoConfiguration:
      Did not match:
         - @ConditionalOnProperty (quickbite.audit.enabled) found different value in property 'enabled' (OnPropertyCondition)

# 4. always: the Kafka block
   QuickbiteAuditAutoConfiguration.KafkaAuditSinkConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.apache.kafka.clients.producer.KafkaProducer' (OnClassCondition)

Each line names the annotation, the question and the answer. When an auto-configured bean is missing and you do not know why, search this report for the class name. It is the single most useful debugging tool in the Boot toolbox. In a running service the same data is at /actuator/conditions.

Figure 22.14 shows the decision flow Boot follows for one auto-configuration class.

What Boot does with one line of the imports file 1 · Read the imports file from every jar on the classpath 2 · @ConditionalOnClass is AuditLogger on the classpath? Skip the whole class (report: Did not match) no yes 3 · @ConditionalOnProperty is quickbite.audit.enabled true? Skip the whole class (library switched off) no yes 4 · @ConditionalOnMissingBean does the app define an AuditLogger? Back off: use the app's bean (auto-configuration steps aside) yes no 5 · Create the bean AuditLogger from AuditProperties App beans are registered first, so step 4 can see them.
Fig. 22.14 — The conditions flow for one auto-configuration class. Steps 2 and 3 skip the entire class. Step 4 only skips one bean, and only when the application already has one. Boot writes the answer of every step to the condition evaluation report.

One rule is easy to miss. @ConditionalOnMissingBean is reliable in an auto-configuration because Boot processes those classes after the application's own configuration. In a normal @Configuration of your own, the order depends on scanning, and the condition can run before the bean it looks for exists. Use it for libraries.

Idiom: shared infrastructure goes into a starter that backs off

The problem: the same helper (audit, request-id filter, standard error format) is copied into nine services. Copies drift. A fix needs nine pull requests, and four services never got the fix. The other failure is the opposite: a shared library creates its beans unconditionally and collides with what the application defines.

How it works: put the helper in one library with an @AutoConfiguration class. Guard the class with @ConditionalOnClass and an on/off property, guard each bean with @ConditionalOnMissingBean, and list the class in the imports file. Applications get the default by adding one dependency, and override it by defining their own bean.

  1. Write the service and a properties class: give every setting a default so the zero-configuration case works.
  2. Write the auto-configuration: @AutoConfiguration, an on/off property with matchIfMissing = true, and @ConditionalOnMissingBean on every bean.
  3. Register it: add the class name to the AutoConfiguration.imports file under META-INF/spring/.
  4. Test with --debug: check the three outcomes: default, overridden and switched off.

Without the idiom: we removed @ConditionalOnMissingBean from the starter, installed it, and ran the application with its own bean. The application does not start.

run --demo=starter --own=true · starter without back-off · Boot 4.2runs offline
$ java -jar app.jar --demo=starter --own=true     # starter WITHOUT @ConditionalOnMissingBean
APPLICATION FAILED TO START
***************************
Description:
The bean 'auditLogger', defined in class path resource [com/quickbite/audit/QuickbiteAuditAutoConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/quickbite/wiring/StarterDemo$OwnAuditLogger.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

Both beans were called auditLogger, and Boot forbids silent replacement. Had the names differed, the application would have started with two AuditLogger beans, and any injection point asking for one would fail with a "no unique bean" error. If you turn on spring.main.allow-bean-definition-overriding, the library bean would replace the application's. Drill question Q70 is this exact situation. The cure is the one line we put back.

A naming note. Our demo module is called quickbite-audit-starter. Boot reserves the spring-boot-starter-* pattern for its own modules, and asks everyone else to put their name first, for example quickbite-audit-spring-boot-starter. Many teams also split the code into an autoconfigure module and an empty starter module that only lists dependencies. For an internal one-jar library, a single module is fine.

Bridge: the bean lifecycle, in the order it really runs

QuickBite's menu service warmed its cache inside a @PostConstruct method: load 8,000 menu items from the database, about 40 seconds on a cold database. In the test environment the database was warm and it took 3 seconds, so nobody noticed. In production the pod did not answer for 40 seconds after start, the liveness probe gave up at 30, and Kubernetes restarted the pod, which started the warm-up again. Three pods looped for 11 minutes.

The bug is not in Kubernetes. It is in not knowing when each callback runs and what is still missing at that moment. A lifecycle callback is a method Spring calls at a fixed moment in a bean's life. There are many, and several look alike. The only way to remember them is to see them in order.

We build one bean, Kitchen, with every callback Spring offers, plus a listener for each application event and both kinds of runner. Every callback prints a numbered line. Chunk one is the bean itself.

Kitchen · LifecycleDemo.java · Boot 4.2runs offline
    static int step = 0;
    static void log(String what) { System.out.printf("%2d  %s%n", ++step, what); }

    static class Menu { }

    static class Kitchen implements InitializingBean, DisposableBean, SmartInitializingSingleton {
        Kitchen() { log("Kitchen: constructor"); }

        @Autowired
        void setMenu(Menu menu) { log("Kitchen: @Autowired setter (menu injected)"); }

        @PostConstruct
        void postConstruct() { log("Kitchen: @PostConstruct"); }

        @Override public void afterPropertiesSet() { log("Kitchen: afterPropertiesSet()"); }

        void customInit() { log("Kitchen: @Bean(initMethod = customInit)"); }

        @Override public void afterSingletonsInstantiated() {
            log("Kitchen: SmartInitializingSingleton.afterSingletonsInstantiated()");
        }

        @PreDestroy
        void preDestroy() { log("Kitchen: @PreDestroy"); }

        @Override public void destroy() { log("Kitchen: destroy() (DisposableBean)"); }

        void customDestroy() { log("Kitchen: @Bean(destroyMethod = customDestroy)"); }
    }

Chunk two registers the bean, a BeanPostProcessor that reports when Kitchen passes through it (a post-processor is a hook that sees every bean before and after its init callbacks), the event listeners and the two runners. The ready listener also ends the demo.

registration · LifecycleDemo.java · Boot 4.2runs offline
    @Bean Menu menu() { return new Menu(); }

    @Bean(initMethod = "customInit", destroyMethod = "customDestroy")
    Kitchen kitchen() { return new Kitchen(); }

    @Bean
    static BeanPostProcessor watcher() {            // static: it must exist before the other beans
        return new BeanPostProcessor() {
            @Override public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
                if (name.equals("kitchen")) log("BeanPostProcessor: before init callbacks");
                return bean;
            }
            @Override public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
                if (name.equals("kitchen")) log("BeanPostProcessor: after init callbacks");
                return bean;
            }
        };
    }

    @EventListener void refreshed(ContextRefreshedEvent e) { log("ContextRefreshedEvent"); }
    @EventListener void started(ApplicationStartedEvent e) { log("ApplicationStartedEvent"); }
    @EventListener void closing(ContextClosedEvent e) { log("ContextClosedEvent (shutdown begins)"); }

    @Bean CommandLineRunner commandLineRunner() { return args -> log("CommandLineRunner.run()"); }
    @Bean ApplicationRunner applicationRunner() { return args -> log("ApplicationRunner.run()"); }

    @EventListener
    void ready(ApplicationReadyEvent e) {
        log("ApplicationReadyEvent (the app is ready for traffic)");
        ApplicationContext ctx = e.getApplicationContext();
        System.exit(SpringApplication.exit(ctx));
    }

Make the invisible visible: one run, startup and shutdown.

run --demo=lifecycle · Boot 4.2runs offline
 1  Kitchen: constructor
 2  Kitchen: @Autowired setter (menu injected)
 3  BeanPostProcessor: before init callbacks
 4  Kitchen: @PostConstruct
 5  Kitchen: afterPropertiesSet()
 6  Kitchen: @Bean(initMethod = customInit)
 7  BeanPostProcessor: after init callbacks
 8  Kitchen: SmartInitializingSingleton.afterSingletonsInstantiated()
 9  ContextRefreshedEvent
10  ApplicationStartedEvent
11  CommandLineRunner.run()
12  ApplicationRunner.run()
13  ApplicationReadyEvent (the app is ready for traffic)
14  ContextClosedEvent (shutdown begins)
15  Kitchen: @PreDestroy
16  Kitchen: destroy() (DisposableBean)
17  Kitchen: @Bean(destroyMethod = customDestroy)

Figure 22.15 is the same list as a picture. Steps 1 to 7 repeat for every bean. The rest happen once per application.

Startup: top to bottom Shutdown 1 · constructor 2 · @Autowired setter (dependencies injected) 3 · BeanPostProcessor before init 4 · @PostConstruct 5 · afterPropertiesSet() 6 · custom init method (initMethod) 7 · BeanPostProcessor after init (proxy made here) 8 · SmartInitializingSingleton callback 9 · ContextRefreshedEvent 10 · ApplicationStartedEvent 11 · CommandLineRunner.run() 12 · ApplicationRunner.run() 13 · ApplicationReadyEvent 14 · ContextClosedEvent 15 · @PreDestroy 16 · destroy() (DisposableBean) 17 · custom destroy method Not called for prototype beans, and not called at all if the JVM is killed with kill -9.
Fig. 22.15 — The order of callbacks in one run. Steps 1 to 7 repeat for each bean (plain boxes). Steps 8 and 9 happen once the container has built all singletons. Steps 10 to 13 belong to the application start-up (green). Shutdown starts with the close event and then runs each bean's destroy callbacks in the order shown.

What you see: the constructor runs first, with no dependencies injected yet. The setter runs second, with the dependency. Then come the post-processor, @PostConstruct, afterPropertiesSet and the custom init method. Only after every singleton bean exists does the SmartInitializingSingleton callback fire, then ContextRefreshedEvent, then ApplicationStartedEvent, then the runners, and last ApplicationReadyEvent. On close, the event comes first, and each destroy callback follows in the order @PreDestroy, destroy(), custom method.

Two lines in this output deserve a second look. The CommandLineRunner ran before the ApplicationRunner, which is the order we declared them in (7 runs out of 7 on the course machine). Neither interface promises that order. With no @Order given, treat it as an accident, and add @Order when it matters.

And our own post-processor's "before" callback printed ahead of @PostConstruct. Post-processors run in layers according to their own ordering, so the exact place of a custom one among the built-in ones is not something to build on. What you can build on is the sequence of the bean's own four callbacks.

Where does my start-up work belong?
PlaceRuns whenGood forThe catch
ConstructorBean is created, dependencies are only constructor argumentsStoring the dependencies. Nothing else.Fields injected by @Autowired on a field or setter are still empty here. Do no work.
@PostConstructDependencies injected, this bean onlyCheap checks and setting derived fields.Other beans may not be ready. A slow task here delays the whole start-up (the web server has not even started), as the 40-second warm-up did.
SmartInitializingSingletonAll singletons existWork that needs every bean to exist.Still before the web server has started, so nothing can call the application yet.
ApplicationRunner / CommandLineRunnerContext ready, before ApplicationReadyEventOne-off start-up jobs that should finish before "ready".The web port is already open while runners run, but the readiness state is not yet "accepting traffic". An exception here stops the start-up. Order between the two kinds is not guaranteed.
ApplicationReadyEventApplication fully startedWarm-ups that may run while traffic starts: hand them to an executor.Listeners run on the starting thread, one after another. In the default setup Boot switches readiness to "accepting traffic" only after they return, so a slow listener delays readiness. Hand slow work to an executor.

The rule that would have saved QuickBite: do nothing slow in @PostConstruct. Start the warm-up from ApplicationReadyEvent on a background thread, make the first requests tolerate a cold cache (a miss simply loads that key, see section 04), and let the readiness probe, not the start-up order, decide when traffic arrives. For the probes themselves see E4 production behaviour.

Last, a note on style. Prefer constructor injection for required dependencies. The fields can then be final, the bean cannot exist half-built, and a missing dependency fails at the earliest possible moment. The setter in the demo exists only to show the order.

Bridge: circular dependencies, the start-up failure and the fixes

A Friday refactor at QuickBite gave OrderService a discount from LoyaltyService. Loyalty needed to know how many orders a customer had placed, so it called back into OrderService. Each service now needed the other. On Boot 2.5 and earlier the application started anyway. Since Boot 2.6 it refuses, and the upgrade day turned into a debugging day.

A circular dependency (a cycle) means bean A needs bean B to be created, and B needs A. Spring must create one first, and it cannot, because the first one is not finished. Here are the two classes, written with constructor injection, and the configuration that wires them.

Cycles.java · broken design · Boot 4.2runs offline
    static class OrderService {
        final LoyaltyService loyalty;
        OrderService(LoyaltyService loyalty) { this.loyalty = loyalty; }
        int place(String who, int cents) { return cents - loyalty.discount(who, cents); }
        int countFor(String who) { return 3; }
    }
    static class LoyaltyService {
        final OrderService orders;
        LoyaltyService(OrderService orders) { this.orders = orders; }
        int discount(String who, int cents) { return orders.countFor(who) >= 3 ? cents / 10 : 0; }
    }

    @Configuration
    @ConditionalOnProperty(name = "demo", havingValue = "cycle")
    static class Broken {
        @Bean OrderService orderService(LoyaltyService l) { return new OrderService(l); }
        @Bean LoyaltyService loyaltyService(OrderService o) { return new LoyaltyService(o); }
        @Bean CommandLineRunner run(OrderService o, ApplicationContext ctx) { return Cycles.runner(o, ctx); }
    }
run --demo=cycle · Boot 4.2runs offline
# trimmed: log timestamps, pids and the first WARN line removed
***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  orderService defined in class path resource [com/quickbite/wiring/Cycles$Broken.class]
↑     ↓
|  loyaltyService defined in class path resource [com/quickbite/wiring/Cycles$Broken.class]
└─────┘


Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

The message is good. The box is the cycle: orderService needs loyaltyService (arrow down) which needs orderService (arrow up). Read it as a loop and you know exactly which two beans to look at. Longer cycles show more rows. The "Action" paragraph names the last resort, and we come back to why it is the last.

Why can Spring not just make one first? Picture it as two people each waiting for the other to hand over a finished object:

// illustrativeruns offline
create orderService   -> needs loyaltyService (as a finished object)
   create loyaltyService -> needs orderService (as a finished object)
      orderService is not finished yet -> nowhere to go

Now the fixes, from best to worst. Each is real code that ran.

Fix 1: extract the shared part (redesign)

The two services share one fact: how many orders a customer placed. That fact does not belong to either of them. Move it into a small third bean, OrderCounter. Now LoyaltyService depends on the counter, and OrderService depends on loyalty. The arrows run one way only.

Cycles.java · fix 1 · Boot 4.2runs offline
    static class OrderCounter { int countFor(String who) { return 3; } }
    static class OrderService2 {
        final LoyaltyService2 loyalty;
        OrderService2(LoyaltyService2 l) { this.loyalty = l; }
        int place(String who, int cents) { return cents - loyalty.discount(who, cents); }
    }
    static class LoyaltyService2 {
        final OrderCounter counter;
        LoyaltyService2(OrderCounter c) { this.counter = c; }
        int discount(String who, int cents) { return counter.countFor(who) >= 3 ? cents / 10 : 0; }
    }

    @Configuration
    @ConditionalOnProperty(name = "demo", havingValue = "cycle-extract")
    static class Extracted {
        @Bean OrderCounter orderCounter() { return new OrderCounter(); }
        @Bean OrderService2 orderService(LoyaltyService2 l) { return new OrderService2(l); }
        @Bean LoyaltyService2 loyaltyService(OrderCounter c) { return new LoyaltyService2(c); }

Cycle

Each service holds the other. Start-up fails.

Cycles.javaruns offline
OrderService(LoyaltyService loyalty)
LoyaltyService(OrderService orders)
// start-up: "form a cycle" 

Extracted

The shared fact moved to a third bean.

Cycles.javaruns offline
OrderService(LoyaltyService loyalty)
LoyaltyService(OrderCounter counter)
// start-up OK: costs 1800 

The shift: a one-way graph is something Spring can build in order.

Fix 2: replace a call with an event

Sometimes one side does not need an answer, it only needs to be told. When an order is placed, loyalty wants to add points. So OrderService publishes an OrderPlaced event and does not know who listens. LoyaltyService has an @EventListener method. Neither holds the other. Events are explained in section 07.

Cycles.java · fix 2 · Boot 4.2runs offline
    record OrderPlaced(String who, int cents) { }
    static class OrderService3 {
        final ApplicationEventPublisher events;
        OrderService3(ApplicationEventPublisher e) { this.events = e; }
        void place(String who, int cents) { events.publishEvent(new OrderPlaced(who, cents)); }
    }
    static class LoyaltyService3 {
        final Map<String, Integer> points = new HashMap<>();
        @EventListener void on(OrderPlaced e) { points.merge(e.who(), e.cents() / 100, Integer::sum); }
    }

    @Configuration
    @ConditionalOnProperty(name = "demo", havingValue = "cycle-event")
    static class ByEvent {
        @Bean OrderService3 orderService(ApplicationEventPublisher e) { return new OrderService3(e); }
        @Bean LoyaltyService3 loyaltyService() { return new LoyaltyService3(); }
        @Bean CommandLineRunner run(OrderService3 o, LoyaltyService3 l, ApplicationContext ctx) {
            return args -> { o.place("amy", 2000);
                             System.out.println("amy has " + l.points.get("amy") + " loyalty points");
                             System.exit(SpringApplication.exit(ctx)); };
        }
    }

Fix 3: @Lazy on one injection point

@Lazy on a parameter tells Spring: do not build the real bean now, inject a stand-in object (a proxy) that builds the real one on first use. That breaks the knot at start-up. But the cycle is still there. It is only hidden behind a proxy.

Cycles.java · fix 3 · Boot 4.2runs offline
    @Configuration
    @ConditionalOnProperty(name = "demo", havingValue = "cycle-lazy")
    static class LazyFix {
        @Bean OrderService orderService(@Lazy LoyaltyService l) { return new OrderService(l); }
        @Bean LoyaltyService loyaltyService(OrderService o) { return new LoyaltyService(o); }
        @Bean CommandLineRunner run(OrderService o, ApplicationContext ctx) { return Cycles.runner(o, ctx); }
    }

Last resort: allow circular references

The property spring.main.allow-circular-references=true lets Spring hand out a half-built bean early to break a cycle. It only works when the early bean can be injected after construction, which means setter or field injection. We try it twice: with the original constructor cycle, and with field injection.

Cycles.java · field-injection cycle · Boot 4.2runs offline
    static class OrderService4 {
        @Autowired LoyaltyService4 loyalty;
        int place(String who, int cents) { return cents - loyalty.discount(who, cents); }
        int countFor(String who) { return 3; }
    }
    static class LoyaltyService4 {
        @Autowired OrderService4 orders;
        int discount(String who, int cents) { return orders.countFor(who) >= 3 ? cents / 10 : 0; }
    }

    @Configuration
    @ConditionalOnProperty(name = "demo", havingValue = "cycle-allow-setter")
    static class AllowSetter {
        @Bean OrderService4 orderService() { return new OrderService4(); }
        @Bean LoyaltyService4 loyaltyService() { return new LoyaltyService4(); }
        @Bean CommandLineRunner run(OrderService4 o, ApplicationContext ctx) {
run · allow-circular-references=true · Boot 4.2runs offline
# 1. constructor cycle (--demo=cycle-allow-ctor --spring.main.allow-circular-references=true)
The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  orderService defined in class path resource [com/quickbite/wiring/Cycles$AllowCtor.class]
↑     ↓
|  loyaltyService defined in class path resource [com/quickbite/wiring/Cycles$AllowCtor.class]
└─────┘

Action:

Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.

# 2. field injection (--demo=cycle-allow-setter --spring.main.allow-circular-references=true)
order of 2000 cents costs 1800

# 3. the same field-injection cycle WITHOUT the property (--demo=cycle-allow-setter)
┌─────┐
|  orderService (field com.quickbite.wiring.Cycles$LoyaltyService4 com.quickbite.wiring.Cycles$OrderService4.loyalty)
↑     ↓
|  loyaltyService (field com.quickbite.wiring.Cycles$OrderService4 com.quickbite.wiring.Cycles$LoyaltyService4.orders)
└─────┘

What you see: with constructor injection, even the property cannot save you: Spring says the cycle "could not be broken". With field injection and the property on, the application starts and gives the right answer. With the same field-injection code and no property, it refuses to start. The property does not fix the design, it only changes how strictly Spring checks it.

Here are all four fixes with their real results.

The fixes, ranked
RankFixResult in the demoWhy this rank
1Extract the shared part into a third beanStarts. order of 2000 cents costs 1800Removes the cycle. The design now says what each class owns.
2Publish an event instead of calling backStarts. amy has 20 loyalty pointsRemoves the dependency. Costs some traceability: the call is hidden behind an event.
3@Lazy on one injection pointStarts. order of 2000 cents costs 1800Hides the cycle behind a proxy. A call made during start-up can still fail. The real problem stays.
4Setter or field injection plus allow-circular-references=trueStarts with fields. Still fails with constructors.Beans can be seen half-built. A global switch that hides every future cycle.

Idiom: break the cycle by moving the shared part, not by loosening the rules

The problem: two beans need each other. The tempting fixes are a global switch (allow-circular-references) or @Lazy everywhere. They make the error message go away and leave the tangle in place. The next developer adds a third bean to the loop and the failure moves.

How it works: a cycle is a sign that two classes share a responsibility that neither owns. Name that responsibility and give it a class, or turn a request into a notification. The graph becomes a one-way tree, and Spring can create the beans in order.

  1. Read the box: the failure message lists the exact beans in the loop. Start there.
  2. Ask what they share: a query, a counter, a rule. Extract it into a third bean that both depend on.
  3. Or ask who needs an answer: if one side only needs to be told, publish an event and delete the call.
  4. Only then consider @Lazy: for a genuine, documented case, on one injection point, with a comment saying why.

Without the idiom: the constructor cycle that does not start (the first run of this part). With the idiom: the extracted version, whose real output was order of 2000 cents costs 1800 with no property changes and no proxies. Both services still do their job.

Quick diagnosis: what to look at first

Symptoms from this section and the first thing to check
SymptomFirst checkTool
A value in the wrong environmentWhich source won the key?/actuator/env/<key>, section "property sources" above
A value in application-prod.yml is ignoredIs the prod profile active?activeProfiles in /actuator/env
Env var seems ignoredPrefix and words match exactly? (LIMIT versus LIMITS)The binding table above; make the field @NotBlank
An auto-configured bean is missing or unexpectedWhich condition said no?--debug or /actuator/conditions
Slow start-up or pod restart loopWhat runs in @PostConstruct?The numbered lifecycle log above
"form a cycle" at start-upWhich two beans are in the box?The failure message, then Fix 1 or 2

09 · PlatformLogging, Database Migrations and Developer Experience

Three things sit under every Spring service and decide how bad a bad day is: the logs you can read at 3 a.m., the database schema that must change without breaking the last deploy, and the dev tools that make a change visible in a second. This section covers structured JSON logging, changing log levels without a redeploy, trace ids, Flyway migrations (including a real checksum failure), DevTools and Docker Compose support.

At 19:40 on a Friday, QuickBite checkouts started failing for about one customer in fifty. The service ran on 12 pods. An engineer opened the log viewer, searched for the word payment, and got 31,000 lines. Each line looked like 2026-... INFO ... payment failed, will retry.

Which request did a line belong to? Which retry belonged to which customer? Lines from different requests were mixed, and a stack trace was split across 14 lines that the viewer showed as 14 separate entries. It took 40 minutes to find one failing request by hand.

The following Tuesday brought a different kind of pain. A developer fixed a typo in a migration file that had already run in production. The next deploy failed on every pod with a "checksum mismatch" and the rollout stopped. The service was fine, the database was fine, a text file had changed. We reproduce both problems below, with real output, and then show the fix for each.

Bridge: structured logging, one JSON object per line

A normal log line is a sentence for a human. A structured log line is a small JSON object, one per line, with named fields: time, level, logger, message, and any extra field you add. A log tool can filter on fields instead of searching words. Since Boot 3.4 this is built in. You switch it on with one property, and you do not change your log.info(...) calls.

First the program. It puts an order id into the MDC (mapped diagnostic context: a small map that the logging library attaches to every line written by the current thread), logs one line, and logs a warning with an exception.

LoggingDemo.java · Boot 4.2runs offline
    private static final Logger log = LoggerFactory.getLogger(LoggingDemo.class);

    @Bean
    CommandLineRunner logSome(ConfigurableApplicationContext ctx) {
        return args -> {
            MDC.put("orderId", "1042");                       // a field every line below should carry
            log.info("order placed, total {} cents", 2000);
            try {
                throw new IllegalStateException("payment gateway returned 503");
            } catch (IllegalStateException e) {
                log.warn("payment failed, will retry", e);
            }
            MDC.clear();
            System.exit(SpringApplication.exit(ctx));
        };
    }
}

We run it with the default format, with ecs (Elastic Common Schema, a widely used field naming) plus one extra field called team, and with logstash. Long lines are shortened: the stack trace is cut to 90 characters.

run --demo=logging · Boot 4.2 (trimmed)runs offline
--- plain text (default)
2026-12-02T00:57:00.730+05:30  INFO 1800903 --- [platform] [           main] [                                                 ] com.quickbite.platform.LoggingDemo       : order placed, total 2000 cen
2026-12-02T00:57:00.731+05:30  WARN 1800903 --- [platform] [           main] [                                                 ] com.quickbite.platform.LoggingDemo       : payment failed, will retry

java.lang.IllegalStateException: payment gateway returned 503
	at com.quickbite.platform.LoggingDemo.lambda$logSome$0(LoggingDemo.java:25) ~[!/:0.0.1-SNAPSHOT]
	at org.springframework.boot.SpringApplication.lambda$callRunner$1(SpringApplication.java:781) ~[spring-boot-4.2.0.jar!/:4.2.0]
--- ecs, with an extra field and without process/ecs blocks
{"@timestamp":"2026-12-01T19:27:05.109182368Z","log":{"level":"INFO","logger":"com.quickbite.platform.LoggingDemo"},"service":{"name":"platform","version":"0.0.1-SNAPSHOT"},"message":"order placed, total 2000 cents","orderId":"1042","team":"payments"}
{"@timestamp":"2026-12-01T19:27:05.109779799Z","log":{"level":"WARN","logger":"com.quickbite.platform.LoggingDemo"},"service":{"name":"platform","version":"0.0.1-SNAPSHOT"},"message":"payment failed, will retry","orderId":"1042","error":{"type":"java.lang.IllegalStateException","message":"payment gateway returned 503","stack_trace":"java.lang.IllegalStateException: payment gateway returned 503\n\tat com.quickbite.platform.L..."},"team":"payments"}
--- logstash
{"@timestamp":"2026-12-02T00:57:09.512335363+05:30","@version":"1","message":"order placed, total 2000 cents","logger_name":"com.quickbite.platform.LoggingDemo","thread_name":"main","level":"INFO","level_value":20000,"orderId":"1042"}

What you see: the plain line carries the text but not the order id: the default pattern does not print the MDC. The same event in ECS format carries orderId as its own field, the exception as error.type, error.message and error.stack_trace in one line, and our team field. The Logstash format has its own names (logger_name, level_value) but the same idea.

Why: a JSON formatter walks the log event instead of filling a text pattern. The MDC entries become fields, and the stack trace stays inside one string, so a log tool never splits it into 14 entries. The calls in your code stay the same: the format is a setting of the logging system, not of your code.

The formats Boot offers
FormatProperty valuePick it when
Elastic Common Schemalogging.structured.format.console=ecsYou send logs to Elastic, or your tool understands ECS names (log.level, error.stack_trace).
Logstash JSONlogging.structured.format.console=logstashYour pipeline already expects Logstash field names.
GELFlogging.structured.format.console=gelfYou use Graylog. (We did not run this format here.)
Plain text (default)nothing setA developer's laptop, where a person reads the console.

Three more settings are worth knowing. logging.structured.json.add.team=payments adds a fixed field to every line (good for team, region or version). logging.structured.json.exclude=process,ecs drops fields you do not want (we dropped two blocks in the run above). And you can write the same format to a file with logging.structured.format.file. For a custom layout, Boot lets you plug in your own formatter; check the reference documentation for your version.

Idiom: one JSON object per line, with the MDC as fields

The problem: log lines are sentences. A tool can only search words, a multi-line stack trace becomes many entries, and nothing ties a line to a request, a customer or an order.

How it works: turn on a structured format in production only. Put the identifiers that join lines (order id, customer id, trace id) in the MDC at the edge of a request, and clear them at the end. The formatter turns them into JSON fields that you can filter and group on.

  1. Switch the format on for production: set logging.structured.format.console through an environment variable or the production profile. Keep plain text for laptops.
  2. Set the join fields once: a servlet filter or interceptor sets MDC.put("orderId", ...) and clears it in a finally.
  3. Keep messages constant: write log.info("order placed, total {} cents", total), not string concatenation, so the same event always has the same message.
  4. Add the fixed fields: logging.structured.json.add.* for team, region, build.

Without the idiom: the plain-text run above. The order id is gone and the exception spans many lines. With the idiom: the ECS line has "orderId":"1042" and one line holds the whole exception. A search for orderId:1042 now returns exactly the lines of that order, from every pod.

Bridge: log levels, groups and the logging library underneath

A log level says how important a line is: TRACE, DEBUG, INFO, WARN, ERROR. A logger prints only lines at or above its level. Levels are set per logger name, and logger names are usually class names, so levels follow package names. Setting com.quickbite to INFO covers every class in that package and below.

The demo application keeps everything quiet and opens only its own packages. A group is a name for several loggers set together. Boot ships two, web and sql, and you can add your own.

# illustrative · application.propertiesruns offline
logging.level.root=warn                    # everything quiet by default
logging.level.com.quickbite=info           # our code at INFO
# a group: one name, several loggers
logging.group.quickbite-db=com.quickbite.platform.orders,org.flywaydb
logging.level.quickbite-db=debug           # turn the whole group to DEBUG
# built-in groups
logging.level.sql=debug                    # SQL statements (a lot of output)

Underneath, Spring Boot writes to the SLF4J API (the standard facade, the Logger class in the program above) and picks an implementation. Your code never names the implementation, so you can swap it.

Logback or Log4j2
OptionPick it whenCost or catch
Logback (Boot default)You want it to just work. Structured logging, groups and the actuator endpoint are all tested against it.Asynchronous logging needs an explicit async appender; at very high log volume it can become a bottleneck.
Log4j2 (spring-boot-starter-log4j2, exclude the default logging starter)You log at very high volume and want its asynchronous loggers, or the rest of your company uses it.A second set of configuration files. Mixing both on the classpath causes confusing duplicate bindings, so exclude one properly. We did not run Log4j2 for this chapter; check the reference documentation for your version.
Neither: log to standard output and let the platform ship itYou run on Kubernetes (the normal case).Not an alternative to the two above, a deployment rule: write to the console, one JSON object per line, and let the node agent collect it. See E10.

Bridge: changing a log level in production without a redeploy

Back to the Friday outage. The team wanted DEBUG for the payment package, now, on 12 pods, without a deploy that would restart the pods and perhaps hide the failure. Actuator has an endpoint for exactly this: /actuator/loggers. A GET reads a level. A POST with a JSON body changes it in memory, immediately.

We start the demo as a web service on a free port with only the loggers endpoint exposed. The script reads the level, calls an endpoint that logs at INFO and DEBUG (only INFO appears), switches the package to DEBUG, calls again (both appear), and puts it back. The log lines at the bottom are the application's own output in ECS format.

run-loglevel.sh · Boot 4.2 (@timestamp removed from the log lines)runs offline
$ curl -s localhost:18412/actuator/loggers/com.quickbite.platform
{"effectiveLevel":"INFO"}
$ curl -s localhost:18412/orders/1042      # DEBUG is off
order 1042
$ curl -i -X POST localhost:18412/actuator/loggers/com.quickbite.platform -H "Content-Type: application/json" -d {"configuredLevel":"DEBUG"}
HTTP/1.1 204 
$ curl -s localhost:18412/actuator/loggers/com.quickbite.platform
{"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"}
$ curl -s localhost:18412/orders/1043      # DEBUG is on
order 1043
$ curl -X POST ... -d {"configuredLevel":null}   # put it back
{"effectiveLevel":"INFO"}
--- log lines of the app (orders only)
{"log":{"level":"INFO","logger":"com.quickbite.platform.OrderController"},"message":"order 1042 found, total 2000 cents","traceId":"2d9b45ef931e60b65c1dcd0aa940f0c5","spanId":"838c011eb8eb9f5d"}
{"log":{"level":"DEBUG","logger":"com.quickbite.platform.OrderController"},"message":"loading order 1043 from the database","traceId":"e34fdfbd79d9830a5652811d5b9eca41","spanId":"436b3859cb78c326"}
{"log":{"level":"INFO","logger":"com.quickbite.platform.OrderController"},"message":"order 1043 found, total 2000 cents","traceId":"e34fdfbd79d9830a5652811d5b9eca41","spanId":"436b3859cb78c326"}
{"log":{"level":"INFO","logger":"com.quickbite.platform.OrderController"},"message":"order 1044 found, total 2000 cents","traceId":"da3c8eac7f7c24e67eb7bb3e964124cf","spanId":"e3bf7febd9deaa04"}

What you see: the first GET reports effectiveLevel: INFO and no configuredLevel, meaning no explicit setting. The POST returns 204 (no body, it worked). The next GET shows DEBUG both configured and effective. The second request logged a DEBUG line (loading order 1043 from the database) that the first request did not. After setting configuredLevel to null the package went back to INFO, and request 1044 logged only the INFO line.

Why: a logger holds a level in memory. The endpoint calls the logging system and changes that field, so no restart is involved. That is also the limit: the change exists only in this process. A restart forgets it, and each pod needs its own call.

Idiom: raise one logger to DEBUG at runtime, then put it back

The problem: you need DEBUG output from one package on live pods. A redeploy with a different property takes minutes, restarts the pods (and so may remove the faulty state), and then must be undone with another deploy.

How it works: expose the loggers endpoint on a protected management port. POST a level for the narrowest logger that covers the problem. Collect the evidence. Set configuredLevel back to null (or the old level) as soon as you are done.

  1. Narrow first: pick com.quickbite.payments, not root. DEBUG on the root logger writes thousands of lines per second and can itself cause the next outage.
  2. Hit every pod: the change is per process. Loop over the pods, and note the time you turned it on.
  3. Collect the evidence: filter the JSON logs on the logger name and the trace id of the failing request.
  4. Put it back: a null level removes your explicit setting. Pods that restart forget it anyway.
# illustrative: all pods of one deployment (Kubernetes, curl from inside the cluster)runs offline
for pod in $(kubectl get pods -l app=orders -o name); do
  kubectl exec "$pod" -- curl -s -X POST localhost:9090/actuator/loggers/com.quickbite.payments \
    -H 'Content-Type: application/json' -d '{"configuredLevel":"DEBUG"}'
done

Now the part that matters as much as the trick: secure it. An endpoint that changes behaviour is a write endpoint. Anyone who can reach it can turn on DEBUG everywhere, fill the disks, and read sensitive details from the extra output. Four rules.

  1. Expose only what you need: management.endpoints.web.exposure.include=health,loggers, never the wildcard *.
  2. Use a separate management port: management.server.port=9090, bound to an address the public ingress does not route to.
  3. Authenticate: with Spring Security, restrict /actuator/loggers/** to an operator role, see E4 production behaviour.
  4. Audit it: a level change is an operation. Log who made it (the audit starter from the previous section would do).
# illustrative · application.propertiesruns offline
management.endpoints.web.exposure.include=health,loggers
management.server.port=9090
management.server.address=127.0.0.1

Bridge: trace ids, so a line can find its request

Structured logs let you filter. A trace id lets you follow one request across services. A trace is the full journey of one user request. It is split into spans, each a unit of work such as one HTTP call.

Every span has a span id, and all spans of one request share the trace id. If every log line carries the current trace id, then the line from the payment service and the line from the order service for the same customer request can be joined with one search.

In Boot 4 the tracing part is a starter, spring-boot-starter-opentelemetry. It brings Micrometer Tracing with an OpenTelemetry bridge. When a request arrives, Boot starts a span, and the logging system puts traceId and spanId into the MDC for that thread.

We only need to remove what we do not have: a collector to send spans to. This machine has none, so the properties below switch every exporter off, and raise sampling to 100 percent. (The default samples only about 10 percent of requests, so most lines would carry no trace id.)

application.properties · Boot 4.2runs offline
# OpenTelemetry stays on, nothing is sent anywhere
management.otlp.metrics.export.enabled=false
management.tracing.export.otlp.enabled=false
management.logging.export.otlp.enabled=false
# sample every request (the default is a fraction)
management.tracing.sampling.probability=1.0

We start the web service and send two requests. The second carries a standard traceparent header (the W3C format that another service would send), so we can check that Boot joins the existing trace instead of starting a new one. The first line is the script's readiness check.

run-trace.sh · Boot 4.2runs offline
$ curl -s localhost:18414/orders/1042
order 1042
$ curl -s localhost:18414/orders/1043 -H "traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
order 1043
--- app log (trimmed to the order lines, timestamps and pids removed)
INFO [6c5a0b45653fb58431caa3566e79ac7c-f7030f4bdedc1afc] order 0 found, total 2000 cents
INFO [c82c52b3d91be69d9dbc6200a2e907d3-dbf813acca9d5022] order 1042 found, total 2000 cents
INFO [4bf92f3577b34da6a3ce929d0e0e4736-c5991e1e7958eed6] order 1043 found, total 2000 cents

What you see: each log line now has a bracket with traceId-spanId. Requests with no header got fresh ids. The request that arrived with traceparent: 00-4bf92f35...-...-01 logged the same trace id, 4bf92f3577b34da6a3ce929d0e0e4736, with a new span id of its own. In the ECS run from the previous bridge the same ids appeared as traceId and spanId fields next to orderId.

Why: the web server's observation reads the traceparent header and continues that trace, and the logging system copies the ids into the MDC for the duration of the request. A client that calls the next service forwards the header, which is how one id spans many services.

Three limits. First, the ids reach the log only on the thread that handles the request. Work you hand to an executor needs the MDC copied across (section 05 shows the decorator). Second, this demo proves that ids appear in logs.

Spans reach a backend such as Tempo or Jaeger only when you enable an exporter and point it at a collector, which we did not do here. Third, the names of the fields differ by format: in the ECS output we saw plain traceId and spanId keys, not the ECS names trace.id and span.id, so check your log tool's mapping.

Bridge: Flyway in Boot 4, the schema as ordered files

A database schema changes over time: a table, a column, an index. With nothing in charge, every environment drifts. Flyway makes the schema a list of numbered SQL files. On start-up it looks at a table it keeps in the database (the history table), finds the files not yet applied, runs them in order, and records each one with a checksum (a number computed from the file's content).

Next time, it recomputes the checksum of every applied file and compares it with the stored one. That check is called validation, and it is what failed on the Tuesday in our story.

Boot 4 split the starters into modules (see section 11), so Flyway comes as spring-boot-starter-flyway. Boot auto-configures it, runs it before the JPA layer starts, and the migration strategy hook lives in the package org.springframework.boot.flyway.autoconfigure, which we compiled against below.

For databases such as PostgreSQL or MySQL you also add the matching Flyway database module (for example flyway-database-postgresql). Flyway printed one warning for the H2 database used here, that H2 2.5 is newer than the version Flyway has verified. It still worked.

Naming rules for migration files
KindName patternRule
VersionedV1__create_orders.sqlLetter V, version, two underscores, description. Runs once, in version order. Versions compare as numbers: V2 comes before V10.
RepeatableR__order_summary_view.sqlNo version. Runs again whenever its checksum changes, after all versioned ones. Good for views and procedures.
UndoU1__...Part of a paid edition. We do not use it: see the idiom below.
Locationclasspath:db/migration (default)Change with spring.flyway.locations. Our demo uses a plain folder so we can edit files without a rebuild.

Our three files. The first creates the table, the second adds a column, the third is a repeatable view.

migrations/V1__create_orders.sql · Flyway 12runs offline
create table orders (
    id          bigint primary key,
    customer    varchar(40) not null,
    total_cents int         not null
);
migrations/V2__add_status.sql · Flyway 12runs offline
alter table orders add column status varchar(20) default 'NEW' not null;
migrations/R__order_summary_view.sql · Flyway 12runs offline
create or replace view order_summary as
    select status, count(*) as orders, sum(total_cents) as cents
    from orders
    group by status;

The demo runs the application six ways against one H2 file database (so it remembers between runs). The runner prints the history table at the end. First run, on an empty database:

run-flyway.sh · run 1 · Boot 4.2 (log prefixes trimmed)runs offline
INFO org.flywaydb.core.FlywayExecutor         : Database: jdbc:h2:file:./target/flywaydb (H2 2.5)
INFO o.f.c.i.s.JdbcTableSchemaHistory         : Schema history table "PUBLIC"."flyway_schema_history" does not exist yet
INFO o.f.core.internal.command.DbValidate     : Successfully validated 3 migrations (execution time 00:00.021s)
INFO o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table "PUBLIC"."flyway_schema_history" ...
INFO o.f.core.internal.command.DbMigrate      : Current version of schema "PUBLIC": << Empty Schema >>
INFO o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version "1 - create orders"
INFO o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version "2 - add status"
INFO o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" with repeatable migration "order summary view"
INFO o.f.core.internal.command.DbMigrate      : Successfully applied 3 migrations to schema "PUBLIC", now at version v2 (execution time 00:00.016s)
rank  version  description          type  checksum     success
-1    null     << Flyway Schema History table created >> TABLE null         true
1     1        create orders        SQL   1934866666   true
2     2        add status           SQL   292701503    true
3     null     order summary view   SQL   1572893498   true

What you see: Flyway found no history table and created one. It applied version 1, version 2, then the repeatable view, and says "now at version v2". The history table has one row for each file with its checksum. The first row, rank -1, is Flyway's own marker that it created the table. The repeatable migration has no version (null) but has a rank and a checksum like the others.

Now the Tuesday incident. Someone notices that new orders should start as PLACED, not NEW, and edits the old file in place. One word changes. The next deploy starts the application against the same database:

run-flyway.sh · run 2 · Boot 4.2 (trimmed)runs offline
$ sed -i "s/'NEW'/'PLACED'/" migrations/V2__add_status.sql
$ cat migrations/V2__add_status.sql
alter table orders add column status varchar(20) default 'PLACED' not null;

$ start the application again  (stack trace and the 200-character bean-creation prefix trimmed)
ERROR o.s.boot.SpringApplication               : Application run failed
...flywayInitializer ...: Validate failed: Migrations have failed validation
Migration checksum mismatch for migration version 2
-> Applied to database : 292701503
-> Resolved locally    : -1700206075
Either revert the changes to the migration, or run repair to update the schema history.

What you see: the application does not start. Validation compared two numbers for version 2: 292701503 stored in the database when the file was first applied, and -1700206075 computed from the file now. They differ, so Flyway stops. It names the migration, shows both numbers and offers two ways out: revert the file, or run repair. The error appears inside the bean flywayInitializer, which the JPA layer waits for, so nothing else starts.

Why: Flyway cannot tell whether your edit matters. It only knows that a file it already ran has changed. The database where the old version ran still has NEW as the default, and changing the file would not change that database. Different environments would then disagree about what "version 2" means. Stopping is the safe answer.

Which way out is right? Flyway offers two. The first is to revert the file byte for byte and add the change as a new migration. The second is repair, which rewrites the stored checksum to match the file. Repair does not run the changed SQL. So after a repair on a real change, the file says one thing and the database holds another.

We do the first: restore version 2 and add V3__default_status_placed.sql, which changes the default going forward.

Edit in place

Rewrites history. Every database that ran V2 now disagrees with the file.

V2__add_status.sql (edited)runs offline
alter table orders add column status
  varchar(20) default 'PLACED' not null;
-- checksum changed: start-up stops

Forward only

V2 stays byte for byte. A new file carries the change.

V3__default_status_placed.sql (new)runs offline
alter table orders alter column status
  set default 'PLACED';
-- next version: applied once, in order

The shift: a change in meaning is a new migration, never a new version of an old one.

migrations/V3__default_status_placed.sql · Flyway 12runs offline
alter table orders alter column status set default 'PLACED';
run-flyway.sh · run 3 · Boot 4.2 (log prefixes trimmed)runs offline
WARN s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/hibernate/autoconfigure/HibernateJpaConfiguration.class]: Failed to initialize dependency 'flywayInitializer' of LoadTimeWeaverAware bean 'entityManagerFactory': Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration$FlywayConfiguration.class]: Validate failed: Migrations have failed validation
Migration checksum mismatch for migration version 2
-> Applied to database : 292701503
-> Resolved locally    : -1700206075
Either revert the changes to the migration, or run repair to update the schema history.
Need more flexibility with validation rules? Learn more: https://help.red-gate.com/help/flyway-cli12/help_11.aspx?topic=flyway-blog/older-posts/customize-validation-rules-with-ignoremigrationpatterns
ERROR o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/hibernate/autoconfigure/HibernateJpaConfiguration.class]: Failed to initialize dependency 'flywayInitializer' of LoadTimeWeaverAware bean 'entityManagerFactory': Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration$FlywayConfiguration.class]: Validate failed: Migrations have failed validation
Migration checksum mismatch for migration version 2
-> Applied to database : 292701503
-> Resolved locally    : -1700206075
Either revert the changes to the migration, or run repair to update the schema history.
Need more flexibility with validation rules? Learn more: https://help.red-gate.com/help/flyway-cli12/help_11.aspx?topic=flyway-blog/older-posts/customize-validation-rules-with-ignoremigrationpatterns
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-7.1.0.jar!/:7.1.0]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:203) ~[spring-beans-7.1.0.jar!/:7.1.0]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:978) ~[spring-context-7.1.0.jar!/:7.1.0]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:622) ~[spring-context-7.1.0.jar!/:7.1.0]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742) ~[spring-boot-4.2.0.jar!/:4.2.0]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:431) ~[spring-boot-4.2.0.jar!/:4.2.0]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:309) ~[spring-boot-4.2.0.jar!/:4.2.0]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354) ~[spring-boot-4.2.0.jar!/:4.2.0]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-4.2.0.jar!/:4.2.0]
	at com.quickbite.platform.PlatformApplication.main(PlatformApplication.java:9) ~[!/:0.0.1-SNAPSHOT]
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:565) ~[na:na]
	at org.springframework.boot.loader.launch.Launcher.launch(Launcher.java:94) ~[platform-0.0.1-SNAPSHOT.jar:0.0.1-SNAPSHOT]

The database was at version 2. Flyway validated four files (the four checksums all matched), applied only version 3, and the history table has a fourth row. The old pods and the new pods now agree, and the history tells the whole story.

Repair has a legitimate use: a tool changed a file without changing its meaning. Line endings change when a file is checked out on another operating system. An IDE reformats the whitespace. Even a comment changes the checksum, because the checksum covers the text, not the meaning. To try it, we add one comment line to version 2 and run with a migration strategy that calls repair() before migrate().

FlywayMigrationStrategy · FlywayDemo.java · Boot 4.2runs offline
    @Bean
    @ConditionalOnProperty(name = "repair", havingValue = "true")
    FlywayMigrationStrategy repairThenMigrate() {
        return (Flyway flyway) -> {
            System.out.println("repair: " + flyway.repair().repairActions);
            flyway.migrate();
        };
    }
run-flyway.sh · run 4 with --repair=true · Boot 4.2 (log prefixes trimmed)runs offline
INFO o.f.c.i.s.JdbcTableSchemaHistory : Repairing Schema History table for version 2
      (Description: add status, Type: SQL, Checksum: -6469213)  ...
INFO o.f.core.internal.command.DbRepair : Successfully repaired schema history table
INFO o.f.core.internal.command.DbValidate : Successfully validated 4 migrations
INFO o.f.core.internal.command.DbMigrate : Schema "PUBLIC" is up to date. No migration necessary.
rank  version  description          type  checksum     success
2     2        add status           SQL   -6469213     true

What you see: repair rewrote the stored checksum of version 2 from 292701503 to -6469213 (because a comment was added), validation then passed, and nothing needed migrating. Repair is a database edit. Run it deliberately, once, with the cause known, and record why. Never put it into the start-up of a production service.

Figure 22.16 shows the shape of a healthy migration history, and the pattern QuickBite uses when a change would break the running version.

Migrations go forward only; risky changes are split into expand and contract Migration files (applied once, never edited) V1 create orders V2 add status V3 new default V4 new column V5 backfill V6 drop old one Application versions running app v1 (reads and writes the old column) app v2 (writes both, then only the new column) EXPAND (V4): add the new column. v1 ignores it. OVERLAP: during a rolling deploy both versions run. BACKFILL (V5): copy old values into the new column. CONTRACT (V6): only after v1 is gone. Dropping earlier breaks v1. time
Fig. 22.16 — A forward-only history. Files V1 to V3 are ordinary steps. The column change is split into three migrations so that the old and new application versions both work while the rolling deploy is in progress. Nothing already applied is ever edited. The same pattern is taught for Python services in E20 (expand and contract migration).

Idiom: forward-only migrations, never edit an applied file

The problem: a migration that already ran somewhere (production, a colleague's database, the staging server) is edited in place. The file and the databases now disagree, the checksum check stops every pod, and a "quick fix" with repair leaves production and the source code describing different schemas.

How it works: treat an applied migration as history. History is not edited. To change what a migration did, add a new, higher-numbered migration that does it. For a change that would break the running version, split it into expand, migrate and contract over several releases.

  1. Add, do not edit: a mistake in V2 is fixed by V3. The old file stays as it was, byte for byte.
  2. Expand first: add the new column or table in a way the running version ignores (nullable, with a default).
  3. Contract last: drop the old column in a later release, after no running version reads it.
  4. Keep repair for tooling accidents: line endings, whitespace, a comment. Never for a change in meaning.

Without the idiom: run 2 above, a stopped deployment from a one-word edit. With the idiom: run 3, where the change arrived as V3, the old files kept their checksums, and the deploy finished with one new row in the history.

Flyway or Liquibase
OptionPick it whenCost or catch
FlywayYour team writes SQL and wants the least ceremony: files, numbers, one history table. The Boot default.Undo scripts are in a paid edition. Changes that depend on the database vendor are written per vendor as separate files.
LiquibaseYou need rollback tags, preconditions, contexts and labels, or one changelog that targets several database vendors. It can also diff two databases.More concepts (changelog, changeset, contexts). Changesets are identified by id, author and file, and a changed changeset also fails validation by checksum. We did not run Liquibase for this chapter; check the reference documentation for your version.
Hibernate ddl-autoA throw-away test database.It guesses a diff and cannot express data changes. Never use it to evolve a production schema.
Hand-run SQL scriptsAlmost never.No history, no checksum, no order. Environments drift silently.

Both tools solve the same problem, and the idiom applies to both. The checksum check is not a Flyway quirk. It is the tool's way of defending the rule "history is not edited".

Bridge: DevTools, restart in half a second

Restarting a Spring application after every change costs you the whole start-up: 4 to 7 seconds on this machine. DevTools (spring-boot-devtools) cuts most of it. It starts the application with two class loaders. A class loader is the part of the JVM that reads .class files.

The base loader holds libraries that never change (Spring, Hibernate, Tomcat). The restart loader holds your own classes. When a class file in your project changes, DevTools throws away only the restart loader, builds a new one and starts the application again. The libraries stay loaded, so the new start is much faster than a cold one.

Three more features come with it. A LiveReload server (port 35729 by default) that a browser extension can use to refresh the page. Property defaults: caches such as template caching are switched off, and more web logging is enabled, so a change shows up at once. And remote support, which we do not recommend. The dependency goes in with optional so it never reaches other projects.

pom.xml excerpt · Boot 4.2runs offline
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

To see the restart, we start a tiny web application with spring-boot:run (which uses the project's class folder, the setting DevTools watches). We call /hello, change the text in the source, recompile with Maven, and call again. The log lines below are the real ones, with timestamps and process ids removed.

run via spring-boot:run · Boot 4.2 (trimmed)runs offline
# measured on the course machine (12 cores); your numbers will differ
INFO [restartedMain] Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
INFO [restartedMain] Started DevApplication in 4.624 seconds (process running for 5.239)
$ curl -s localhost:18413/hello
hello from restart 1
# change the string in DevApplication.java, then:  ./mvnw -o -q compile
INFO [File Watcher] Restarting due to 1 class path change (0 additions, 1 deletion, 0 modifications)
INFO [restartedMain] Started DevApplication in 0.672 seconds (process running for 11.232)
INFO [File Watcher] Restarting due to 1 class path change (1 addition, 0 deletions, 0 modifications)
INFO [restartedMain] Started DevApplication in 0.477 seconds (process running for 13.146)
$ curl -s localhost:18413/hello
hello from restart 2

What you see: the first start took 4.6 seconds. After the recompile, the file watcher reported a class path change and started again in 0.67 and then 0.48 seconds, roughly ten times faster. The thread name changed to restartedMain, which tells you DevTools is in charge. The recompile logged two restarts, a deletion and then an addition, because Maven deleted the class file and wrote a new one. An IDE that overwrites in place usually triggers one.

Why must DevTools never reach production? Its property defaults turn off caches and add logging. Its restart machinery watches the disk for changes. Its remote feature is an extra door into the process. Boot protects you in two ways. DevTools disables itself when the application runs from a fully packaged jar, and the Maven plugin leaves it out of the jar in the first place. We checked the second one, for the DevTools project and for the Docker Compose one:

run in each project · Boot 4.2runs offline
$ unzip -l target/devtools-0.0.1-SNAPSHOT.jar | grep -c "spring-boot-devtools"
0
$ unzip -l target/dockercompose-0.0.1-SNAPSHOT.jar | grep -c "spring-boot-docker-compose"
0

The count is zero for both: the packaged jars do not contain spring-boot-devtools or spring-boot-docker-compose, although both are listed in the poms. The Spring Boot Maven plugin leaves these two out by default. The count of zero is a check you can add to a build.

Bridge: Docker Compose support and Testcontainers

A developer who clones QuickBite should not need to install PostgreSQL. The team keeps a compose.yaml in the project root. With spring-boot-docker-compose on the classpath, Boot finds that file at start-up, runs docker compose up for it, waits until the containers are healthy, and then creates the connection settings itself, so there is no spring.datasource.url to write. When the application stops, Boot stops the containers.

compose.yaml · Docker Composeruns offline
services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: quickbite
      POSTGRES_USER: quickbite
      POSTGRES_PASSWORD: secret
    ports:
      - "5432"          # only the container port: Docker picks a free host port

Only the container port is given ("5432"). Docker picks a free port on your machine, so two projects cannot clash. The application has no datasource properties at all. Its runner prints the JDBC URL it was given, the server version, and does a tiny write.

ComposeApplication.java · Boot 4.2runs offline
    @Bean
    CommandLineRunner check(DataSource ds, JdbcTemplate jdbc, ConfigurableApplicationContext ctx) {
        return args -> {
            try (var c = ds.getConnection()) {
                System.out.println("JDBC url     : " + c.getMetaData().getURL());
            }
            System.out.println("server       : " + jdbc.queryForObject("select version()", String.class).substring(0, 22));
            jdbc.execute("create table if not exists orders (id bigint primary key, total_cents int not null)");
            jdbc.update("insert into orders values (1042, 2000) on conflict do nothing");
            System.out.println("orders table : " + jdbc.queryForObject("select count(*) from orders", Integer.class) + " row(s)");
            System.exit(SpringApplication.exit(ctx));
        };
    }

We found a trap on the way. The first attempt used java -jar on the packaged jar. It failed, because the jar has no Docker Compose support (see the check above):

java -jar target/dockercompose-0.0.1-SNAPSHOT.jar · Boot 4.2runs offline
$ java -jar target/dockercompose-0.0.1-SNAPSHOT.jar
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class

Compose support is a development feature. We run it with spring-boot:run, the way a developer would from the command line. The log lines come from Boot's Docker Compose module; the last three lines are our runner. The Postgres image (postgres:16-alpine) was already on this machine, so no download happened.

./mvnw -o spring-boot:run · Boot 4.2 (trimmed)runs offline
INFO .s.b.d.c.l.DockerComposeLifecycleManager : Using Docker Compose file /home/iam100god/Desktop/AI_COURSE/code/e22-spring-in-depth/D/dockercompose/compose.yaml
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Creating 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Created 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Starting 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Started 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Waiting 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Healthy 
INFO c.quickbite.compose.ComposeApplication   : Started ComposeApplication in 6.068 seconds (process running for 6.367)
JDBC url     : jdbc:postgresql://127.0.0.1:32800/quickbite?ApplicationName=dockercompose
server       : PostgreSQL 16.14 on x8
orders table : 1 row(s)

What you see: Boot announced the compose file, created the container, waited for it to be Healthy, and then started the application in about 6 seconds. The application got jdbc:postgresql://127.0.0.1:32800/quickbite.

The port 32800 is the free host port Docker picked, and the user and password came from the compose file's environment, never from a property. The server is PostgreSQL 16. On exit Boot stopped the container. We then ran docker compose down -v to remove it, so nothing is left running.

How does Boot know the settings? It looks at the image name (postgres) and reads the container's environment and mapped ports, then produces a connection details object that the datasource auto-configuration uses in place of properties. The setting spring.docker.compose.lifecycle-management chooses between none, start-only and start-and-stop (the default we saw). Compose support is skipped in tests by default; check the reference documentation for the exact switch in your version.

Testcontainers solves the same problem from the test side. A test declares a container as a field. Boot starts it before the test and stops it afterwards. The annotation @ServiceConnection plays the role that compose support played above: it turns the running container into connection details, so a test needs no URL either.

The code below shows the shape. We did not run it: this machine works offline, and the PostgreSQL module of Testcontainers version 2 is not in its local Maven cache. Package and artifact names changed between Testcontainers 1 and 2, so check the reference documentation for your version before copying it.

# illustrative · TestApplication.java (not run offline)runs offline
@TestConfiguration(proxyBeanMethods = false)
class TestcontainersConfig {

    @Bean
    @ServiceConnection              // container -> datasource connection details
    PostgreSQLContainer postgres() {
        return new PostgreSQLContainer("postgres:16-alpine");
    }
}

// a "dev-time" main that starts the real app WITH the container:
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.from(QuickBiteApplication::main)
            .with(TestcontainersConfig.class)
            .run(args);
    }
}
Docker Compose support or Testcontainers or something else
OptionPick it whenCost or catch
Docker Compose supportDevelopers run the whole app locally and want the same services (database, broker, cache) as the team, from one file that is also usable outside Spring.Needs Docker and the compose plugin on every laptop. The jar does not include it. Containers keep state between runs unless you down -v.
Testcontainers with @ServiceConnectionTests need a real database or broker, started and removed for you. Also good for a "dev mode" main class.Needs Docker. Slower than an in-memory database. Containers start per test class unless shared.
H2 or another in-memory databaseFast unit-style tests that do not depend on vendor behaviour.It is not PostgreSQL. SQL dialect and locking differences hide real bugs until production.
A shared dev databaseAlmost never.Everyone changes the same data, migrations collide, and the property precedence story at the top of this chapter happens again.

Put together: the same Postgres 16 image can serve three jobs, a developer's run (compose support), a test (Testcontainers) and, with the real server in production, the database that Flyway migrates. The migrations are identical in all three, which is the point of making the schema a list of files.

Section 09 is the platform under your service: JSON logs you can query, a log level you can change at 3 a.m., a trace id that joins lines, a schema that only moves forward, a restart that takes half a second and a database that starts itself. The next section moves up a level, to servers that push events, messages, batches and the wider Spring ecosystem.

10 · Web extras, messaging, batch and the Spring ecosystemWeb Extras, Messaging, Batch and the Spring Ecosystem

This section covers the pieces around a Spring web service that E4 skipped: pushing live updates (server-sent events and WebSocket), the order in which filters, interceptors and argument resolvers run, file uploads, declarative HTTP clients, messaging, Spring Batch for big imports, Spring Modulith for keeping a monolith tidy, and which Spring Cloud parts still matter on Kubernetes. Everything that prints below ran on Spring Boot 4.2.0 and Java 25.

Start with QuickBite's order-tracking page. After a customer places an order, the page asks the server "what is the status now?" once every second. It looked fine with 50 customers. On a rainy Friday there were 1,200 tracking pages open at the same time, so the page alone sent 1,200 requests a second.

The rest of the API handled about 1,800 requests a second. So 1,200 of 3,000 total requests, 40 percent of all traffic, were tracking pages asking a question whose answer had not changed. Each order changes status about five times in 40 minutes. A page that polls every second therefore asks around 2,400 times to hear 5 pieces of news.

The fix was server-sent events, usually shortened to SSE. The page opens one connection. The server writes a line into that connection each time the status changes. Nothing is sent when nothing happens. Traffic from the tracking page dropped from 1,200 requests a second to about 1,200 open connections that were mostly quiet. Let us build it and watch it with curl.

Bridge: server-sent events, one level down

HTTP normally works like a phone call that ends after one question and one answer. The client sends a request, the server sends a response, and the connection is finished. Server-sent events change one thing: the server does not finish the response. It sends a header that says Content-Type: text/event-stream, then keeps writing small text messages into the same response for as long as it likes.

An SSE message is plain text. A line that starts with data: carries the payload. A line that starts with id: gives the message a number. A line that starts with event: gives it a name. A line that starts with a colon is a comment: browsers ignore it, so it is a safe way to keep the connection busy. A blank line ends one message.

In Spring MVC the class for this is SseEmitter. The controller method returns an emitter right away, so the request thread goes back to the pool. Another thread (here, a virtual thread, see E21 virtual threads) keeps the emitter and calls send(...) whenever something happens. Calling complete() closes the response.

The setup: one endpoint, GET /orders/{id}/status. It pushes the five states of an order. After each state it waits 400 ms, sends a heartbeat comment, and waits another 400 ms. A real kitchen takes minutes, not 800 ms, and the sleeps stand in for that.

OrderStatusController.java · Boot 4.2runs offline
package com.quickbite.web;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class OrderStatusController {
    private final ExecutorService pusher = Executors.newVirtualThreadPerTaskExecutor();
    private static final List<String> STATES =
            List.of("PLACED", "ACCEPTED", "COOKING", "OUT_FOR_DELIVERY", "DELIVERED");

    @GetMapping(path = "/orders/{id}/status", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter status(@PathVariable long id) {
        SseEmitter emitter = new SseEmitter(30_000L);          // give up after 30 s
        emitter.onTimeout(() -> System.out.println("[sse] timeout, order " + id));
        emitter.onCompletion(() -> System.out.println("[sse] completed, order " + id));
        pusher.submit(() -> {
            try {
                int n = 1;
                for (String s : STATES) {
                    emitter.send(SseEmitter.event().id(String.valueOf(n++)).name("status")
                            .data("{\"order\":" + id + ",\"status\":\"" + s + "\"}"));
                    Thread.sleep(400);
                    emitter.send(SseEmitter.event().comment("heartbeat"));   // keeps proxies awake
                    Thread.sleep(400);
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);                  // client left: stop pushing
            }
        });
        return emitter;
    }
}

Three details matter here. The 30_000L given to the emitter is a timeout in milliseconds: after 30 seconds without completion, Spring ends the request. The onTimeout and onCompletion callbacks let us log what happened. And the catch block calls completeWithError, because if the customer closes the tab, the next send throws an IOException, and that is our signal to stop pushing.

Make the invisible visible: start the app, call the endpoint with curl -N (the -N flag turns off curl's own output buffering, so each event appears the moment it arrives) and print the time of every line. The -i flag adds the response headers so you can see the content type.

curl · Boot 4.2runs offline
$ curl -sNi localhost:18081/orders/42/status
# prefixed with seconds since the request started
  0.0s  HTTP/1.1 200 
  0.0s  Content-Type: text/event-stream
  0.0s  Transfer-Encoding: chunked
  0.0s  Date: Tue, 01 Dec 2026 19:04:47 GMT
  0.0s  
  0.0s  id:1
  0.0s  event:status
  0.0s  data: {"order":42,"status":"PLACED"}
  0.1s  
  0.4s  :heartbeat
  0.4s  
  0.8s  id:2
  0.8s  event:status
  0.8s  data: {"order":42,"status":"ACCEPTED"}
  0.8s  
  1.2s  :heartbeat
  1.2s  
  1.6s  id:3
  1.6s  event:status
  1.6s  data: {"order":42,"status":"COOKING"}
  1.6s  
  2.0s  :heartbeat
  2.0s  
  2.4s  id:4
  2.4s  event:status
  2.4s  data: {"order":42,"status":"OUT_FOR_DELIVERY"}
  2.4s  
  2.8s  :heartbeat
  2.8s  
  3.2s  id:5
  3.2s  event:status
  3.2s  data: {"order":42,"status":"DELIVERED"}
  3.2s  
  3.6s  :heartbeat
  3.6s  

What you see: one HTTP request returned 200 and a text/event-stream body with no Content-Length (the chunked encoding means "more may come"). The five statuses arrived at 0.0, 0.8, 1.6, 2.4 and 3.2 seconds, and a :heartbeat comment arrived halfway between them. After the last one the server ended the response.

Why: Spring holds the response open and flushes every send to the network. The heartbeat is not for the browser. It is for everything between the server and the browser, such as a load balancer or a reverse proxy, which often closes a connection that has been silent for 30 or 60 seconds.

What happens when the customer leaves early? We started a second request and let curl quit after 1.3 seconds (-m 1.3). The server log printed [sse] completed, order 43. The next write failed, our catch block ran, and completeWithError released the emitter. Without that catch block the pushing thread would keep sending to nobody until the 30-second timeout.

Idiom: SseEmitter for one-way live updates

The problem: a page needs to learn about changes as they happen, and the server is the only side that has news. Polling wastes requests (1,200 a second for five facts per order) and still shows news up to a second late. A WebSocket would work but adds a second protocol you must secure, proxy and monitor, for a flow that only goes one way.

How it works: the controller returns an SseEmitter with produces = text/event-stream. Some other thread keeps the emitter, sends events, and finishes it. The browser side is one line: new EventSource(url).

  1. Return the emitter at once: never sleep or loop inside the controller method itself, or you hold a request thread for the whole stream.
  2. Push from another thread: a virtual thread, an executor, or a listener on your own event bus.
  3. Always register cleanup: onTimeout, onCompletion, and a catch around send, so a closed tab removes the emitter from your list.
  4. Send a heartbeat comment a little more often than the shortest idle timeout on the path (a proxy, a load balancer).

Behind a proxy, and when many orders are live

Two things break SSE in production more than any code bug. First, a reverse proxy such as nginx buffers a response by default and passes it on only when the buffer fills. Your events then arrive in bursts, or never. For the SSE path you turn buffering off in the proxy, and you can also send the response header X-Accel-Buffering: no for nginx.

Second, idle timeouts. Many load balancers close a connection after 60 seconds without data. A heartbeat every 15 to 20 seconds keeps the line alive. Our demo sent one every 800 ms only to make it visible; do not copy that number.

Third, scale. Each open stream is one open socket and one SseEmitter object in memory. 1,200 streams is nothing for Tomcat. 100,000 is a real design problem: you need an event source such as Kafka or Redis that every server instance listens to, so that whichever instance holds the customer's connection can push the update. Keep a map from order id to emitter in each instance, and remove the entry in onCompletion, onTimeout and onError.

Five status changes, three ways to deliver them Polling 1 request per second "same as before" "same as before" "COOKING" (news!) 8 requests, 1 change SSE 1 request, 1 open reply one HTTP response stays open; the server writes into it whenever news arrives PLACED COOKING DELIVERED WebSocket 1 upgraded connection either side may speakat any time Top lane: arrows go down only, and most return nothing new.Lower lanes: one connection, messages when needed.
Fig. 22.17 — Polling asks eight times to learn one fact. SSE keeps one reply open and the server writes into it. WebSocket keeps a two-way connection open.

Stack: polling, SSE, WebSocket, or something heavier

Picking a live-update tool is a stack choice, so here are the alternatives with the cost of each.

Ways to push news to a browser
OptionPick it whenCost or catch
Polling (setInterval and fetch)Updates are rare, a delay of seconds is fine, or you have under about 100 viewers. It is the simplest thing and it works through every proxy.Most requests return nothing new. Traffic grows with viewers times frequency, not with real changes. Our incident: 40 percent of all traffic.
Long pollingYou must support a client or proxy that cannot stream, and still want fast news.The server holds each request until news arrives, then the client asks again. More complex than polling and a worse fit than SSE for new code.
SSE (SseEmitter)Only the server has news: status, progress, notifications, live feeds. This is the default choice for QuickBite tracking.One-way and text only. Needs heartbeats, proxy buffering off, and an event bus once you run several instances.
WebSocket (@EnableWebSocket) or STOMP over WebSocketBoth sides send often: chat, a driver sharing a live location, collaborative editing, games.A second protocol with its own upgrade handshake, authentication, message framing and monitoring. Load balancers need sticky or well-configured connections.
A message broker pushed to the browser (RabbitMQ web-STOMP, a hosted service)Fan-out to very many clients, or you already run the broker.Another system to run. Worth it past tens of thousands of connections, not before.

To see the WebSocket row in real life, here is the smallest possible server and a client written with only the JDK's own java.net.http.WebSocket. The server sends the first status as soon as the client connects, and then answers whatever the client sends. That second part is what SSE cannot do.

WsDemo.java (server part) · Boot 4.2runs offline
@Configuration
@EnableWebSocket
@ConditionalOnProperty(name = "demo", havingValue = "ws")
class WsDemo implements WebSocketConfigurer {
    @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry r) {
        r.addHandler(new TextWebSocketHandler() {
            @Override public void afterConnectionEstablished(WebSocketSession s) throws Exception {
                s.sendMessage(new TextMessage("{\"order\":42,\"status\":\"PLACED\"}"));
            }
            @Override protected void handleTextMessage(WebSocketSession s, TextMessage m) throws Exception {
                s.sendMessage(new TextMessage("server got: " + m.getPayload()));   // two-way: client talks too
            }
            @Override public void afterConnectionClosed(WebSocketSession s, CloseStatus st) {
                System.out.println("server: connection closed " + st);
            }
        }, "/ws/orders");
    }
run --demo=ws · Boot 4.2runs offline
client: open
client received: {"order":42,"status":"PLACED"}
client received: server got: cancel order 42?
server: connection closed CloseStatus[code=1000, reason=bye]

The client opened one connection, received the first status, sent a question, received the answer, and closed with code 1000 ("normal closure"). Notice what we did not have to write: no polling timer, no second HTTP request, and the server learned that the client left from a callback.

Raw WebSocket gives you a pipe and nothing else. If you want named destinations such as /topic/orders/42, subscriptions, and a broker that fans messages out, Spring offers STOMP (a small text protocol for messaging) on top of WebSocket. The configuration is short:

StompConfig.java · Boot 4.2runs offline
@Configuration
@EnableWebSocketMessageBroker
class StompConfig implements WebSocketMessageBrokerConfigurer {
    @Override public void configureMessageBroker(MessageBrokerRegistry r) { r.enableSimpleBroker("/topic"); r.setApplicationDestinationPrefixes("/app"); }
    @Override public void registerStompEndpoints(StompEndpointRegistry r) { r.addEndpoint("/stomp"); }
}

This class compiled against Boot 4.2 and I did not run a STOMP client for it. With it, a controller method annotated @MessageMapping("/track") receives frames sent to /app/track, and anything published to /topic/... goes to all subscribers. The simple in-memory broker lives inside one JVM, so with several instances you switch to a broker relay (RabbitMQ with its STOMP plugin, for example). Check the Spring reference guide for the exact relay settings of your version.

My rule for QuickBite: SSE for the tracking page, because only the server talks. WebSocket only if we add a live chat between customer and delivery rider, because then both sides talk.

Filters, interceptors, argument resolvers and advice: who runs when

QuickBite needed to know who the customer was on every order request. One developer wrote a servlet filter that read the X-Customer header. A second developer, on another team, wrote an interceptor that did the same thing and logged it. A third added a @CurrentCustomer parameter to controller methods. For two weeks the log showed three lines per request and nobody knew which code ran first, so a bug that only appeared when the filter rejected a request took days to explain.

The cause was simple. Spring MVC has four different places where you can put code that runs "around" a controller, and they sit at different layers. Each can see different things. If you know the layers you pick the right one on the first try.

Bridge: the four hooks, one level down

A servlet filter is part of the servlet standard, not of Spring MVC. It sees the raw request before Spring has decided which controller will answer. It can change the request, stop it, or wrap the response. Use it for things that must apply to everything, including static files and error pages: authentication, request ids, compression, CORS.

A handler interceptor (HandlerInterceptor) is part of Spring MVC. It runs after Spring has picked the controller method, so it knows which one. It has three hooks: preHandle (before the controller; return false to stop), postHandle (after the controller returned, before the response is written) and afterCompletion (always, even after an exception). Use it for per-controller rules such as timing, audit lines and locale.

A handler method argument resolver builds one parameter of a controller method. When a method asks for a type or an annotation that Spring does not know, the resolver supplies the value. Use it to turn a header, a token or a session into a clean parameter like @CurrentCustomer String who, so controllers never touch request objects.

@ControllerAdvice (here @RestControllerAdvice) holds shared controller helpers. It can contain @ExceptionHandler methods, and it can implement ResponseBodyAdvice to change a body just before it is written. Use it for error shapes and response envelopes.

The setup: one of each, all printing a numbered line. Here are the pieces in chunks, then you will see the order they really run in.

AuditFilter · Boot 4.2runs offline
@Component
class AuditFilter extends OncePerRequestFilter {
    @Override protected boolean shouldNotFilter(HttpServletRequest r) { return !r.getRequestURI().startsWith("/chain"); }
    @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        System.out.println("1 filter           before chain");
        chain.doFilter(req, res);
        System.out.println("8 filter           after chain, status " + res.getStatus());
    }
}
TraceInterceptor and CustomerResolver · Boot 4.2runs offline
class TraceInterceptor implements HandlerInterceptor {
    @Override public boolean preHandle(HttpServletRequest q, HttpServletResponse s, Object h) {
        System.out.println("2 interceptor      preHandle  (handler = " + ((org.springframework.web.method.HandlerMethod) h).getMethod().getName() + ")");
        return true;
    }
    @Override public void postHandle(HttpServletRequest q, HttpServletResponse s, Object h, org.springframework.web.servlet.ModelAndView m) {
        System.out.println("6 interceptor      postHandle");
    }
    @Override public void afterCompletion(HttpServletRequest q, HttpServletResponse s, Object h, Exception e) {
        System.out.println("7 interceptor      afterCompletion, exception = " + e);
    }
}

class CustomerResolver implements HandlerMethodArgumentResolver {
    @Override public boolean supportsParameter(MethodParameter p) { return p.hasParameterAnnotation(CurrentCustomer.class); }
    @Override public Object resolveArgument(MethodParameter p, ModelAndViewContainer c, NativeWebRequest r, WebDataBinderFactory f) {
        System.out.println("3 argument resolver resolveArgument");
        return r.getHeader("X-Customer") == null ? "anonymous" : r.getHeader("X-Customer");
    }
}
WebConfig and ChainController · Boot 4.2runs offline
@Configuration
class WebConfig implements WebMvcConfigurer {
    @Override public void addInterceptors(InterceptorRegistry r) { r.addInterceptor(new TraceInterceptor()).addPathPatterns("/chain/**"); }
    @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> l) { l.add(new CustomerResolver()); }
}

@RestController
class ChainController {
    @GetMapping("/chain/hello") String hello(@CurrentCustomer String who) {
        System.out.println("4 controller       hello(" + who + ")");
        return "hello " + who;
    }
    @GetMapping("/chain/boom") String boom(@CurrentCustomer String who) {
        System.out.println("4 controller       boom(" + who + ") throws");
        throw new IllegalStateException("kitchen closed");
    }
}

The filter is a Spring bean that extends OncePerRequestFilter, so Boot adds it to the servlet chain by itself. The interceptor and the resolver are not beans on their own: they only count after you register them in a WebMvcConfigurer. Forgetting that registration is the most common reason an interceptor "does nothing".

Make the invisible visible: send one request with an X-Customer header, then another to the endpoint that throws.

curl and server log · Boot 4.2runs offline
$ curl -s -H "X-Customer: asha" localhost:18081/chain/hello
hello asha

# server console, same request
1 filter           before chain
2 interceptor      preHandle  (handler = hello)
3 argument resolver resolveArgument
4 controller       hello(asha)
5 advice           beforeBodyWrite
6 interceptor      postHandle
7 interceptor      afterCompletion, exception = null
8 filter           after chain, status 200

$ curl -si localhost:18081/chain/boom | head -1
HTTP/1.1 409

# server console, the request that throws
1 filter           before chain
2 interceptor      preHandle  (handler = boom)
3 argument resolver resolveArgument
4 controller       boom(anonymous) throws
4b advice          @ExceptionHandler caught: kitchen closed
7 interceptor      afterCompletion, exception = null
8 filter           after chain, status 409

What you see: the order is filter, interceptor preHandle, argument resolver, controller, response advice, interceptor postHandle, interceptor afterCompletion, filter again. In the second request there is no line 5 and no line 6, because no normal body was produced. The @ExceptionHandler built the 409 response instead.

Why: the layers nest like an onion (Fig. 22.18). The filter is the outermost layer, so it starts first and finishes last. Inside the dispatcher the interceptor wraps the controller call. The argument resolver runs while Spring is preparing the arguments, which is before the method body. An exception skips postHandle but never afterCompletion, and in this run afterCompletion printed exception = null because the advice had already turned the exception into a normal 409 response.

One request, in the order the demo printed it Servlet container: Filter (1 in, 8 out) DispatcherServlet: Interceptor (2 preHandle, 6 postHandle, 7 afterCompletion) Handler adapter 3 · argument resolver 4 · controller method runs 5 · response advice beforeBodyWrite 4b · controller throws: @ExceptionHandler runs here, postHandle skipped, afterCompletion still runs Requests go inward 1 to 5. Then 6, 7, 8 unwind outward in reverse, like the layers of an onion.
Fig. 22.18 — Where each hook sits. A servlet filter wraps everything, the interceptor wraps the controller call, the argument resolver builds one parameter, and the response advice touches the body just before it is written.

When do you reach for which? A short table settles most arguments.

Which hook for which job
HookSeesPick it whenCost or catch
Servlet FilterRaw request and response, before Spring MVC. Also static files and error dispatches.Authentication, request id, CORS, compression, rate limits: anything for every request.Does not know the controller. In Spring Security the filter chain has its own order; ordering with your own filters is explicit.
HandlerInterceptorThe chosen handler method, request, response.Timing, audit logging, per-controller checks, stopping a request in preHandle.Only for MVC requests, only for paths you register. Not called for non-MVC resources unless mapped.
Argument resolverOne parameter of one method.A clean @CurrentCustomer style parameter, or request data parsed once.Hidden magic if overused. Do not put business rules here.
@ControllerAdviceExceptions thrown by controllers; response bodies (with ResponseBodyAdvice).One error shape for the whole API, response envelopes, shared model attributes.Applies broadly unless you narrow it, as we did with assignableTypes. A wide @ExceptionHandler can swallow exceptions you wanted to see (my first run did exactly that to an upload error).

For AOP-style concerns that must wrap service methods rather than web requests, you use an aspect, not these hooks: see Spring AOP from zero and the interceptor chain earlier in this chapter. For the container and the web layer in general, E4 · Web layer is the companion.

File uploads: limits, the real error, and streaming

A different QuickBite surprise: restaurants upload menu photos. A restaurant owner tried a 3 MB photo and the app answered with an empty error page. The code was fine. The server had a limit nobody had read, and nobody knew what status the user should see.

Spring MVC reads a form upload (multipart/form-data, "multipart" because the body has several parts, one per field or file) into a MultipartFile. Two properties cap it: spring.servlet.multipart.max-file-size (one file; default 1 MB) and spring.servlet.multipart.max-request-size (the whole request; default 10 MB). Past either limit, the container stops reading, Spring throws MaxUploadSizeExceededException, and the response is 413 Content Too Large.

application.properties · Boot 4.2runs offline
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=2MB
UploadController.java · Boot 4.2runs offline
package com.quickbite.web;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {
    @PostMapping("/photos")
    String photo(@RequestParam("file") MultipartFile file) throws IOException {
        return "stored " + file.getOriginalFilename() + " " + file.getSize() + " bytes";
    }

    // raw body, never fully in memory: read it in 8 KB pieces
    @PostMapping("/photos/stream")
    String stream(HttpServletRequest req) throws IOException {
        byte[] buf = new byte[8192];
        long total = 0;
        try (var in = req.getInputStream()) {
            int n;
            while ((n = in.read(buf)) != -1) total += n;
        }
        return "streamed " + total + " bytes";
    }
}

Make the invisible visible: upload a 500 KB file, then a 3 MB file to the multipart endpoint, then send the same 3 MB as a raw body to the streaming endpoint. The HTTP/1.1 100 lines are curl's "Expect: 100-continue" handshake and can be ignored.

curl · Boot 4.2runs offline
$ curl -s -i -F file=@e_half.bin localhost:18081/photos
HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 30
Date: Tue, 01 Dec 2026 19:05:26 GMT

stored e_half.bin 500000 bytes

$ curl -s -i -F file=@e_3mb.bin localhost:18081/photos
HTTP/1.1 100 

HTTP/1.1 413 
Content-Length: 0
Date: Tue, 01 Dec 2026 19:05:26 GMT
Connection: close



$ curl -s -i -X POST --data-binary @e_3mb.bin localhost:18081/photos/stream
HTTP/1.1 100 

HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 22
Date: Tue, 01 Dec 2026 19:05:26 GMT

streamed 3000000 bytes

# server log (trimmed) for the 3 MB multipart request
WARN ... DefaultHandlerExceptionResolver : Resolved
  [org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded]

What you see: the 500 KB file was stored. The 3 MB file got 413 with an empty body and a log line naming MaxUploadSizeExceededException. The streaming endpoint accepted the same 3 MB with a plain 200, because it is not a multipart endpoint and the multipart limits do not apply to it.

Why: the multipart limits belong to the multipart parser. A raw body is read straight from the request stream, in the 8 KB pieces our loop asked for, and it never sits fully in memory. That is the right shape for a 2 GB video: read the stream and copy it to disk or object storage as you go, instead of calling file.getBytes(), which loads the whole file into the heap.

Three practical rules follow. Set the limits on purpose and tell the user the limit in the error: add a @ExceptionHandler(MaxUploadSizeExceededException.class) that returns a clear message. Remember the limit also lives outside Spring, in the reverse proxy: nginx rejects bodies over 1 MB by default (client_max_body_size) with its own 413 page.

And for large files, let the browser upload straight to object storage with a pre-signed URL, so your servers never carry the bytes at all. A word of caution on the second 413 line in the log: it was logged twice per request in my run, probably because the error is handled once and then dispatched again to the error page. Do not read it as two uploads.

Calling other services: the HTTP interface client

QuickBite's order service calls the menu service for prices. Six different developers had written six small wrappers. One used RestTemplate with a hand-built URL string. One used RestClient. One had no timeout, so when the menu service stalled for 40 seconds, 200 order threads waited with it. Nobody could list which services were called, with which settings.

A tidy answer is the HTTP interface client. You write a plain Java interface, put @HttpExchange annotations on its methods, and Spring generates the implementation. It looks like a Spring MVC controller, turned inside out: the annotations describe a call you make, not a call you receive.

Bridge: the declarative client, one level down

Under the interface is an ordinary HTTP client. In Spring Framework 7 that client is usually RestClient (a fluent, blocking client that replaces RestTemplate). A factory called HttpServiceProxyFactory reads the annotations and creates a JDK dynamic proxy (see the proxy bridge in the AOP section) that turns each method call into one RestClient call: it fills {id} from @PathVariable, adds query parameters, sends the body, and converts the response to your return type.

Spring Boot 4 adds a registry: you list your interfaces in one place with @ImportHttpServices and put each group's settings (base URL, timeouts) in properties. The factory, the RestClient and the proxy are all built for you. The group name ties the Java code to the property names.

The setup: a tiny interface with two methods, a record for the answer, and two properties. The server side is a normal controller in the same app, answering /menu/{id} and a deliberately slow /menu/slow that sleeps 3 seconds.

MenuApi.java · Boot 4.2runs offline
package com.quickbite.web;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;

@HttpExchange("/menu")
public interface MenuApi {
    @GetExchange("/{id}")
    MenuItem item(@PathVariable long id);

    @GetExchange("/slow")
    MenuItem slow();
}
application.properties · Boot 4.2runs offline
spring.http.serviceclient.menu.base-url=http://localhost:18081
spring.http.serviceclient.menu.read-timeout=1s

Now the registration, and a runner that calls the client and prints what happens. The group name menu in the annotation is the same word as in the property names above.

ClientDemo.java · Boot 4.2runs offline
@Configuration
@ImportHttpServices(group = "menu", types = MenuApi.class)
@ConditionalOnProperty(name = "demo", havingValue = "httpclient")
class ClientDemo {
    @Bean CommandLineRunner callMenu(MenuApi api, ApplicationContext ctx) {
        return args -> {
            System.out.println("client class  : " + api.getClass().getName());
            System.out.println("api.item(7)   : " + api.item(7));
            long t0 = System.nanoTime();
            try { api.slow(); }
            catch (Exception e) {
                System.out.println("api.slow()    : " + e.getClass().getSimpleName() + " after "
                        + (System.nanoTime() - t0) / 1_000_000 + " ms");
                Throwable c = e; while (c.getCause() != null) c = c.getCause();
                System.out.println("root cause    : " + c.getClass().getName() + ": " + c.getMessage());
            }
            System.exit(SpringApplication.exit(ctx));
        };
    }
}

Make the invisible visible: run it. The first call should work. The second call should be cut off by the 1-second read timeout, long before the server's 3 seconds are over.

run --demo=httpclient · Boot 4.2runs offline
client class  : jdk.proxy2.$Proxy123
api.item(7)   : MenuItem[id=7, name=Chicken biryani, priceInPaise=24900]
api.slow()    : ResourceAccessException after 1005 ms
root cause    : java.net.http.HttpTimeoutException: Request cancelled

What you see: the injected MenuApi is a JDK proxy (jdk.proxy2.$Proxy...), because the interface is the only thing Spring had. api.item(7) returned a MenuItem record built from the JSON. api.slow() failed after 1,005 ms with a ResourceAccessException whose root cause is the JDK client's HttpTimeoutException.

Why: read-timeout=1s reached the underlying HTTP client through the group settings. Without that line the call would have waited the full 3 seconds. Timeouts are the first thing to set on any client: a default of "wait forever" is how one slow service takes down every service that calls it.

Idiom: a declarative HTTP interface client with explicit timeouts

The problem: every team hand-writes its own client wrapper. URLs are built by string concatenation, error handling differs, and timeouts are missing in at least one of them. A stalled downstream service then holds your threads hostage.

How it works: one interface describes the remote API. A registry (or HttpServiceProxyFactory by hand) generates the implementation. Settings live in one property group per remote service.

  1. Describe the API: an interface with @HttpExchange at the top and @GetExchange, @PostExchange and friends on methods.
  2. Register it: @ImportHttpServices(group = "menu", types = MenuApi.class).
  3. Configure the group: spring.http.serviceclient.menu.base-url and the connect and read timeouts.
  4. Inject and call: use MenuApi like any bean. Decide in the caller what a timeout means (retry, fallback, error).

By hand

Build the factory and the proxy yourself. Works on any version with RestClient.

snippetruns offline
RestClient rc = builder
    .baseUrl("http://localhost:18081")
    .build();
var factory = HttpServiceProxyFactory
    .builderFor(RestClientAdapter.create(rc))
    .build();
MenuApi api =
    factory.createClient(MenuApi.class);

Registry (Boot 4)

Declare the group and let Boot build everything.

snippetruns offline
@ImportHttpServices(
    group = "menu",
    types = MenuApi.class)
class ClientConfig { }

// application.properties:
// spring.http.serviceclient.menu
//   .base-url=http://menu:8080
//   .read-timeout=1s

The shift: the registry moves the plumbing and the timeouts out of Java and into one group of properties per remote service.

The left side compiled against Boot 4.2 as Manual.java in the demo project; the right side is the code that ran above. Both give you the same kind of proxy.

Stack: which HTTP client

Spring HTTP clients today
OptionPick it whenCost or catch
HTTP interface (@HttpExchange)A fixed set of calls to a service. New code in Spring 6 and 7.Generated proxy, blocking by default. Fewer knobs than raw RestClient.
RestClientYou want a fluent, blocking client with full control per request. The default choice for new blocking code.You write the URL, the call and the error handling yourself every time.
WebClient (WebFlux)You already run reactive code and need non-blocking calls or streaming.Pulls in the reactive model. With virtual threads, plain blocking RestClient is often simpler.
OpenFeign (Spring Cloud)An existing codebase uses it, or you need its integrations (load balancing, circuit-breaker bridges).A separate library with its own release train. The HTTP interface covers the plain case without it.
RestTemplateOnly existing code you cannot change yet.Deprecated for removal since Spring Framework 7.1, which Boot 4.2 uses. I checked this by compiling: the next section shows the warning.

Two last tips. Wrap calls that can fail in the retry and circuit-breaker tools from the resilience section, and keep timeouts shorter than your own callers' timeouts, so a slow call fails where you can handle it.

Messaging: which Spring library for which broker

Messaging means one service puts a message on a broker and another service picks it up later. The two sides do not wait for each other. QuickBite uses it when the order service tells the kitchen, billing and notification services that an order exists. The question is only which broker and which Spring project.

Each broker has its own Spring library, and each follows the same pattern: a template to send, an annotated method to receive. The snippets below are shapes, not runs. I did not start a broker for this section, and I would rather say that than paste invented output.

// illustrative: the same receiving pattern, three brokersillustrative
@KafkaListener(topics = "orders", groupId = "kitchen")
void onOrder(OrderPlaced event) { ... }          // Spring for Apache Kafka

@RabbitListener(queues = "orders.kitchen")
void onOrder(OrderPlaced event) { ... }          // Spring AMQP, RabbitMQ

@JmsListener(destination = "orders")
void onOrder(OrderPlaced event) { ... }          // Spring JMS, ActiveMQ and others
Messaging stacks
OptionPick it whenCost or catch
Spring for Apache Kafka (@KafkaListener)A durable, replayable log of events; many consumers read the same stream at their own speed; high volume. See E17 · Kafka.You run and tune a cluster. Ordering is per partition only. Consumers must be idempotent.
Spring AMQP with RabbitMQ (@RabbitListener)Classic work queues and routing: "send this job to one of the kitchen workers"; flexible routing by key; easy to run.A message is gone once acknowledged: no replay by default. Boot 4.2 adds support for AMQP 1.0 (a different, standardised wire protocol that RabbitMQ also speaks); the classic AMQP 0-9-1 client still works. Check the 4.2 reference for the exact starter and property names before you switch.
Spring JMS (@JmsListener)You live in an enterprise estate that already runs ActiveMQ, IBM MQ or similar.Older API style; the vendor client matters more than Spring does.
Spring Data Redis streams / pub-subYou already run Redis and need light, fast fan-out. Boot 4.1 auto-configures Redis listener endpoints.Pub-sub drops messages if nobody listens at that moment; streams need care. A cache is not a broker.
Transactional outbox plus any brokerYou must update the database and publish an event without losing either. See the outbox idiom in E7.Extra table and a relay. Worth it for money-moving events.

Whichever you pick, three rules carry over. Make consumers idempotent (processing the same message twice must be harmless), because every broker can redeliver. Send small events with an id and the facts that changed, not entire objects. And never publish from inside a database transaction without thinking: see after-commit events earlier for how to publish only once the data is safe.

Spring Batch 6: import a big file, and survive a crash

Each night a partner restaurant chain sends QuickBite a CSV of 480,000 menu rows. The first import was a loop inside a @Scheduled method: read a line, insert a row, repeat. At row 312,004 the database connection dropped. The loop died, 312,003 rows were already in, and the only way to continue was to delete everything and start again, 40 minutes later.

That job needs three things a loop does not have. It must commit in small batches so a failure loses little. It must remember how far it got. And it must be able to start again from there instead of from zero. This is what Spring Batch is for.

Bridge: job, step and chunk, one level down

A job is the whole task ("import the menu"). A job has one or more steps. The most common kind of step is chunk-oriented, and it has three parts: an item reader that returns one record at a time, an item processor that changes or filters one record, and an item writer that receives a whole chunk of records and writes them together.

The chunk size (here 100) is the number of items per database transaction. Batch reads and processes 100 items, hands all 100 to the writer, commits, and then repeats. If something fails, only the current chunk rolls back. The 100 chunks before it stay committed.

The job repository is the notebook Batch writes in. After each chunk commit it stores how far the reader got, in an execution context (a small map of saved state, such as menuReader.read.count=600). A job instance is "this job with these identifying parameters" (here file=menu.csv). Each attempt to run an instance is a job execution. Running the same instance again after a failure is a restart: the reader finds its saved count and skips ahead.

The setup: a generated menu.csv with 1,000 lines (id,name,price), a reader for it, a processor that upper-cases the name and can be told to fail on one row id, a writer that inserts into an H2 table, and a step with chunk size 100. First the three pieces.

BatchDemo.java (reader, processor, writer) · Boot 4.2runs offline
    record MenuRow(long id, String name, int price) {}
    @Bean FlatFileItemReader<MenuRow> reader() {
        return new FlatFileItemReaderBuilder<MenuRow>().name("menuReader")
                .resource(new FileSystemResource("menu.csv")).linesToSkip(1).delimited()
                .names("id", "name", "price")
                .fieldSetMapper(fs -> new MenuRow(fs.readLong("id"), fs.readString("name"), fs.readInt("price")))
                .build();
    }

    @Bean ItemProcessor<MenuRow, MenuRow> processor() {
        int failAt = Integer.getInteger("failAt", -1);
        return row -> {
            if (row.id() == failAt) throw new IllegalStateException("bad row " + row.id() + " (forced)");
            return new MenuRow(row.id(), row.name().toUpperCase(), row.price());
        };
    }

    @Bean JdbcBatchItemWriter<MenuRow> writer(DataSource ds) {
        return new JdbcBatchItemWriterBuilder<MenuRow>().dataSource(ds)
                .sql("insert into menu_import (id, name, price) values (:id, :name, :price)")
                .beanMapped().build();
    }

The reader is a FlatFileItemReader: it skips the header line, splits each line on commas and builds a MenuRow record. The processor is where a real job validates and transforms. The writer is a JdbcBatchItemWriter, which sends each chunk as one JDBC batch. Now the step and the job, which wire the pieces together.

BatchDemo.java (step and job) · Boot 4.2runs offline
    @Bean Step importStep(JobRepository repo, PlatformTransactionManager tx, FlatFileItemReader<MenuRow> r,
                          ItemProcessor<MenuRow, MenuRow> p, JdbcBatchItemWriter<MenuRow> w) {
        return new StepBuilder("importStep", repo).<MenuRow, MenuRow>chunk(100).transactionManager(tx)
                .reader(r).processor(p).writer(w).build();
    }

    @Bean Job importJob(JobRepository repo, Step importStep) {
        return new JobBuilder("importMenu", repo).start(importStep).build();
    }

The Batch 6 package names changed from Batch 5: for example the item classes now live in org.springframework.batch.infrastructure.item... and a job is a org.springframework.batch.core.job.Job. All the code in this section compiled against Batch 6.1.0 as shipped with Boot 4.2.0, so you can copy the imports from the project in code/e22-spring-in-depth/E/integ.

Make the invisible visible: run the job twice with the same command. In the first run the processor is told to throw on row 650 (-DfailAt=650). In the second run it is not. I deleted nothing between the runs: the repository and the table live in an H2 file, so the second run can see what the first did.

run --demo=batch · Boot 4.2runs offline
# run 1: row 650 is bad (-DfailAt=650)   (log trimmed)
INFO  AbstractStep : Executing step: [importStep]
ERROR ChunkOrientedStep : Rolling back chunk transaction
java.lang.IllegalStateException: bad row 650 (forced)
ERROR AbstractStep : Encountered an error executing step importStep in job importMenu
INFO  AbstractStep : Step: [importStep] executed in 398ms
job instance 1, execution 1
step context: {menuReader.read.count=600, batch.executed=true, ...}
step importStep: FAILED read=700 written=600 commits=6 rollbacks=1
job status : FAILED  exit=FAILED
rows in menu_import: 600

# run 2: same command, bad row fixed
INFO  AbstractStep : Executing step: [importStep]
INFO  AbstractStep : Step: [importStep] executed in 266ms
job instance 1, execution 2
step context: {menuReader.read.count=1001, batch.executed=true, ...}
step importStep: COMPLETED read=400 written=400 commits=4 rollbacks=0
job status : COMPLETED  exit=COMPLETED
rows in menu_import: 1000

# run 3: the instance is already COMPLETED
Caused by: JobInstanceAlreadyCompleteException: A job instance already exists and is
  complete for identifying parameters={file=menu.csv}

What you see: run 1 read 700 rows (seven chunks) and wrote 600: six commits, then a rollback of the seventh chunk at row 650. The job ended FAILED with 600 rows in the table and a saved reader position of 600. Run 2 was execution 2 of the same instance 1. It read only 400 rows, wrote 400, committed four chunks and finished COMPLETED with exactly 1,000 rows, no duplicates. Run 3 refused to run again, because the same parameters already completed.

Why: the six committed chunks saved their position in the job repository in the same transaction as the data. When the seventh chunk rolled back, so did its position. On restart the reader read menuReader.read.count=600 from the repository and skipped 600 lines. The data and the "how far I got" note can never disagree, because they are committed together.

The trap: the restart that was not a restart

My first version of this demo did not restart. I had only added the Boot starter spring-boot-starter-batch, and in Boot 4.2 that starter gives you the job launcher and runner, but its default job repository is held in memory, not in the database. Run 2 then looked like this:

first attempt, in-memory job repository (trimmed)runs offline
job instance 1, execution 1          <- a new JVM, so a brand new notebook
step context: {batch.executed=true, ...}   <- no menuReader.read.count at all
org.springframework.dao.DuplicateKeyException: ... Unique index or primary key violation:
  "PUBLIC.CONSTRAINT_6 PRIMARY KEY ON PUBLIC.MENU_IMPORT(ID)" ( CAST(1 AS BIGINT), 'KEBAB ROLL #1', ...
step importStep: FAILED read=100 written=0 commits=0 rollbacks=1
rows in menu_import: 600

The second JVM had an empty notebook. It started from row 1, hit the 600 rows that were already in the table, and failed on a duplicate key. Nothing was lost, but nothing was restartable either. To get a persistent repository I added @EnableBatchProcessing and @EnableJdbcJobRepository to the configuration class and created the Batch tables from the schema script that ships inside spring-batch-core (org/springframework/batch/core/schema-h2.sql).

Boot may offer a dedicated JDBC starter for this; I could not find one in the offline repository I used, so check the Boot 4.2 reference for the current recommendation. Whatever you choose, test the restart: it is the one feature that silently does not work when the repository is not persistent.

Make restarts boring: four rules

  1. Persistent repository: job state in a database that outlives the JVM.
  2. Stable parameters: a restart reuses the same identifying parameters. If you add a timestamp parameter, every run is a new instance and nothing restarts.
  3. A named reader: the reader saves its position under its name (menuReader here). A reader without a name cannot save state.
  4. Idempotent writes where you can: an upsert (merge) instead of an insert makes even a half-done chunk safe to repeat.

Spring Batch also has skip and retry policies (skip up to N bad rows, retry a deadlock), partitioning (split the file across threads or machines) and listeners for audit. I show none of those here because I did not run them. The chunk-and-restart core above is what you will explain in an interview.

Batch, scheduled loop, or something else
OptionPick it whenCost or catch
Spring BatchLarge volumes, a failure must not mean starting over, you need an audit trail of runs and counts.A job repository, extra tables and concepts. Overkill for 500 rows.
A @Scheduled method with a loopSmall, quick, safe to rerun from scratch. See scheduled jobs.No saved progress. A crash at row 312,004 means row 1 again.
A database script or COPY / bulk loadThe data needs no business logic and the database can load a file directly.Hard to validate row by row; vendor specific.
A stream or message pipeline (Kafka)Records arrive continuously, not as a nightly file. See E17.Different tool: consumers, offsets and idempotency instead of jobs and restarts.

One more place where an extra process matters: if two instances of the application both start the nightly job, you get two imports. A lock such as ShedLock (see the scheduling section) or a launch from a single Kubernetes CronJob keeps it to one.

Spring Modulith: keeping a monolith from turning into a ball of mud

QuickBite is one Spring Boot application, on purpose. Eighteen months in, someone in the orders package needed a price and imported the menu team's MenuRepository directly. A month later the menu team changed that repository's method, and the orders code stopped compiling during a release. Nobody had agreed that orders could depend on menu internals. The language let them, so they did.

Java's own visibility rules do not help much here, because public means "public to the whole application". Spring Modulith adds a rule on top: your application is a set of modules, each module has a public face, and everything else in it is private to the module. A test checks the rule.

Bridge: what a "module" is, one level down

In Modulith a module is a direct sub-package of the package that holds your @SpringBootApplication class. With the main class in com.quickbite, the packages com.quickbite.orders, com.quickbite.menu and com.quickbite.payments are three modules. Types in the module's top package are its API. Types in deeper sub-packages (like menu.internal) are internal: other modules must not use them.

ApplicationModules.of(Application.class) scans the compiled classes (it uses a bytecode analysis library called ArchUnit under the hood), builds the module list, and verify() throws if a rule is broken. It checks that no module reaches into another module's internals and that there are no cycles between modules.

The setup: three modules. menu exposes MenuApi and hides MenuRepository in menu.internal. payments exposes PaymentService. orders depends on both, and, as in the story, it takes the repository directly.

OrderService.java (the illegal version) · Boot 4.2runs offline
package com.quickbite.orders;

import com.quickbite.menu.internal.MenuRepository;     // reaches into another module's internals
import com.quickbite.payments.PaymentService;
import org.springframework.stereotype.Service;

@Service
public class OrderService {
    private final MenuRepository menu;
    private final PaymentService payments;
    OrderService(MenuRepository menu, PaymentService payments) { this.menu = menu; this.payments = payments; }
    public void place(long itemId) { payments.charge(1, menu.price(itemId)); }
}
ModularityTests.java · Boot 4.2runs offline
package com.quickbite;

import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;

class ModularityTests {
    static final ApplicationModules modules = ApplicationModules.of(BaseApplication.class);

    @Test void listModules() { modules.forEach(System.out::println); }

    @Test void verifiesModularStructure() { modules.verify(); }
}

Two tests. The first just prints what Modulith found. The second is the one that guards the rules. It is a plain JUnit test with no Spring context, so it runs in about four seconds.

Make the invisible visible: run ./mvnw -o test. First the module list, then the verdict.

./mvnw test · Boot 4.2 (trimmed)runs offline
# Menu
> Logical name: menu
> Base package: com.quickbite.menu
> Spring beans:
  o ....internal.MenuRepository
  o ....internal.MenuService
# Payments
> Base package: com.quickbite.payments
> Spring beans:
  + ....PaymentService
# Orders
> Base package: com.quickbite.orders
> Spring beans:
  + ....OrderService

[ERROR] Tests run: 2, Failures: 0, Errors: 1
org.springframework.modulith.core.Violations:
- Module 'orders' depends on non-exposed type com.quickbite.menu.internal.MenuRepository
  within module 'menu'!
  Method <com.quickbite.orders.OrderService.place(long)> calls method
  <com.quickbite.menu.internal.MenuRepository.price(long)> in (OrderService.java:12)
- ... (the same message for the field, the constructor and its parameter)

What you see: Modulith found three modules. In the bean list a + marks a bean exposed by the module's API and an o marks an internal bean: MenuRepository and MenuService got o. Then verify() failed, naming the module that broke the rule, the type it should not touch, and the exact place: the method call, the field and the constructor.

Why: everything under menu.internal is private to menu. orders imported it, and the analysis of the compiled classes found the reference. The build fails in CI instead of an angry release night.

The fix is to depend on the module's public face. MenuApi is an interface in the module's top package, and the internal MenuService implements it.

Illegal

orders imports a type from menu.internal.

snippetruns offline
import com.quickbite
  .menu.internal.MenuRepository;

private final MenuRepository menu;
// menu.price(itemId)

Legal

orders uses the module's public interface.

snippetruns offline
import com.quickbite.menu.MenuApi;

private final MenuApi menu;
// menu.priceOf(itemId)

The shift: depend on the interface in the module's top package and the verification test passes.

./mvnw test · Boot 4.2runs offline
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.808 s -- in com.quickbite.ModularityTests
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

Both tests passed after the one-word change. Keep ModularityTests in the build and every future violation fails the pull request that introduces it.

Modulith has more than this test. It can generate module diagrams, let you test one module in isolation (@ApplicationModuleTest), and ships an event publication registry: modules talk through events, and events are stored in the database before delivery, so a listener that crashed can be retried.

That registry needs additional Modulith artifacts (the events modules and a persistence module) that I did not add or run here, so I describe it and do not show it: check the Modulith reference for your version before relying on it. The relation to our earlier work is direct: it is the same idea as after-commit events with a safety net underneath.

Spring Cloud today: which parts still matter on Kubernetes

Spring Cloud grew up when the cluster did not exist for you: you had to build service discovery, central configuration and a gateway yourself. Kubernetes now provides much of that. The honest question for a QuickBite team on Kubernetes is therefore: for each Spring Cloud piece, does the platform already do it?

Spring Cloud pieces against Kubernetes
Spring Cloud pieceWhat it didOn Kubernetes today
Config ServerCentral configuration for all services, from a Git repository.ConfigMaps and Secrets mounted as files or environment variables do the same job with no extra service. Keep Config Server only if you need Git-backed history and live refresh across many non-Kubernetes apps. See E10 and the configuration section.
Service discovery (Eureka, Consul)Services register themselves; callers look them up.A Kubernetes Service gives a stable DNS name (http://menu) and spreads calls across pods. Discovery servers are rarely needed.
Spring Cloud GatewayOne entry point: routing, rate limits, header changes, authentication.An Ingress or Gateway API controller covers routing and TLS. Spring Cloud Gateway still matters when you want routing and filters written in Java next to your code.
OpenFeign / load balancerDeclarative clients, client-side load balancing.The Service load-balances at the connection level. For the client itself the HTTP interface from earlier in this section is the lighter option.
Circuit breaker and retryResilience around remote calls.Not a platform feature. Still your job: see the resilience section, using Resilience4j or the Spring Framework 7 core annotations.
Spring Cloud KubernetesRead ConfigMaps and Secrets as Spring property sources; discover Services through the Kubernetes API.Useful when you want property reload on ConfigMap change and have no other way to inject configuration. Plain mounted files are simpler when a restart is acceptable.

Notice what survived: the pieces that live in your code (resilience, declarative clients) matter, and the pieces that duplicated infrastructure are fading. Check which Spring Cloud release train matches your Boot version before you add any of them.

One more item from the Boot 4.1 release notes: gRPC support. gRPC is a way to call remote methods using compact binary messages over HTTP/2, with a schema file that generates the client and server code. Boot 4.1 added auto-configuration for Spring gRPC for both servers and clients.

I did not build a gRPC service for this chapter, so I give you only the shape: you write a .proto file, generate classes, annotate an implementation as a gRPC service, and Boot starts the server beside (or instead of) the web server. Choose it for internal service-to-service calls where speed and a strict contract matter more than being callable from a browser, and check the Spring gRPC reference for the exact dependencies.

11 · Spring Boot 4.0, 4.1 and 4.2What Changed in Spring Boot 4.0, 4.1 and 4.2

Boot 4.0 moved to Spring Framework 7, split the big starters into smaller ones, and switched JSON from Jackson 2 to Jackson 3 under a new package name. Boot 4.1 and 4.2 added features (API versioning, HTTP service registry, gRPC, AMQP 1.0) and began deprecating RestTemplate. This section shows the real compiler messages from a 3.5-style snippet on 4.2, the real JSON difference, API versioning with curl, and a migration order that works.

A QuickBite team had a healthy Spring Boot 3.5 service. They changed the parent version to 4.2.0 on a Monday morning. By lunch it did not build. A starter they depended on had been renamed and one had vanished. Imports for Jackson no longer resolved. A test annotation was gone. And a client class they used everywhere lit up with deprecation warnings that would turn into removal in some later release.

Nothing in that list was a surprise to anyone who had read the release notes, and nobody had read them. Let us reproduce the whole morning on purpose, and read the compiler's actual words. The legacy snippet below is a typical 3.5 price client: it uses RestTemplateBuilder, RestTemplate and Jackson's ObjectMapper.

The setup: a Boot 4.2.0 project with webmvc and the REST client starter, plus the Boot 3.5-era class and test below, compiled with deprecation warnings switched on.

PriceClient.java · written for Boot 3.5, compiled on Boot 4.2runs offline
package com.quickbite.legacy;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class PriceClient {
    private final RestTemplate rest;
    private final ObjectMapper mapper;

    public PriceClient(RestTemplateBuilder builder, ObjectMapper mapper) {
        this.rest = builder.rootUri("http://menu.internal").build();
        this.mapper = mapper;
    }

    public String price(long id) throws Exception {
        String json = rest.getForObject("/menu/{id}", String.class, id);
        return mapper.readTree(json).get("priceInPaise").asText();
    }
}
PriceClientTest.java · written for Boot 3.5runs offline
package com.quickbite.legacy;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

@SpringBootTest
class PriceClientTest {
    @MockBean PriceClient client;
    @Test void loads() { }
}

Make the invisible visible: compile it with ./mvnw -o compile. Here are the compiler's lines, shortened only by removing the file path.

./mvnw compile · Boot 4.2 (paths shortened)runs offline
[WARNING] PriceClient.java:[10,19] org.springframework.web.client.RestTemplate in
          org.springframework.web.client has been deprecated and marked for removal
[ERROR]   PriceClient.java:[3,38]  package com.fasterxml.jackson.databind does not exist
[ERROR]   PriceClient.java:[4,43]  package org.springframework.boot.web.client does not exist
[ERROR]   PriceClient.java:[11,19] cannot find symbol
            symbol:   class ObjectMapper
[ERROR]   PriceClient.java:[13,24] cannot find symbol
            symbol:   class RestTemplateBuilder
[ERROR] BUILD FAILURE

What you see: four lines that matter. Jackson's package com.fasterxml.jackson.databind is not on the classpath (Jackson 3 uses tools.jackson.databind). RestTemplateBuilder is gone from org.springframework.boot.web.client. RestTemplate itself still compiles but is "deprecated and marked for removal". The compiler stops at the first errors, so the test class's complaint is hidden until main compiles.

Why: Boot 4 reorganised its code into modules (the builder now lives in org.springframework.boot.restclient), Jackson 3 changed its Java package, and Spring Framework 7.1 marks RestTemplate @Deprecated(since = "7.1", forRemoval = true). I confirmed that last one by reading the annotation in the class file with javap, not by trusting a blog post.

I checked three more facts the same way, by looking at what is in the 4.2.0 artifacts. The test annotation @MockBean (package org.springframework.boot.test.mock.mockito) is not in spring-boot-test-4.2.0.jar at all, so the test fails to compile too; its replacement is Spring Framework's @MockitoBean. The starter spring-boot-starter-aop does not exist at 4.2.0, so the old dependency fails with this message from Maven:

./mvnw dependency:get · Boot 4.2 (trimmed)runs offline
The following artifacts could not be resolved:
  org.springframework.boot:spring-boot-starter-aop:jar:4.2.0 (absent):
  ... was not found in https://repo.maven.apache.org/maven2

And one thing I expected to fail and did not: spring-boot-starter-web still resolves at 4.2.0. Its published description says "deprecated in favor of spring-boot-starter-webmvc". So the old web starter is a compatibility stopgap, not a time bomb for tomorrow, but you should move off it. Do not assume every old starter has this courtesy: -aop does not.

The fixes, one by one

From the 3.5 snippet to Boot 4.2
3.5 code4.2 codeHow I know
spring-boot-starter-aopspring-boot-starter-aspectjMaven could not resolve -aop:4.2.0; the base project of this chapter uses -aspectj and runs aspects.
spring-boot-starter-webspring-boot-starter-webmvcBoth resolve; the old one is described as deprecated.
com.fasterxml.jackson.databind.ObjectMappertools.jackson.databind.json.JsonMapper (or ObjectMapper in tools.jackson.databind)The demo below compiles with JsonMapper; the compile error above names the old package.
org.springframework.boot.web.client.RestTemplateBuilderorg.springframework.boot.restclient.RestTemplateBuilder, or better RestClient.BuilderCompiled both; the moved builder is itself deprecated for removal (warnings below).
@MockBean / @SpyBean@MockitoBean / @MockitoSpyBeanClass absent from spring-boot-test-4.2.0.jar; MockitoBean present in spring-test-7.1.0.jar.
spring-boot-starter-test for everythinga -test starter per module, e.g. spring-boot-starter-webmvc-testThe base project of this chapter uses the per-module ones; the aggregate still exists.

Here is the fixed client, which compiled. It uses RestClient.Builder and the Jackson 3 JsonMapper. It also uses an annotation from JSpecify, an industry-wide set of null-safety annotations that Spring Framework 7 now uses throughout its own API: @Nullable from org.jspecify.annotations says "this may return null".

PriceClient.java · Boot 4.2runs offline
package com.quickbite.b4;

import org.jspecify.annotations.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import tools.jackson.databind.json.JsonMapper;

@Service
public class PriceClient {
    private final RestClient rest;
    private final JsonMapper mapper;

    public PriceClient(RestClient.Builder builder, JsonMapper mapper) {
        this.rest = builder.baseUrl("http://menu.internal").build();
        this.mapper = mapper;
    }

    public @Nullable String price(long id) {
        String json = rest.get().uri("/menu/{id}", id).retrieve().body(String.class);
        return json == null ? null : mapper.readTree(json).get("priceInPaise").asString();
    }
}

Three small things changed in the body beyond the imports. The Jackson 3 exceptions are unchecked, so the old throws Exception disappears. asText() became asString() (the old name still exists in 3.1.8, I saw it with javap, so do not rely on removal). And the RestClient call is a fluent chain with retrieve().body(...), instead of getForObject.

If you must keep RestTemplate for a release or two, the stopgap compiles but warns, and that is how you find every use:

StopGap.java · Boot 4.2runs offline
package com.quickbite.b4;

import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;

class StopGap {                       // 3.5 code with only the imports fixed: compiles, but warns
    RestTemplate rest(RestTemplateBuilder builder) { return builder.build(); }
}
./mvnw compile · Boot 4.2 (paths shortened)runs offline
[WARNING] .../b4/StopGap.java:[7,5] org.springframework.web.client.RestTemplate in
          org.springframework.web.client has been deprecated and marked for removal
[WARNING] .../b4/StopGap.java:[7,23] org.springframework.boot.restclient.RestTemplateBuilder in
          org.springframework.boot.restclient has been deprecated and marked for removal
[INFO] BUILD SUCCESS

Both the class and the moved builder warn "marked for removal". The path is clear: new code uses RestClient or the HTTP interface from the previous section.

What changes where: 3.5 to 4.2 3.5 (start) Framework 6.2 starter-web, starter-aop Jackson 2 (com.fasterxml) @MockBean RestTemplate normal Spring Retry library Hand-made API versions Upgrade to the last 3.5.x first, fix warnings 4.0 (Nov 2025) Framework 7 baseline modular starters: webmvc, aspectj, per- module -test starters Jackson 3 (tools.jackson) @MockitoBean replaces @MockBean core @Retryable, API versioning, JSpecify 4.1 (Jun 2026) Spring gRPC auto-configuration Redis listener endpoints configured more features: read the 4.1 release notes 4.2 (Nov 2026) Framework 7.1 RestTemplate deprecated for removal (7.1) AMQP 1.0 support Buildpacks image cache LDAP SSL bundles The pain is in the first jump (3.5 to 4.0): package moves and renamed starters.The later jumps mostly add things and deprecate a few. Version dates after 4.0 follow the release notes as I read them; check the official notes.
Fig. 22.19 — The change map. Most breaking changes sit in 4.0. Releases 4.1 and 4.2 add features and start deprecating.

The baseline: what you get with 4.2.0

These versions come from the real dependency tree of the Boot 4.2.0 project used for every demo in this chapter.

Boot 4.2.0 baseline
PieceVersionWhat it means for you
Spring Framework7.1.0Core resilience annotations (@Retryable, @ConcurrencyLimit), API versioning in MVC, RestTemplate deprecated for removal, JSpecify annotations.
Spring Security7.2.0Same API ideas as 6.x; read its own migration guide if you customise filters.
Spring Batch6.1.0New package names for items and jobs (see the batch part of the previous section).
Hibernate ORM7.4.15See E5 for the JPA side.
Jackson3.1.8New package tools.jackson; annotations stay in com.fasterxml.jackson.annotation (the jar on the classpath is jackson-annotations-2.21).
JUnit Jupiter6.1.3Tests: use the per-module -test starters.
Tomcat11.0.27Servlet 6.1 generation. Undertow support was removed in 4.0 as I read the notes; verify before relying on it.
Micrometer / HikariCP / Flyway1.18.0 / 7.1.0 / 12.11.0Metrics, connection pool and migrations; see the platform section.
Java17 or newer (25 used here)Java 17 is the floor. I ran everything on Java 25.

Modular starters: what the new names buy you

Until 3.5, one auto-configuration jar held the code for nearly every integration. Every application downloaded and scanned all of it, and most of it stayed switched off by conditions. In 4.0 Boot split that big jar into one module per technology (spring-boot-webmvc, spring-boot-flyway, spring-boot-batch and so on), and gave each a matching starter (a dependency that pulls the module plus the libraries it needs).

The effect: smaller classpaths, fewer classes for auto-configuration to consider, and a clearer answer to "which module configures this?". A spring-boot-starter-classic exists, whose published description is "core classic starter, including full auto-configuration support"; I read it as a bridge for the old big jar, but I did not test it.

The practical change is in your pom.xml. Here is a small one in both generations.

Boot 3.5

One web starter, one aop starter, one test starter.

snippetruns offline
<dependency>
  <artifactId>
    spring-boot-starter-web
  </artifactId>
</dependency>
<dependency>
  <artifactId>
    spring-boot-starter-aop
  </artifactId>
</dependency>
<dependency>
  <artifactId>
    spring-boot-starter-test
  </artifactId>
  <scope>test</scope>
</dependency>

Boot 4.2

Named after the module; tests per module.

snippetruns offline
<dependency>
  <artifactId>
    spring-boot-starter-webmvc
  </artifactId>
</dependency>
<dependency>
  <artifactId>
    spring-boot-starter-aspectj
  </artifactId>
</dependency>
<dependency>
  <artifactId>
    spring-boot-starter-webmvc-test
  </artifactId>
  <scope>test</scope>
</dependency>

The shift: name the starter after the module you use, and add the matching -test starter for each one.

Other examples in the real pom.xml of this chapter's base project: spring-boot-starter-flyway (Flyway used to be auto-configured from the big jar and now has its own starter), spring-boot-starter-validation, and spring-boot-h2console (the H2 web console is its own module now).

A common migration slip: after moving to Boot 4 a feature "stops working" with no error, because its starter was never added. Flyway is the classic example: with only flyway-core on the classpath, migrations may no longer run on startup. When something that worked on 3.5 goes quiet, first ask "which module configures this, and is its starter on my classpath?".

Jackson 3: the package move and what it does to your JSON

The package move is mechanical: com.fasterxml.jackson.databind becomes tools.jackson.databind, and core and datatype classes move the same way. The annotations (@JsonProperty, @JsonIgnore) stay in com.fasterxml.jackson.annotation, so your model classes mostly compile unchanged. Jackson 3's JsonMapper is built with JsonMapper.builder()...build() and, in contrast to Jackson 2, it is immutable after building.

The package move is the easy part. The harder part is behaviour: some defaults changed. The only way to know what changes for your clients is to serialise the same object with both. I did exactly that. The project has Jackson 2.17.3 and Jackson 3.1.8 side by side on the classpath (possible because the packages differ), and the class below has fields in a deliberately unsorted order and four tricky types.

Order.java · Boot 4.2runs offline
package com.quickbite.b4;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;

public class Order {
    public long id = 42;
    public String status = "PLACED";
    public LocalDate placedOn = LocalDate.of(2026, 12, 2);
    public Instant paidAt = Instant.parse("2026-12-02T10:15:30Z");
    public BigDecimal total = new BigDecimal("499.00");
    public String note = null;
    public String customer = "asha";
}
JacksonDemo.java (the run method) · Boot 4.2runs offline
    @Bean CommandLineRunner run(tools.jackson.databind.json.JsonMapper boot, ApplicationContext ctx) {
        return args -> {
            var j2 = new com.fasterxml.jackson.databind.ObjectMapper()
                    .registerModule(new com.fasterxml.jackson.datatype.jsr310.JavaTimeModule());
            var j3 = tools.jackson.databind.json.JsonMapper.builder().build();
            System.out.println("Jackson 2 (new ObjectMapper + JavaTimeModule): " + j2.writeValueAsString(new Order()));
            System.out.println("Jackson 3 (JsonMapper.builder().build())     : " + j3.writeValueAsString(new Order()));
            System.out.println("Jackson 3 (Spring Boot's JsonMapper bean)    : " + boot.writeValueAsString(new Order()));
            String json = "{\"id\":1,\"extra\":true}";
            try { j2.readValue(json, Order.class); System.out.println("J2 unknown property: accepted"); }
            catch (Exception e) { System.out.println("J2 unknown property: " + e.getClass().getSimpleName()); }
            try { var o = j3.readValue(json, Order.class); System.out.println("J3 unknown property: accepted (id=" + o.id + ")"); }
            catch (Exception e) { System.out.println("J3 unknown property: " + e.getClass().getSimpleName()); }
            try { boot.readValue(json, Order.class); System.out.println("Boot unknown property: accepted"); }
            catch (Exception e) { System.out.println("Boot unknown property: " + e.getClass().getSimpleName()); }
            System.exit(SpringApplication.exit(ctx));
        };
    }
}

Make the invisible visible: write the same Order with a bare Jackson 2 mapper (with the java.time module registered, otherwise it cannot write dates at all), a bare Jackson 3 mapper, and the mapper Spring Boot builds. Then read the same JSON with an unknown field.

run --demo=jackson · Boot 4.2runs offline
Jackson 2 (new ObjectMapper + JavaTimeModule):
{"id":42,"status":"PLACED","placedOn":[2026,12,2],"paidAt":1796206530.000000000,
 "total":499.00,"note":null,"customer":"asha"}
Jackson 3 (JsonMapper.builder().build()):
{"customer":"asha","id":42,"note":null,"paidAt":"2026-12-02T10:15:30Z",
 "placedOn":"2026-12-02","status":"PLACED","total":499.00}
Jackson 3 (Spring Boot's JsonMapper bean): identical to the line above

J2 unknown property: UnrecognizedPropertyException
J3 unknown property: accepted (id=1)
Boot unknown property: accepted

What you see: three differences between a bare Jackson 2 mapper and a bare Jackson 3 mapper, all in the same JSON. First, the date: [2026,12,2] (an array) against "2026-12-02" (text). Second, the instant: 1796206530.000000000 (seconds with nine decimals) against "2026-12-02T10:15:30Z".

Third, the property order: Jackson 2 kept declaration order (id, status, placedOn...), Jackson 3 sorted the names alphabetically (customer, id, note...). The null note and the 499.00 decimal were the same in both. Reading JSON with an extra field failed in Jackson 2 and was accepted by Jackson 3.

Why: Jackson 3 changed several defaults to what most applications turn on anyway. Spring Boot already configured its Jackson 2 mapper to write ISO dates and to ignore unknown fields, so a Boot 3.5 service usually did not show the first and the last difference. What changes is code that built its own bare ObjectMapper (a utility class, a test helper, a cache serializer): that code now produces different bytes. Property order matters if anyone compares JSON as text or computes a signature over it.

That is all I can state as observed: three outputs, one run, on 3.1.8 and 2.17.3. The Jackson project documents more changes in its 3.0 migration notes, and I did not test them. Treat the result as a method rather than a full list: before a migration, serialise your real response classes with both mappers and diff the text.

API versioning in Spring MVC

QuickBite's order endpoint returned "total": 499.0, a bare number. Finance asked for the currency. Changing the field to an object {"amount":499.0,"currency":"INR"} would break the old Android app that 30 percent of customers still ran. The usual workaround was a new URL, /v2/orders/7, with a copy of the controller, and every team invented its own convention.

Spring Framework 7 builds versioning into MVC. A mapping can declare which version it serves, and a resolver reads the requested version once, in one place. I verified the exact API on 4.2.0 by compiling it and then calling it with curl.

Bridge: how the version gets from the request to the method

Three pieces cooperate. A version resolver pulls a raw version string out of the request: from a header, a query parameter, a path segment or a media-type parameter. A version parser turns the string into a comparable value (so "2" and "2.0" mean the same). And a version strategy applies the rules: which versions are supported, which one is the default when the client sends none, and whether a version is required.

Then @GetMapping(path = "/orders/{id}", version = "2") matches only requests whose resolved version is 2. In Boot you do not write the resolver by hand: Boot reads properties under spring.mvc.apiversion and builds all three pieces. These are the property names from the Boot 4.2 configuration metadata:

spring.mvc.apiversion.* (from the 4.2.0 metadata)
PropertyTypeWhat it does
use.headerStringRead the version from this request header, for example API-Version.
use.query-parameterStringRead it from a query parameter, for example ?version=2.
use.path-segmentIntegerRead it from this segment index of the URL path.
use.media-type-parameterMapRead it from a parameter of the Accept media type.
supportedList of StringThe versions the API accepts. Others get a 400.
defaultStringThe version to use when the client does not send one.
requiredBooleanWhether the client must send a version.
detect-supportedBooleanCollect the supported versions from the version attributes found on mappings.

The setup: two methods for the same URL. Version 1 returns the old shape and version 2 the new one.

OrderVersionController.java · Boot 4.2runs offline
package com.quickbite.b4;

import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
class OrderVersionController {
    @GetMapping(path = "/orders/{id}", version = "1")
    Map<String, Object> v1(@PathVariable long id) {
        return Map.of("id", id, "total", 499.0);                 // old shape: a bare number
    }

    @GetMapping(path = "/orders/{id}", version = "2")
    Map<String, Object> v2(@PathVariable long id) {
        return Map.of("id", id, "total", Map.of("amount", 499.0, "currency", "INR"));
    }
}
start command · Boot 4.2runs offline
java -jar target/b4-0.0.1-SNAPSHOT.jar \
  --spring.main.web-application-type=servlet --server.port=18082 \
  --spring.mvc.apiversion.use.header=API-Version \
  --spring.mvc.apiversion.supported=1,2 \
  --spring.mvc.apiversion.default=1

Make the invisible visible: the same URL four times: no header, version 1, version 2, version 3.

curl · Boot 4.2runs offline
$ curl -si localhost:18082/orders/7
HTTP/1.1 200 

{"id":7,"total":499.0}
$ curl -si -H 'API-Version: 1' localhost:18082/orders/7
HTTP/1.1 200 

{"id":7,"total":499.0}
$ curl -si -H 'API-Version: 2' localhost:18082/orders/7
HTTP/1.1 200 

{"id":7,"total":{"amount":499.0,"currency":"INR"}}
$ curl -si -H 'API-Version: 3' localhost:18082/orders/7
HTTP/1.1 400 

{"timestamp":"...","status":400,"error":"Bad Request","path":"/orders/7"}

What you see: no header gave the version 1 shape, because default=1. An explicit 1 gave it too. 2 gave the new object. 3 was refused with 400 Bad Request before any controller ran.

Why: the resolver (Fig. 22.20) read API-Version once, checked it against supported, and handed the resolved version to the mapping, which picked the method whose version attribute matched. The old Android app, which sends nothing, keeps getting version 1 without any change on its side.

Idiom: declare the version on the mapping, choose where it travels in properties

The problem: a response shape has to change, and old clients cannot. Teams answer with URL copies (/v2/...), duplicated controllers, and four different conventions across four services. Retiring a version means grepping.

How it works: one URL per resource. Each method says version = "N". A property chooses the transport (header, query, path, media type), the supported set and the default.

  1. Choose one transport for the whole company: a header is least intrusive; a path segment is easiest to try in a browser.
  2. List supported versions and a default so old clients keep working without changes.
  3. Add the new method with the new version; leave the old one untouched until usage is zero.
  4. Test it per version (below), then retire the old one on a date you announced.
One URL, several versions: GET /orders/7 Request API-Version: 2 Version resolver reads the header, checks supported = 1,2 v1 handler "1" total: 499.0 v2 handler "2" total: {amount, currency} 400 Bad Request version 3 is not supported 1, or none 2 3 The header, query parameter, path segment or media-type parameteris chosen in properties, not in each controller.
Fig. 22.20 — API versioning in Spring MVC. A resolver reads the requested version once, and each handler declares the version it serves.

Testing it: RestTestClient

Spring Framework 7 also adds RestTestClient, a fluent test client for HTTP endpoints. It looks like WebTestClient but does not need the reactive stack. In Boot 4 you add @AutoConfigureRestTestClient and inject it. This test compiled and passed on 4.2.0 against a real server on a random port:

OrderVersionTest.java · Boot 4.2runs offline
package com.quickbite.b4;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureRestTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.client.RestTestClient;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
        "spring.main.web-application-type=servlet", "spring.mvc.apiversion.use.header=API-Version", "spring.mvc.apiversion.supported=1,2"})
@AutoConfigureRestTestClient
class OrderVersionTest {
    @Autowired RestTestClient client;

    @Test void v2ReturnsMoney() {
        client.get().uri("/orders/7").header("API-Version", "2")
                .exchange()
                .expectStatus().isOk()
                .expectBody().jsonPath("$.total.currency").isEqualTo("INR");
    }
}
./mvnw test · Boot 4.2runs offline
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.02 s
[INFO] BUILD SUCCESS

The test sends API-Version: 2 and checks that the JSON path $.total.currency is INR. One more test with version 1 and a test with version 3 expecting 400 would pin the whole contract.

Other Boot 4 changes that you will meet

A short tour of the rest, each tied to where it is taught. Resilience annotations (@Retryable, @ConcurrencyLimit, @EnableResilientMethods) are now in Spring Framework itself: see the resilience section. The HTTP service registry (@ImportHttpServices) is in the HTTP client part above. JSpecify annotations (@Nullable, @NonNull from org.jspecify.annotations) appear in the PriceClient above; IDEs and static checkers such as NullAway can use them to warn about null, and Spring's own API is annotated with them.

And there is a spring-boot-starter-opentelemetry starter for OpenTelemetry traces and metrics; I confirmed that it exists and resolves, but I did not export any telemetry in this chapter, so see E4 · production for observability basics.

What 4.1 and 4.2 add (as far as I verified)
ReleaseChangeHow sure I am
4.1Spring gRPC auto-configuration for servers and clients.From the release notes; not built here. See the gRPC paragraph earlier in this section.
4.1Redis listener endpoints are auto-configured (a default RedisMessageListenerContainer).From the release notes; not run.
4.2RestTemplate and RestTemplateBuilder deprecated for removal.Verified by compiling: both warn "marked for removal".
4.2AMQP 1.0 support for RabbitMQ.From the release notes; I did not start a broker.
4.2Buildpacks image build cache; SSL bundle support for LDAP.From the release notes; not run.
4.2Some properties renamed, for example server.tomcat.redirect-context-root became server.tomcat.servlet.redirect-context-root.Verified in the next idiom with real warnings.

Property renames: let the migrator find them

The last migration morning surprise was silent. A property like server.tomcat.redirect-context-root=false was renamed, the old name was no longer read, and nothing failed. The behaviour just changed. You cannot grep for what you do not know was renamed.

Idiom: add spring-boot-properties-migrator during the upgrade, then remove it

The problem: renamed or removed configuration keys do not fail the build. The application starts with defaults where your setting used to be, and you find out in production.

How it works: the migrator jar reads Boot's own configuration metadata (the files that mark each property as deprecated and name its replacement). At startup it looks at your environment (files, environment variables, command line) and logs every key it recognises as renamed or no longer supported. For renamed keys it also temporarily maps the old key to the new one so the app still behaves.

  1. Add the dependency with runtime scope only for the upgrade branch.
  2. Start the application with each profile and read the startup log.
  3. Edit your configuration to the new keys until the warnings stop.
  4. Remove the migrator. It adds startup work and hides the problem it was meant to show.
pom.xml excerpt · Boot 4.2runs offline
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-properties-migrator</artifactId>
  <scope>runtime</scope>
</dependency>

Make the invisible visible: start with two old-style properties on the command line: server.tomcat.redirect-context-root and management.endpoints.enabled-by-default.

run · Boot 4.2 (trimmed, timestamps removed)runs offline
WARN  PropertiesMigrationListener :
The use of configuration keys that have been renamed was found in the environment:

Property source 'commandLineArgs':
        Key: server.tomcat.redirect-context-root
                Replacement: server.tomcat.servlet.redirect-context-root

Each configuration key has been temporarily mapped to its replacement for your
convenience. To silence this warning, please update your configuration to use the new keys.

ERROR PropertiesMigrationListener :
The use of configuration keys that are no longer supported was found in the environment:

Property source 'commandLineArgs':
        Key: management.endpoints.enabled-by-default
                Reason: Replacement key 'management.endpoints.access.default' uses an
                        incompatible target type

What you see: two different messages. The first key was simply renamed. The migrator mapped it for me and told me the new name. The second key was not mapped: its replacement, management.endpoints.access.default, has a different type (the old one was true or false; the new one takes an access level such as none), so a mechanical mapping would be unsafe. That one needs a human decision.

Why: the migrator can only rewrite what is safe to rewrite. Where meaning changed, it reports an error and leaves the decision to you, which is the correct behaviour.

The migration checklist, 3.5 to 4.2, in order

The order matters more than the list. Do the small jumps first, because each one has a smaller set of things that can be wrong.

  1. Get to the latest 3.5.x first. Do not jump from an old 3.x. Boot publishes its deprecations in the last release of the previous line, and your build tells you what to fix while the old behaviour still works.
  2. Fix every deprecation warning on 3.5. Compile with deprecation warnings visible. Replace RestTemplate with RestClient now: it exists in 3.5, and it is a change you can make before the big jump.
  3. Move to Boot 4.0 on its own. Change the parent, rename starters (-web to -webmvc, -aop to -aspectj, add -test starters), add missing module starters such as Flyway, change Jackson imports, replace @MockBean with @MockitoBean.
  4. Add the properties migrator, run every profile, fix keys, remove it.
  5. Diff your JSON. Serialise your real response classes with the old and new mapper (as above) and compare. Look for dates, property order and unknown-field handling in any code that builds its own mapper.
  6. Run the tests, then the slow checks: integration tests, a startup with the real database, Flyway migrations on a copy of production data, and a load test of the main path.
  7. Then 4.1 and 4.2. Fix the new deprecations, move the last RestTemplate users, and adopt features (API versioning, the HTTP service registry) as separate pull requests.
  8. Keep a rollback. Deploy the upgraded service to a small share of traffic first. Do not combine the upgrade with feature work.

Before you start, read the official Spring Boot 4.0 Migration Guide and the 4.1 and 4.2 release notes on the Spring wiki. This section is what I could verify on 4.2.0 in one afternoon, and the guide covers more than I could test, including Spring Security 7 and Hibernate 7 specifics.

12 · DrillSpring AOP, Ordering and Caching — Q1–Q35

The first thirty-five questions are about the proxy that sits in front of your beans. Interviewers use them to find out whether you know why @Transactional, @Cacheable, @Async and @Retryable sometimes do nothing, and whether you can predict what happens when two of them meet on one method.

Every answer points back to the primer: section 02 teaches Spring AOP from zero, section 03 teaches the interceptor chain, and section 04 teaches caching. The proxy and self-invocation basics are also in E4, section container and section data, so this drill does not re-teach them.

All outputs come from real runs on Spring Boot 4.2.0 (Spring Framework 7.1) and Java 25. The AOP and ordering programs are in code/e22-spring-in-depth/A/, the caching programs in B/, and the few extra ones written for this drill in F/. Each output block names its file.

Drill · Spring AOP fundamentals

These twelve questions test the vocabulary and the limits. A strong answer ties each word to something Spring really does, and names what Spring AOP cannot do before the interviewer asks.

Q1. "What is AOP, in plain words, and which problems does Spring solve with it?"

Reveal answer

Strong answer AOP stands for aspect-oriented programming. It is a way to write code that must run around many methods once, in one place, instead of pasting it into each method. Think of timing, logging, security checks, transactions, caching and retries.

Programmers call these cross-cutting concerns. They "cut across" the normal layers. Your OrderService, MenuService and PaymentService each have their own business job, but all of them also need to be timed, checked for permission and wrapped in a transaction. That repeated code is not business logic, and it hides the business logic.

Spring solves this with proxies. A proxy is a stand-in object that Spring puts in front of your bean. When another bean calls a method, the call goes to the proxy first. The proxy runs your extra code (the advice), then calls the real method, then maybe runs more extra code.

The Spring features you already use are built this way. @Transactional is a proxy that begins and commits a transaction. @Cacheable is a proxy that looks in a cache first. @Async is a proxy that hands the call to another thread. @PreAuthorize is a proxy that checks the user before the method runs. Learn one proxy and the rest stop being magic.

There are two limits to say out loud in an interview. Spring AOP only intercepts method calls on Spring beans, made through the proxy. It does not rewrite your classes. And it works at runtime, so it is easy to turn on, but it cannot advise a constructor, a field read or an object made with new (questions 8 to 10).

Use an aspect when the same extra behaviour applies to many methods and has nothing to do with the business rule: timing, audit, rate limits, logging. Do not use one to hide business rules. A reader of OrderService.place() should not need a second file to learn that an order gets charged.

Picture it Take QuickBite's "log how long every service call takes" requirement. The hand-written version pastes a timer into each method. The aspect version is one class.

Hand-written

Every method carries its own timer, and a new method needs a new copy.

PaymentService.java · Boot 4.2runs offline
public String charge(String id, int c) {
    long t0 = System.nanoTime();
    try {
        return doCharge(id, c);
    } finally {
        log("charge", t0);
    }
}
// ...and again in refund(), place(), cancel()

With an aspect

One class times every public method of every *Service bean.

TimingAspect.java · Boot 4.2runs offline
@Aspect
@Component
public class TimingAspect {
  @Around("execution(* com.quickbite.aop"
      + ".timing.*Service.*(..))")
  Object time(ProceedingJoinPoint pjp)
        throws Throwable {
    long t0 = System.nanoTime();
    try { return pjp.proceed(); }
    finally { /* print elapsed */ }
  }
}

The shift: The timer moved out of 40 methods and into one class, and the services went back to containing only business code.

Make the invisible visible: Call six service methods across three services and read what the one aspect prints.

output · Boot 4.2 (A/timing.out)runs offline
[timing] MenuService.price(..) took 66 ms
[timing] MenuService.items() took 7 ms
[timing] OrderService.place(..) took 36 ms
[timing] OrderService.cancel(..) took 14 ms
[timing] PaymentService.charge(..) took 122 ms
[timing] PaymentService.refund(..) took 84 ms

What you see: Six lines, one per call, and none of the three services contains a single line of timing code. The numbers follow the sleeps in the demo (60, 5, 30, 12, 120 and 80 ms) plus a millisecond or so.

Why: The proxy sits between the caller and each bean. Because the pointcut matches every method of every class named *Service, the same advice wraps all of them. See section 02 for the vocabulary and the annotation pointcut idiom for the version that targets only marked methods.

Land it I define AOP as running shared extra behaviour around many methods from one place, and I remember that in Spring it is always a proxy in front of a bean.

Likely follow-ups
"Is AOP not just hidden magic? It sounds like it makes debugging harder."

It can, when it is overused, so my rule is that an aspect may change how a method is run but not what the business rule is. Timing, audit and security are fine. A discount calculation is not.

The mechanism is not very magical. At startup Spring wraps the bean in a proxy object. When something fails, the stack trace shows the proxy frames (CglibAopProxy, ReflectiveMethodInvocation) between the caller and your method, which looks noisy but tells you exactly which layers were crossed.

To see what is applied to a bean, I print its advisors (question 17), or I turn on logging.level.org.springframework.aop=debug.

The honest cost is discoverability. Someone reading place() cannot see the audit line. I reduce this by using a custom annotation such as @Audited, so the method visibly says "audited" (question 11), and by keeping a short list of aspects in the project README.

"What is a cross-cutting concern, and which ones belong in an aspect?"

A cross-cutting concern is a requirement that touches many classes but is not part of any one class's job. If you can say "and the same for every service method" about it, it is cross-cutting.

Good candidates are timing and metrics, audit logs, permission checks, transaction boundaries, caching, retries, rate limiting and request-scoped logging context. Each is the same code around many methods, and each can be removed without changing the answer the method returns (except an exception raised by a permission check).

Poor candidates are anything that changes the result: pricing rules, validation of business invariants, choosing which supplier to call. These belong in plain methods where a reader and a unit test can see them.

A test I use: could I delete the aspect and still have a correct, merely slower or less observable, program? If yes, it is a fine aspect. If deleting it changes money or data, it is business logic in disguise, and I move it into a service.

"How is an aspect different from a servlet filter or a Spring MVC interceptor?"

A filter and an interceptor wrap web requests. They see an HTTP request and response and know nothing about your service methods. An aspect wraps method calls on beans, wherever they come from: a controller, a scheduled job, a message listener or a test.

That makes the aspect the right tool when the rule must hold for every caller. If audit logging lives in a filter, a nightly job that calls MenuAdmin.changePrice() is never audited. If it lives in an aspect on that method, every caller is covered.

The other way round, a filter is the right tool for things that exist only in HTTP: reading a header, setting a response header, rejecting an oversized body before Spring parses it. Question 84 in the integration drill lists the order in which filters, interceptors and argument resolvers run.

Many real systems use both. A filter puts a request id in the MDC, and an aspect on the service layer includes that id in the audit record.

"Does using an aspect slow my application down?"

Slightly, and almost never in a way you can notice. Each advised call goes through a proxy and an interceptor chain, which adds a few object allocations and method calls. That cost is measured in microseconds at most. I did not benchmark it for this course, so treat that as the usual order of magnitude, not a measured figure.

Compare it with what the advised methods do. A database call is milliseconds. A remote HTTP call is tens or hundreds of milliseconds. The timing demo above sleeps 60 ms in a method and the aspect adds less than the rounding error of the printout.

The cost that does matter is what your advice does. An aspect that writes a log line with the full argument list, or calls a remote audit service synchronously, can be slower than the method it wraps. Keep advice cheap, push slow work off the calling thread (with care, see the @Async questions), and never put a pointcut like execution(* *(..)) on the whole application.

For hot loops of tiny methods, such as a pure getter called a million times, do not advise them at all. Narrow the pointcut to the service layer.

Q2. "Aspect, join point, pointcut, advice, advisor, proxy, weaving — define each with one example."

Reveal answer

Strong answer I explain these with one running sentence: "An aspect (the class) says which calls (the pointcut) to intercept and what to run (the advice) at those join points. Spring builds an advisor from each piece and weaves them in with a proxy."

TermPlain meaningQuickBite example
Join pointA moment the framework could step in. In Spring AOP that is always a method execution on a bean.The call menu.price("biryani")
PointcutA rule that picks which join points to intercept.execution(* com.quickbite..*Service.*(..))
AdviceThe code that runs at a picked join point, and when (before, after, around).A method that prints elapsed milliseconds
AspectA class that bundles pointcuts and advice. Marked with @Aspect.TimingAspect
AdvisorSpring's own object: one piece of advice plus the pointcut that decides where it applies.The object Spring builds from TimingAspect.time()
ProxyThe stand-in object that receives the call and runs the advisors in a chain before the real bean.MenuService$$SpringCGLIB$$0
WeavingLinking aspects to target code. Spring AOP does it at runtime by creating proxies. AspectJ can do it at compile or class-load time.Spring starts the proxy when the bean is created

Two details trip people up. First, the word "join point" in AspectJ includes field reads, constructor calls and more, but in Spring AOP it only ever means a method call. Second, "advisor" is a Spring word, not an AspectJ word. You rarely write one by hand, but @Transactional, @Cacheable and @Retryable each show up in the proxy as one advisor, which is why you can print them (question 17).

Weaving by proxy means the aspect lives outside your class. Your MenuService has no idea it is advised. That is also why only calls that pass through the proxy are advised.

Picture it These words are easier to remember when you see the same call matched in several ways. The demo has three services and eight methods. Each pointcut below was printed with the exact methods it selected.

The setup: Eight methods are called, and each pointcut aspect prints the method names it matched.

Make the invisible visible: Run the seven pointcut aspects against the eight calls.

output · Boot 4.2 (A/pointcuts.out)runs offline
Methods called: price, items, setPrice, place, cancel, status, charge, refund
A execution(* OrderService.*(..))
      -> [OrderService.place(..), OrderService.cancel(..), OrderService.status(..)]
B within(PaymentService)
      -> [PaymentService.charge(..), PaymentService.refund(..)]
C @annotation(Audited)
      -> [MenuService.setPrice(..), OrderService.place(..)]
D @within(Sensitive)
      -> [PaymentService.charge(..), PaymentService.refund(..)]
E bean(menuService)
      -> [MenuService.price(..), MenuService.items(), MenuService.setPrice(..)]
F args(String, ..)
      -> [MenuService.price(..), MenuService.setPrice(..), OrderService.place(..), OrderService.status(..), Pa
G ... && !execution(* s*(..))
      -> [MenuService.price(..), MenuService.items(), OrderService.place(..), OrderService.cancel(..), Payment

What you see: The pointcut is the only thing that changes between lines A to E. The join points (the eight calls) and the advice (print the name) stay the same. Rule E, bean(menuService), picked three methods because they all belong to one bean, and rule C picked two because only two methods carry @Audited.

Why: A pointcut is a filter over join points, not a list of methods. Add a new method to OrderService tomorrow and rule A already covers it. That is the value over copy and paste. Question 5 compares these designators.

Land it I can define each word with a QuickBite example: the pointcut picks the method calls, the advice is the code that runs, the aspect holds both, and the proxy does the work at runtime.

Likely follow-ups
"What is the difference between an aspect and an advisor?"

An aspect is what you write: a class annotated with @Aspect that holds pointcuts and advice methods. An advisor is what Spring builds: one object that pairs a piece of advice with a pointcut. One aspect with three advice methods becomes three advisors.

This matters because the proxy works with advisors. When you print the chain of a proxied bean (question 17) you see advisors, not aspects. For an @Aspect method the printed chain shows the aspect and method name, and for @Transactional it shows BeanFactoryTransactionAttributeSourceAdvisor.

Spring also has advisors that are not written as aspects at all. @Cacheable is added by BeanFactoryCacheOperationSourceAdvisor, and no @Aspect class exists for it in the framework source. From the proxy's point of view they are all the same kind of thing.

So in an interview I say: "I write aspects, Spring runs advisors, and annotations such as @Transactional are advisors that Spring registers for me."

"Is a join point the method, or the call to the method?"

It is the execution of the method, at the moment a call arrives at the proxy. The same method called 100 times gives you 100 join points.

That is also why the term "method execution join point" appears in the Spring reference. In full AspectJ you can also advise a method call (the place that calls it), and that is a different join point kind, call(...). Spring AOP does not support call, only execution.

The practical effect is on the argument: pjp.getArgs() gives you the values of this call, and pjp.getSignature() gives you which method it is. Both belong to the join point and change on every call.

When someone says "the pointcut matched place()", they mean: at startup, Spring decided that place() is a method whose executions it should wrap. At run time, each of its calls then becomes a join point.

"What does weaving mean, and when does it happen in Spring?"

Weaving is the act of linking advice into the code it advises. With Spring AOP it happens when each bean is created. A bean post-processor looks at the new bean, asks "do any advisors match one of this class's methods?", and if so it returns a proxy instead of the bean. The container then hands out the proxy.

That is "runtime weaving" in the sense that no class file changes. Your .class files on disk are exactly what you compiled. You can see the result with getClass(), which prints MenuService$$SpringCGLIB$$0 for an advised bean.

AspectJ weaves at other times. Compile-time weaving rewrites the .class files during the build. Load-time weaving rewrites a class as the JVM loads it, using a Java agent (question 10 shows a real run). In both, the advice is inside the compiled code, so there is no proxy and no self-invocation problem.

The consequence I always mention: because Spring weaves at bean creation, objects made with new are never advised, and a bean that is not created by Spring is not advised either.

"If I write an @Aspect class but forget @Component, what happens?"

Nothing happens, and that is the problem. @Aspect only describes the class to the AspectJ annotation processing. It is not a Spring stereotype, so component scanning does not register it as a bean, and Spring never sees it.

No error appears. The pointcut simply never fires, which is why "my aspect does nothing" is one of the most common AOP questions.

The fix is to add @Component (or declare the aspect with a @Bean method). In Spring Boot 4 also check the dependency. Boot 4 replaced spring-boot-starter-aop with spring-boot-starter-aspectj, and without AspectJ on the classpath the @Aspect annotations are not processed at all.

My checklist when an aspect does not fire: is the class a bean, is spring-boot-starter-aspectj on the classpath, does the pointcut match (print AopUtils.isAopProxy(bean)), and is the call coming from another bean through the proxy and not from inside the class.

Q3. "The five advice types — when do you use each?"

Reveal answer

Strong answer There are five, and the quickest way to remember them is: three run at a point, one runs always, and one runs around everything.

AdviceRunsUse it forIt can change the result?
@BeforeBefore the method startsCheck arguments, set a context, count callsNo. It can only throw to stop the call.
@AfterReturningOnly after a normal returnLog or publish the resultIt can read it, not change it.
@AfterThrowingOnly after an exceptionAlert, count failuresIt can read the exception, not swallow it.
@AfterAlways, like finallyRelease something that @Before tookNo.
@AroundWraps the call: you decide when and whether to call itTiming, retries, caching, transactionsYes. You get the result, you can return another.

My rule is: pick the weakest advice that does the job. @Before and @AfterReturning cannot forget to call the method or lose its result, because the framework does that for you. @Around is the most powerful and the easiest to get wrong, so use it only when you need to measure the call, repeat it, skip it or change its result.

A detail from the Spring reference: within one aspect the order is @Around (outermost), @Before, then the method, then @AfterReturning or @AfterThrowing, then @After, then the rest of @Around. The demo below prints exactly that. Across different aspects the order is decided by @Order (question 15).

Picture it One method, all five advice types in one aspect, printed with a number for the order in which they ran. First the call that succeeds, then the call that throws.

Call returns

place("A-100") finishes normally, so @AfterReturning runs.

advice.out (A) · Boot 4.2runs offline
--- call 1: place("A-100") succeeds
  1 @Around     before proceed()
  2 @Before     args=[A-100]
      >>> place() body runs
  4 @AfterReturning result=placed A-100
  5 @After      (always, like finally)
  6 @Around     after proceed() (finally)
caller got: placed A-100

Call throws

place("bad-7") throws, so @AfterThrowing runs instead.

advice.out (A) · Boot 4.2runs offline
--- call 2: place("bad-7") throws
  1 @Around     before proceed()
  2 @Before     args=[bad-7]
      >>> place() body runs
  4 @AfterThrowing  ex=kitchen closed
  5 @After      (always, like finally)
  6 @Around     after proceed() (finally)
caller got exception: kitchen closed

The shift: Only the fourth line changes between a return and a throw, while @Around and @After run in both cases.

What you see: Line 3, the method body, sits between @Before and the after-advice. The @After line (5) printed in both runs, like finally. The @Around after-part (6) is last in both because @Around is the outer wrapper.

Why: @Around wraps everything else, so its "before" part runs first and its "after" part runs last, the onion shape you will see again in section 03. Fig. 22.3 draws the same timeline.

Land it I use the weakest advice that does the job, @Before or @AfterReturning for simple hooks, and @Around only when I need to time, repeat, skip or replace the call.

Likely follow-ups
"Why not just always use @Around? It can do everything."

Because it can also break everything, and the breakage is silent. With @Around you are responsible for calling pjp.proceed(), returning its result and letting exceptions through. Forget any one and you get the bugs in questions 6 and 7: a method that always returns null, or a failure that callers never see.

@Before and @AfterReturning cannot have those bugs. The framework calls the method and passes the result on for you. The advice method returns void, so there is nothing to forget.

There is also a readability argument. A reviewer who sees @Before knows at once that the aspect cannot change the result. A reviewer who sees @Around must read the body to find out.

So I treat @Around as the escape hatch. It is the right choice for timing (you need both sides of the call), caching and retries (you may skip or repeat the call), and for transactions. For audit lines I still lean towards @Around only because I want the outcome in one record.

"What is the difference between @After and @AfterReturning?"

@After runs always, whether the method returned or threw. It is the aspect version of a finally block. @AfterReturning runs only when the method returned normally, and it can receive the return value through returning = "result".

In the demo above, both runs printed the @After line, but only the successful call printed @AfterReturning. The failing call printed @AfterThrowing instead.

Use @After for clean-up that must happen even on failure, such as clearing a ThreadLocal that a @Before set. Use @AfterReturning for things that only make sense after success, such as publishing "order placed".

One trap: @After cannot see the result or the exception. If you need either, use @AfterReturning, @AfterThrowing or @Around with a try/catch.

"Can an after-advice change the return value or stop an exception?"

No. @AfterReturning can receive the return value, but if you change a mutable object it points to, the caller sees the change, and returning something else from the advice method does nothing. The advice method's own return value is ignored.

@AfterThrowing can read the exception, but the exception keeps travelling to the caller after the advice finishes. If you need to turn a failure into a fallback value, you must use @Around, catch the exception and return something else. Question 7 shows how to do that deliberately.

This is by design. It means after-advice is safe: a bug in it cannot silently change the business result. It can only throw its own exception, and that would replace the original one, so keep after-advice short and wrap risky code in try/catch.

In practice I use the after-advice types for observation (log, count, publish) and @Around for control.

"Do the five advice types run in the same order in every aspect?"

Within one aspect, yes. Since Spring Framework 5.2.7 the order is fixed: @Around, @Before, the method, then @AfterReturning/@AfterThrowing, then @After, and the closing half of @Around. The demo printed that order on Boot 4.2 and Framework 7.1.

Across several aspects on the same method, the order comes from each aspect's @Order (or the Ordered interface). Lower numbers are outer. Two aspects with the same order, or none, have no promised order, and the demos show them in registration order, which is not a contract.

Two aspects with an @Order of 1 and 2 print "enter 1, enter 2, method, exit 2, exit 1", the same onion shape as above. That output is in A/order.out and is explained in the primer's @Order section.

My habit: if the order between two aspects matters, I give both an explicit @Order and add a one-line comment saying why.

Q4. "Write a pointcut that matches every public method of every @Service class. Explain each part."

Reveal answer

Strong answer The pointcut is one line, and I read it from left to right.

Pointcut · Boot 4.2runs offline
@Pointcut("execution(public * "
        + "(@org.springframework.stereotype.Service *)"
        + ".*(..))")
void everyPublicServiceMethod() {}

Each part has one job. execution(...) is the designator that says "match method executions". public is the modifier pattern, so package-private and protected methods are skipped. The first * is the return type, meaning any return type including void. (@org.springframework.stereotype.Service *) is the declaring-type pattern: any class that carries @Service. .* means any method name. (..) means any number of arguments of any type.

An equivalent form that many teams find easier to read joins two simple pointcuts. The first half selects classes by annotation, the second keeps public methods.

Pointcut, two-part form · Boot 4.2runs offline
@Pointcut("@within(org.springframework.stereotype.Service)"
        + " && execution(public * *(..))")
void everyPublicServiceMethod() {}

Two cautions. Spring AOP only sees calls that arrive through the proxy from another bean, so a public method called from inside the same class is matched on paper but never intercepted (question 8). And annotation matching reads the annotation on the declaring class, so check what happens with classes that inherit from a @Service parent in your project before you rely on it.

Name the pointcut with @Pointcut and a method (everyPublicServiceMethod()), then reuse the name in advice. Then a wrong pointcut is fixed in one place.

Picture it A pointcut is easy to get wrong silently, so I always print what it matched. The demo has two @Service classes and one @Component. The MenuService has a public, a package-private, a protected and a private method.

The setup: A @Before aspect with the pointcut above prints the method it matched. The runner calls each method.

PcDemo.java (excerpt) · Boot 4.2runs offline
@Service
public static class MenuService {
    public String price(String item) { ... }
    String packagePrivate() { ... }
    protected String prot() { ... }
    private String hidden() { ... }
    public String callHidden() { return hidden(); }
}
@Aspect @Component
public static class Trace {
  @Before("execution(public * (@org.springframework"
      + ".stereotype.Service *).*(..))")
  void log(JoinPoint jp) {
    System.out.println("   matched: "
        + jp.getSignature().toShortString());
  }
}

Make the invisible visible: Run it and read which calls were matched.

output · Boot 4.2 (F/pc.out)runs offline
-- MenuService.price(..)
   matched: MenuService.price(..)
-- MenuService.callHidden() (calls a private method inside)
   matched: MenuService.callHidden()
-- MenuService.packagePrivate() and prot()
-- OrderService.place(..)
   matched: OrderService.place(..)
-- NotAService.hello() (a @Component, not a @Service)

What you see: price, callHidden and place were matched. packagePrivate and prot printed nothing because of the public in the pointcut. The private hidden() was called inside callHidden() and never appeared. NotAService.hello() printed nothing because the class is a @Component.

Why: Spring AOP matches the declaring class and the modifier in the pointcut, and then only intercepts calls that cross the proxy. Both filters are needed. The private call inside callHidden() is a plain Java call and does not go through the proxy at all.

Land it I write it as execution(public * (@Service *).*(..)), and I print what it matched, because a pointcut that matches nothing fails silently.

Likely follow-ups
"How do I match a whole package instead of a stereotype?"

Use within with a package pattern: within(com.quickbite.service..*). The two dots mean "this package and every sub-package", and the final * means any type inside. This selects all method executions in classes of that package, public or not (though Spring only intercepts calls through the proxy).

When to choose which: the stereotype form follows the role of a class, and it keeps working if somebody moves the class to another package. The package form follows the layout, which is easier to read but breaks silently when a package is renamed.

My preference is the annotation form for service-wide advice and within for a short list of packages when I need to exclude infrastructure code. In both cases I name the pointcut and print the matches in a test.

A useful guard is a test that loads the context and asserts that AopUtils.isAopProxy(bean) is true for the beans the pointcut should cover. If a refactor moves a class out of the pointcut, the test fails instead of production audit lines disappearing.

"Why did my package-private method not get advised?"

Two separate reasons can apply, and I check both. First, the pointcut above says public, so a package-private or protected method is simply not selected. Remove public and the pointcut selects them.

Second, what a proxy can intercept depends on its kind. A JDK interface proxy only sees interface methods, so non-public methods are out of reach. A CGLIB proxy can override protected and package-visible methods in many setups, and recent Spring versions apply annotation-driven features such as @Transactional to them, but the behaviour is easy to break with class loaders and with sub-packages. Check the reference for your version before you depend on it.

The robust rule is: put advice on public methods that are called from other beans. If you want to advise something non-public, that is a sign to move the method to its own bean (question 9 lists the options, including AspectJ weaving).

In the demo above, the prot() and packagePrivate() lines printed nothing, and that matched what I expected from the public filter.

"How do I match only methods with a particular argument or return type?"

Add more designators with &&. For arguments, args(String, ..) matches methods whose first argument is a String, and args(id) binds the argument to a parameter of your advice so you can use it. For the return type, change the first * in execution: execution(java.util.List *.*(..)) matches only methods that return a list.

In the pointcut demo, args(String, ..) matched five of the eight methods, which shows how broad it is on its own. I almost never use args alone. It is a filter to combine with execution, @annotation or within.

There is a cost to precision. A pointcut that names exact return types and exact argument types breaks when somebody changes a signature from int to long. Prefer pointcuts that name roles (an annotation, a stereotype, a package) over ones that name shapes (signatures).

When the matching rule is complicated, I stop and add a marker annotation like @Audited, so the rule becomes "has this annotation". Question 11 designs that.

"Where is the pointcut evaluated, at startup or at every call?"

Mostly at startup, then partly at call time. When a bean is created, Spring checks whether any advisor's pointcut can match any method of the class, and if so builds the proxy. That static check uses the method signature and the annotations on the class.

Some designators also need the real call. args(...), this(...), target(...) and @args(...) depend on the runtime types of the arguments and objects, so Spring checks them on each call. That costs a little more per call, which is the main reason to prefer the static designators (execution, within, @annotation) where you can.

The practical advice is simple: keep the pointcut as static as possible, because a static pointcut is cheaper and easier to reason about. If a runtime check is truly needed, put it in the advice as an if on pjp.getArgs() and measure.

A static check also explains an easy mistake. If the pointcut matches no method of a bean, no proxy is created for that bean, and you see the real class, not a $$SpringCGLIB$$ one, in getClass().

Q5. "execution versus within versus @annotation versus bean() pointcuts — when do you use each?"

Reveal answer

Strong answer Each one answers a different question about a call, so I choose by what I know about the code I want to wrap.

DesignatorQuestion it answersUse it whenCatch
execution(...)Does this method's signature match?You can describe the methods by package, name or shapeBreaks when names or signatures change
within(...)Is the code in this type or package?You want a whole class, package or layerSelects by location, not by role
@annotation(...)Does this method carry my annotation?You want opt-in on single methods (@Audited)Someone must remember to annotate
@within(...)Does the declaring class carry the annotation?The whole class opts in (@Sensitive)Reads the declaring class only
bean(...)Is the target a bean with this name?One named bean, or a name pattern like *ServiceSpring-only, ties the aspect to bean names

execution is the default for layered rules such as "every method in the service package". @annotation is the best choice for behaviour that a developer should switch on deliberately, because the code then says what it does. within is a shortcut for "everything in here". bean() is handy for one-off needs, for example wrapping a single client bean during an incident, but it is a Spring extension and is not portable to AspectJ.

You can combine them. within(com.quickbite.service..*) && !execution(* get*(..)) reads as "all service methods except getters".

My own order of preference for production code: @annotation for behaviour that must be explicit, execution or within for layer-wide rules, and bean() only for tactical, short-lived advice.

Picture it The pointcut demo runs seven rules against eight calls and prints the methods each rule selected. Below is the same code side by side: select by name (execution) and select by marker (@annotation).

By name

execution picks every method of OrderService, annotated or not.

Matches.java (excerpt)runs offline
@Before("execution(* OrderService.*(..))")
void byName(JoinPoint jp) { record("A", jp); }

By marker

@annotation picks only methods that carry @Audited.

Matches.java (excerpt)runs offline
@Before("@annotation(Audited)")
void byMarker(JoinPoint jp) { record("C", jp); }

The shift: The first rule follows where the code lives, the second follows what the developer wrote on the method.

Make the invisible visible: Same calls, seven rules.

output · Boot 4.2 (A/pointcuts.out)runs offline
Methods called: price, items, setPrice, place, cancel, status, charge, refund
A execution(* OrderService.*(..))
      -> [OrderService.place(..), OrderService.cancel(..), OrderService.status(..)]
B within(PaymentService)
      -> [PaymentService.charge(..), PaymentService.refund(..)]
C @annotation(Audited)
      -> [MenuService.setPrice(..), OrderService.place(..)]
D @within(Sensitive)
      -> [PaymentService.charge(..), PaymentService.refund(..)]
E bean(menuService)
      -> [MenuService.price(..), MenuService.items(), MenuService.setPrice(..)]
F args(String, ..)
      -> [MenuService.price(..), MenuService.setPrice(..), OrderService.place(..), OrderService.status(..), Pa
G ... && !execution(* s*(..))
      -> [MenuService.price(..), MenuService.items(), OrderService.place(..), OrderService.cancel(..), Payment

What you see: Rule A (execution) picked all three OrderService methods. Rule C (@annotation) picked only setPrice and place, the two annotated ones, in two different classes. Rule E (bean(menuService)) picked three methods because they share one bean.

Why: Rule G shows combining: ... && !execution(* s*(..)) removed setPrice and status. Real pointcuts are usually one selector plus one or two filters. The primer's pointcut table in section 02 lists the same seven rules.

Land it I choose by what I know: execution for layers, @annotation for opt-in behaviour, within for a whole package, and bean() only for tactical advice on one named bean.

Likely follow-ups
"What does @within do that within does not?"

within(com.quickbite.service..*) selects by where the type lives (a package or a class name). @within(com.quickbite.Sensitive) selects by an annotation on the declaring class. The first is about location, the second is about a marker.

In the demo, rule D @within(Sensitive) selected charge and refund because PaymentService is annotated @Sensitive at class level. Adding a new method to that class automatically brings it under the rule.

That is the value: a class-level annotation lets a team say "this whole class is sensitive" once. The advice then covers methods added later by someone who never read the aspect.

The pairing I use is @annotation for single methods and @within for whole classes, and I combine them with || when both should count. Like all annotation pointcuts, they read the annotation on the declaring class, so test inherited methods before you trust them.

"What are this and target, and when would I use them?"

Both restrict a pointcut by type at runtime. this(X) tests the proxy object, and target(X) tests the real bean behind it. With an interface-based JDK proxy they differ clearly: the proxy implements the interface but is not an instance of your class, so this(MyClass) fails while target(MyClass) succeeds.

Their main use is binding. target(service) in a pointcut lets the advice method receive the real object as a parameter, which is useful for logging its type or calling another method on it.

I use them rarely. Because they depend on runtime types they are checked on each call, which is more costly than a static pointcut (see the follow-up in question 4). And they are easy to confuse.

If you find yourself writing this(...) to pick classes, a stereotype or custom annotation is nearly always clearer. Keep target for the binding case and leave the rest.

"How do I pass the annotation or the arguments into my advice?"

Bind them by name in the pointcut. For an annotation: @Around("@annotation(audited)") plus a parameter Audited audited gives your advice the annotation instance, with its attributes such as audited.action(). The audit demo in question 11 uses exactly this.

For arguments: args(id, ..) binds the first argument to a parameter named id, and @Before("execution(* *(..)) && args(id, ..)") gives your advice String id directly. If you only need them occasionally, pjp.getArgs() returns all arguments as an Object[].

The names in the pointcut must match the advice parameter names. The compiler flag -parameters (Spring Boot's Maven parent turns it on) lets Spring read them, and a mismatch fails at startup with a message such as "formal unbound in pointcut", which is a loud failure and a good one.

Bind instead of casting. pjp.getArgs()[0] compiles but breaks quietly when somebody adds an argument at the front.

"Can I write one pointcut for classes that I do not own, such as repositories?"

Yes, because execution and within accept any type pattern, including third-party and Spring Data ones. The pattern below matches all methods of anything that implements Repository. The plus sign means "this type and its subtypes".

Pointcut over a library type · Boot 4.2runs offline
@Pointcut("execution(* org.springframework.data"
        + ".repository.Repository+.*(..))")
void anyRepository() {}

Spring Data repositories are themselves proxies, so advising them works through the same chain. I have used this for counting slow queries without touching the repository interfaces.

The catch is scope. A pointcut over framework types can match more beans than you expect, including internal ones. Print the matches once (as the demo does) and narrow it before it reaches production.

For beans you do not control and need to wrap in one place only, bean(name) is the shortest option. For a broader rule, within(com.thirdparty..*) with a tight execution filter keeps the match easy to read.

Q6 · Scenario. "An @Around advice made the method always return null. Why?"

Reveal answer

Strong answer The advice called pjp.proceed(), which runs the real method, but it did not return the result. In an @Around advice, the value your advice method returns is what the caller gets. If you throw the result away and return null, every caller sees null, however correct the real method was.

The buggy shape looks harmless.

BROKEN · Boot 4.2runs offline
@Around("execution(* OrderService.*(..))")
Object log(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println("[aspect] calling " + pjp.getSignature().getName());
    pjp.proceed();            // the result is thrown away
    return null;              // the caller always gets null
}

The fix is to keep the result and hand it back: Object result = pjp.proceed(); ... return result;. The return type of the advice method must be Object (or the exact type), never void, because a void around-advice makes no sense.

Two things make this bug nasty. First, a method with a primitive return type (int, boolean) cannot receive null, so Spring throws AopInvocationException. That crash is at least visible. Second, a method with an object return type just gets null, and the failure appears later, far from the cause, as a NullPointerException in the caller.

Prevention costs little: write one test per aspect that calls an advised method and asserts the real return value. Another option is to use @Before or @AfterReturning when you only observe, because those cannot lose the result.

Picture it The demo has three methods: receipt returns a String, total returns an int, and charge throws. The broken advice and the correct advice are shown on the same methods.

Broken

Calls proceed(), then returns null.

Aspects.java · Boot 4.2runs offline
Object log(ProceedingJoinPoint pjp)
        throws Throwable {
    pjp.proceed();
    return null;
}

Fixed

Keeps the result and returns it.

Aspects.java · Boot 4.2runs offline
Object log(ProceedingJoinPoint pjp)
        throws Throwable {
    Object result = pjp.proceed();
    return result;
}

The shift: The fix is two words: keep what proceed() returned, and return it.

Make the invisible visible: Run the three calls with the broken advice, then with the fixed one.

output · broken advice (A/around-forget.out)runs offline
[aspect] calling receipt
receipt(A-100) -> null
[aspect] calling total
total(A-100)   threw AopInvocationException: Null return value from advice does not match primitive return typ
[aspect] calling charge
output · fixed advice (A/around-ok.out)runs offline
[aspect] receipt returned receipt-A-100
receipt(A-100) -> receipt-A-100
[aspect] total returned 49800
total(A-100)   -> 49800

What you see: With the broken advice receipt printed null, and total died with an AopInvocationException whose message says "Null return value from advice does not match primitive return type". With the fix both returned their real values (receipt-A-100, 49800).

Why: The caller receives whatever the outermost advice returns, not what the method returned. The charge line in the first output shows another truth: the real method did run, so the gateway was charged. A wrong return is a bug in the answer, not in the work.

Land it When an around-advice returns null, I check whether it forgot to return the result of proceed(), and I fix it by returning that result and adding a test on the return value.

Likely follow-ups
"Why did the int method fail with an exception but the String method just returned null?"

Because Java cannot unbox null into an int. When the proxy gets null from the advice for a method declared as int, it cannot give the caller a primitive, so Spring raises AopInvocationException with the message "Null return value from advice does not match primitive return type".

For String or any object type, null is a legal value, so nothing complains. The caller receives null and the failure is delayed until somebody uses it.

This difference is a gift if you have primitives and a trap if you do not. A suite of tests that only exercises methods returning objects can pass for months with the broken aspect in place.

My habit is to put one primitive-returning method and one void method in the aspect's test, since they react to the bug differently. A void method hides it completely: the advice returns null, the proxy ignores it, and nothing looks wrong at all.

"How should I write a test that would have caught this?"

I write a small Spring test that loads only the aspect and a stub service, calls an advised method and asserts the returned value. With the broken aspect the assertion fails at once.

AspectReturnTest.java · Boot 4.2runs offline
@SpringBootTest(classes = {LogAspect.class,
                           StubOrderService.class,
                           AopAutoConfiguration.class})
class AspectReturnTest {
  @Autowired OrderService orders;

  @Test void adviceKeepsTheResult() {
    assertThat(orders.receipt("A-100"))
        .isEqualTo("receipt-A-100");
  }
}

The test also proves the aspect is applied at all, because the stub never returns the same thing if the aspect swallowed the result. I add assertThat(AopUtils.isAopProxy(orders)).isTrue() as a second assertion so the test fails if the pointcut stops matching.

This is a small unit-style test. It does not need a database or a web server, so it runs in a second or two and can stay in the default build.

I did not run this exact class for the course, but the same checks were made by hand in the demo above.

"When is it right to return something different from what proceed() returned?"

When the advice is the point: a cache returns the stored value without calling the method at all, a fallback aspect returns a default when the method fails, and a masking aspect redacts a field before the caller sees it.

In each of those cases the change is deliberate and documented. The mistake in the question is accidental: the author wanted to observe and forgot that @Around also controls the result.

If you want to modify, do it visibly. Return a new object instead of mutating the one proceed() returned, keep the change small, and name the aspect so a reader knows (PriceMaskingAspect, not LoggingAspect).

And if the change is "return a default on failure", prefer a real circuit breaker or fallback annotation in the resilience section of the primer, because a hand-written one has to get exception types, timeouts and metrics right as well.

"Can I just use @Before and avoid the problem?"

Yes, whenever you only need to observe or to stop the call. @Before runs, then the framework calls the method and returns its result. Your advice method returns void, so there is nothing to lose.

The same applies to @AfterReturning. It receives the result as a parameter and the framework still returns the original to the caller.

The limit shows up when you need both sides of the call, for example elapsed time (start in the before, stop in the after). You could store the start time in a ThreadLocal in @Before and read it in @After, but then you must clean it up and handle nested calls. An @Around with a local variable is simpler and safer for that job.

So the rule I give a team is: observation only, use @Before or @AfterReturning. Needs a stopwatch, a retry, a skip or a changed result, use @Around and write the return test.

Q7 · Scenario. "An @Around advice swallowed an exception, and callers saw success. How do you write it correctly?"

Reveal answer

Strong answer The advice caught the exception and did not rethrow it. Because @Around controls the call, a catch block that logs and then returns something turns a failure into a quiet success. The caller sees a normal return (often null) and carries on, so the order is placed, the next step runs, and nobody knows the payment failed.

The correct shape has three rules. Call proceed() once. Return its result. If you catch, rethrow the same exception after you have logged it.

CORRECT · Boot 4.2runs offline
@Around("execution(* OrderService.*(..))")
Object log(ProceedingJoinPoint pjp) throws Throwable {
    try {
        Object result = pjp.proceed();   // once, keep the result
        return result;                   // hand it back
    } catch (Throwable t) {
        System.out.println("[aspect] failed: " + t.getMessage());
        throw t;                         // the caller must see it
    }
}

Use throws Throwable on the advice method, because proceed() is declared that way and you must be able to rethrow whatever it threw, including checked exceptions. If your advice throws a checked exception that the advised method did not declare, Java wraps it in UndeclaredThrowableException, so rethrow the original and do not invent a new checked one.

There are legitimate reasons to catch. A fallback aspect catches a specific exception type on purpose and returns a safe value. That is a design decision, so catch the narrow type (PaymentUnavailableException), name the aspect for it, and record a metric, never catch (Throwable) and return null.

A related mistake is a second call to proceed() inside the catch as a hidden retry. On a non-idempotent method that charges the customer twice, and the demo below shows it.

Picture it Three versions of the same advice run against charge(), which throws "gateway down" on its first call. The first swallows, the second retries by calling proceed() twice, the third is correct.

Swallowed

Logs the failure, returns null. The caller thinks it worked.

Aspects.java · Boot 4.2runs offline
try {
    return pjp.proceed();
} catch (Throwable t) {
    log(t.getMessage());
    return null;
}

Correct

Logs the failure, then rethrows the same exception.

Aspects.java · Boot 4.2runs offline
try {
    return pjp.proceed();
} catch (Throwable t) {
    log(t.getMessage());
    throw t;
}

The shift: One word, throw t instead of return null, decides whether the caller learns about the failure.

Make the invisible visible: Run charge("A-100") with the swallowing advice and with the correct one.

output · swallowing advice (A/around-swallow.out)runs offline
[aspect] saw gateway down (charge attempt 1)
charge(A-100)  -> null
gateway was really charged 1 time(s)
output · correct advice (A/around-ok.out)runs offline
[aspect] charge failed: gateway down (charge attempt 1)
charge(A-100)  threw java.lang.IllegalStateException: gateway down (charge attempt 1)
gateway was really charged 1 time(s)

What you see: With the swallow, charge(A-100) -> null printed as if the call succeeded. The correct advice printed the same log line and the caller then saw threw java.lang.IllegalStateException: gateway down. The real gateway was charged once in both runs, so the swallowing version also hid a failed charge.

Why: The caller sees what the outermost advice returns or throws. Swallowing makes the caller's own try/catch and any outer transaction rollback useless, because no exception ever reaches them.

Land it I log in the catch and always rethrow the same exception, and I only catch a narrow type when I mean to turn failure into a fallback.

Likely follow-ups
"What does the hidden-retry version do, and why is it dangerous?"

It calls proceed() a second time inside the catch. The advice author meant to be helpful: "if it fails once, try again". On a method that is safe to repeat that may be fine. On charge() it sends a second money transfer.

output · hidden retry (A/around-twice.out)runs offline
receipt(A-100) -> receipt-A-100
total(A-100)   -> 49800
[aspect] first try failed, trying again
charge(A-100)  threw java.lang.IllegalStateException: gateway down (charge attempt 2)
gateway was really charged 2 time(s)

The last line is the damage: "gateway was really charged 2 time(s)". The first attempt may have reached the bank before the error, and the second sends another request. Nothing in OrderService shows a retry, so a code reviewer of that class will never find it.

A retry is a policy decision that needs a count, a delay, a list of exception types and, for money, an idempotency key (question 48). That is what @Retryable is for in Spring Framework 7, and the primer's resilience section covers it.

My rule is: an aspect that observes must not call proceed() twice, and an aspect that retries must be a real retry with limits, named as such.

"Should I catch Throwable or Exception in the advice?"

For a pass-through advice that rethrows, catch Throwable, because proceed() is declared to throw it and you want your log line for errors such as OutOfMemoryError or StackOverflowError too. Since you rethrow, you change nothing about how callers see it.

For an advice that handles a failure, catch the narrowest type that you really can handle, for example TimeoutException. Anything wider might catch exceptions that mean something else, such as IllegalArgumentException from a bug.

Never catch Throwable and return a value. That can hide Error subclasses that should stop the thread.

Also remember the finally form for clean-up. If your advice has to restore something (a timer, a ThreadLocal), put it in finally and leave the exception path alone. The timing aspect in question 1 does it this way.

"How can I log the exception without a stack trace appearing twice?"

If the advice logs the stack trace and rethrows, and a controller advice or the framework logs it again, the same failure appears twice. That is noise during an incident and makes error counts wrong.

The usual agreement in a service is that the exception is logged once, at the boundary where it is handled (for example the web layer). Inner layers either let it pass untouched or add context by wrapping it.

So in an aspect I log a short line with the method name and message, without the stack trace, and rethrow. The full trace is logged once at the top by whoever finally handles it.

If the aspect is the top (a scheduled job or message listener has no one above it), then log the trace there. I note in the aspect which of the two it is.

"Is it safe to read pjp.getArgs() in the catch block and log them?"

It is safe for the call, but not always safe for your data. Arguments can contain passwords, card numbers and personal data, and a log line is stored, shipped and searched by many people.

I log the argument types and a safe identifier, such as an order id, and never the whole array of Object. For a card payment the audit line should say which order and which amount, not the card.

There is also a cost: calling toString() on a large argument, such as a list of 10,000 items, can be slow, and a lazily loaded JPA entity can trigger database reads or a LazyInitializationException right in your log statement.

A custom annotation can carry the rule, for example @Audited(action="order.cancel") plus a parameter name, so only the intended fields are written. Question 11 builds that.

Q8. "Why doesn't Spring AOP intercept a call from one method to another in the same class?"

Reveal answer

Strong answer Because the interception lives in the proxy, and a call inside the class never touches the proxy. When another bean calls orderService.place(), it holds a reference to the proxy, so the advisors run. Inside place(), a call to confirm(...) really means this.confirm(...), and this is the real object, not the proxy. The call goes straight to the method, past every advisor.

This is called self-invocation. It is the cause behind most "my annotation does nothing" bugs, and it affects every annotation built on a proxy: @Cacheable (no caching), @Async (no new thread), @Transactional (no new transaction), @Retryable (no retry) and @PreAuthorize (no check).

In the demo, the same-class call to a @Cacheable method went to the database every time (three calls, 100 ms each), and the same-class call to an @Async method ran on main and blocked.

The ways to fix it, from the best to the last resort:

  1. Move the method into another bean: the caller then goes through that bean's proxy. This is the fix I want in most cases.
  2. Inject the proxy into the bean itself (self-injection with @Lazy) and call through the field.:
  3. Use AopContext.currentProxy() with exposeProxy = true, which couples the class to Spring AOP.:
  4. Switch to AspectJ weaving, where the advice is in the class and there is no proxy.:

The first option usually also improves the design: a method that needs caching or its own transaction is a separate responsibility.

Picture it Two experiments with the same shape: a method in the same class calls an annotated method, then another bean calls it. The first uses @Cacheable, the second @Async.

Same class

The method calls its own @Cacheable method on this.

MenuService.java · Boot 4.2runs offline
public String viaSame(String i) {
    return cachedPrice(i);    // this.cachedPrice
}

Other bean

The caller is another bean and holds the proxy.

OrderService.java · Boot 4.2runs offline
public String viaBean(String i) {
    return menu.cachedPrice(i);   // proxy
}

The shift: The cached method is identical in both runs, only the receiver of the call changed.

Make the invisible visible: Call each path three times and print the time and a database-call counter.

output · same class (A/selfinv.out)runs offline
   same-class call #1 -> Rs 249 in 101 ms, db calls so far: 1
   same-class call #2 -> Rs 249 in 100 ms, db calls so far: 2
   same-class call #3 -> Rs 249 in 100 ms, db calls so far: 3
output · other bean (A/selfinv.out)runs offline
   other-bean call #1 -> 24900 in 113 ms, db calls so far: 4
   other-bean call #2 -> 24900 in 0 ms, db calls so far: 4
   other-bean call #3 -> 24900 in 0 ms, db calls so far: 4

Make the invisible visible: And the same test for @Async.

output · Boot 4.2 (A/selfinv.out)runs offline
== 2. @Async: called from the same class vs from another bean
   send(A-100) runs on thread main
   same-class call returned after 300 ms
   send(A-101) runs on thread task-1
   other-bean call returned after 4 ms

What you see: Same-class: three calls, three database reads (counter 1, 2, 3), each about 100 ms. Other bean: the first call was a miss (113 ms) and the next two took 0 ms with the counter stuck at 4. For @Async, the same-class call ran on main and returned after 300 ms, while the call from another bean ran on task-1 and returned in 4 ms.

Why: this is the target, not the proxy. The annotation is on the method, but the proxy that reads it is never asked. Fig. 22.1 in section 01 draws the path, and the self-invocation idiom shows the fix. The @Transactional version of this trap is in E4, data.

Land it Inside a class, this.method() skips the proxy, so I move the annotated method to another bean and let the caller go through that bean.

Likely follow-ups
"How can I prove self-invocation is the cause and not something else?"

I print three facts at the top of the suspect method. AopUtils.isAopProxy(this) is false inside the bean, because this is the target. Thread.currentThread().getName() shows main for a method that should be async. And a call counter that goes up on every call shows the cache is not used.

A better check is outside the class: from the caller's side AopUtils.isAopProxy(orderService) should be true, and orderService.getClass() should show $$SpringCGLIB$$. If both hold and the behaviour is still missing, then self-invocation or a wrong pointcut is likely.

Spring also has a debug switch. logging.level.org.springframework.aop=trace and org.springframework.cache=trace show whether an interceptor was entered. For caching, a missing "Computed cache key" line for a call proves the interceptor never ran.

I teach juniors to ask first: "who is calling this method, and is it another bean?" That one question solves most cases.

"Is AopContext.currentProxy() an acceptable fix?"

It works, but I treat it as the last resort. You need @EnableAspectJAutoProxy(exposeProxy = true) so Spring stores the current proxy in a ThreadLocal, and then the method calls ((OrderService) AopContext.currentProxy()).confirm(id).

output · Boot 4.2 (A/cannot.out)runs offline
   [aspect] OrderService.placeViaOtherBean(..)
   body: confirmations.confirm(...) on ANOTHER bean
   [aspect] ConfirmationService.confirm(..)
   [aspect] OrderService.placeViaProxy(..)
   body: AopContext.currentProxy().confirm(...)
   [aspect] OrderService.confirm(..)

The output shows confirm was advised when called through the exposed proxy. So it works.

The costs are real. Your business class now imports a Spring AOP class and casts to itself, which makes it hard to test without Spring. The call fails with an IllegalStateException if the proxy was not exposed or if the code runs on another thread. And it tells the next developer that this class has a design problem.

I accept it in legacy code where moving the method would be a bigger risk than the cast. In new code I extract a bean. The primer's self-invocation fix ranks all the options.

"Does AspectJ weaving really remove the problem?"

Yes. With compile-time or load-time weaving the advice is woven into the class itself, so this.confirm() reaches the advice because the advice is already inside confirm(). There is no proxy to skip, so self-invocation is advised too. Question 10 has a real run showing a private method being advised.

For transactions, the switch is @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) with the spring-aspects dependency and a weaver. Caching and async have the same mode option.

The price is build and deployment complexity: a Java agent on the command line or the AspectJ compiler plugin, a build that fails differently, and a team that must learn to debug woven code.

Most teams never need it. If one class in a thousand has this need, extracting a bean is cheaper than changing how the whole application is built.

"Does the problem also appear when I call a method on a field that points to another bean?"

No. A field that Spring injected holds the other bean's proxy (if that bean is advised), so a call on it goes through the advisors. The demo's placeViaOtherBean() shows that: the aspect printed ConfirmationService.confirm(..).

The case that fools people is two beans that call each other, or a bean that gets itself through a method like getBean(OrderService.class) inside its own class. If you get the bean from the context, you get the proxy, so that also works, but it hides a dependency and is a service-locator smell.

A constructor-injected dependency on another bean is always the proxy when the other bean is advised. The one exception is a bean that is not created by Spring, such as an object made with new, which has no proxy at all.

So the rule is about the receiver of the call: if it is this, there is no proxy. If it is a Spring-injected field, there is.

Q9. "Which methods can Spring AOP not advise — private, final, static, constructors — and why?"

Reveal answer

Strong answer The reason is always the same: a proxy can only intercept what it can override and reach from outside. With CGLIB the proxy is a subclass of your class. With a JDK proxy it implements your interfaces. Anything the proxy cannot override or the caller cannot reach through it is invisible to AOP.

CaseAdvised?WhyWhat to do
private methodNoA subclass cannot override it and an outside caller cannot call itMake it a public method on another bean
final methodNo (it runs on the proxy object, so fields can be null)A subclass cannot override a final methodRemove final
final classFails at startup with CGLIBThe proxy must subclass itRemove final, or use an interface and a JDK proxy
static methodNoThere is no object to proxyWrap it in a bean
ConstructorNoThe proxy is created after construction, and Spring AOP only has method executionsUse @PostConstruct or AspectJ
Object made with newNoSpring never saw itLet Spring create it, or use AspectJ
Same-class callNothis is the targetQuestion 8

The two dangerous ones are the quiet ones. A private or static method simply is not advised and nothing tells you. A final method on a CGLIB proxy is worse: it executes on the proxy object itself, whose fields were never initialised, so it can read null where the real bean has a value.

Kotlin makes all classes and methods final by default, so Kotlin Spring projects use the kotlin-spring compiler plugin to open them. In Java the fix is to remove final from classes and methods that need advice.

Picture it One service calls six different things from place(), with an aspect on every service method. The printed lines show which calls the aspect saw.

The setup: OrderService.place() calls a same-class method, a private helper, a static method, a new PaymentClient(), and an injected PaymentClient. A final method shopName() is called from outside.

Make the invisible visible: Run the demo and read what the aspect printed.

output · Boot 4.2 (A/cannot.out)runs offline
bean class: OrderService$$SpringCGLIB$$0  (proxy: true)
-- 1. place(): what does the aspect see?
   [aspect] OrderService.place(..)
   body of place(): this.confirm(...)
   body of place(): private helper(...)
   body of place(): static tag(...)
   body of place(): new PaymentClient().charge(...)
   body of place(): injected payments.charge(...)
   [aspect] PaymentClient.charge(..)
-- 2. final method called on the proxy
   shopName() -> null

What you see: Only two aspect lines appeared: one for place() itself, and one for the injected payments.charge(...). The same-class call, the private helper, the static method and the new PaymentClient() were all invisible. The final method returned null, because it ran on the proxy object, whose copy of the field shop was never set.

Make the invisible visible: And a final class.

output · Boot 4.2 (A/finalcls.trim.out)runs offline
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class co
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class com.quickbite.aop.finalcls.Demo$Bil

Why: The CGLIB proxy subclasses the class, so final stops it. Spring tells you at startup for a final class ("Cannot subclass final class"), but not for a final method. The primer section on what Spring AOP cannot intercept repeats the table with the fixes.

Land it I remember it as: if the proxy cannot override it or reach it from outside, Spring AOP cannot advise it, so I make those methods public, non-final and call them from another bean.

Likely follow-ups
"Why did the final method return null?"

A CGLIB proxy is a subclass instance that holds a reference to the real bean. For each overridable method, the subclass forwards the call to the real bean after the advisors. A final method cannot be overridden, so the call runs the method body on the proxy object itself.

The proxy object was created without running your constructor (Spring uses Objenesis for that), so its fields still have default values. shopName() returned the field shop, which is null on the proxy but "QuickBite Central" on the real bean.

The same trap exists for any field access from outside the class, for example bean.name with a public field, or a getter marked final. The bug appears only when a bean is advised, which makes it look random between environments.

The fix is to remove final. If you must keep a final method, keep it free of state: make it a pure function of its arguments. And never rely on constructor side effects in a bean that is proxied.

"What are my options when I really need to advise a private method or a constructor?"

Three. First, refactor: move the code into a public method on a new bean. That is almost always the best answer, because a method important enough to advise is usually a separate responsibility.

Second, use AspectJ weaving, which advises private methods, constructors, field access and objects made with new. Question 10 shows the real output: with a load-time weaver, both hello() and the private secret() were advised on an object created by new.

Third, for constructor-like initialisation use Spring's own lifecycle hooks, @PostConstruct or InitializingBean, which run after the bean is wired. They are not advice, but they cover the "do something when the bean is born" need.

The one thing I avoid is reflection hacks that change a private method into a public one for the proxy's sake. They hide the real problem and break on the next upgrade.

"What happens with a protected or package-private method?"

It depends on the proxy type and the Spring version, so I do not rely on it. A JDK proxy only sees interface methods, so non-public methods are outside it. A CGLIB proxy can override protected and package-visible methods when it lives in the same package and class loader, and newer Spring versions apply annotation-driven features such as @Transactional to them.

The demo in question 4 used a pointcut with public, so prot() and packagePrivate() were not matched at all. That is the safe default: public methods only.

In practice I make advised methods public. If a method is not meant for outside callers, it should be private and not advised. If it is meant for other beans, it is public. The middle visibilities save nothing and add risk when a class moves to another package or class loader, for example with Spring Boot DevTools' restart class loader.

When a reviewer sees an annotation such as @Cacheable on a non-public method, the right question is "did you test it", and the right answer is a test, not an opinion.

"Can Spring advise a method that comes from a superclass or an interface default method?"

Yes for ordinary inherited public methods called through the bean. The proxy implements or extends the type and forwards each public method, including inherited ones. The pointcut must match, though. An execution(* OrderService.*(..)) pattern means methods of OrderService, and whether it includes methods declared in a parent depends on the type pattern. Use OrderService+.*(..) (with a plus) to include subtypes, and test inherited methods once before you trust the match.

Interface default methods are advised when called through the interface on a JDK proxy, and the same with CGLIB when the class does not override them.

Where I have been bitten is annotations. A @Cacheable on an interface method is read by Spring's cache support, but a @Cacheable on a superclass method may or may not be found, depending on how the annotation is looked up. The safe habit is to put annotations on the concrete class's own methods.

I check by printing the advisor chain (question 17) and by calling the method twice.

Q10. "Spring AOP versus AspectJ weaving — when would you use AspectJ?"

Reveal answer

Strong answer Spring AOP is proxy-based and runs at runtime. It can advise method executions on Spring beans, nothing else. AspectJ is a full AOP language that weaves advice into the bytecode, either when you compile (compile-time weaving) or when the JVM loads each class (load-time weaving). Because the advice sits inside the class, it can advise almost anything: private methods, constructors, field reads and writes, static methods, and objects created with new.

Spring's annotations (@Aspect, @Around, execution(...)) are the same ones AspectJ uses, so you write the same aspect either way. Only the machinery that applies it changes.

OptionPick it whenCost or catch
Spring AOP (proxies, the default)You advise service-layer methods on Spring beans, which is 95% of casesCannot see self-invocation, private, static or new objects
AspectJ load-time weavingYou need to advise code Spring does not create, or private methods, and a Java agent on the command line is acceptableNeeds -javaagent, aop.xml and a team that can debug woven bytecode
AspectJ compile-time weavingSame needs, but you want no agent at runtime and earlier errorsA different compiler step in the build and IDE setup
Not AOP: refactor into beansThe need is really "call this through the proxy"A small design change, no new tooling

My honest advice: stay on Spring AOP until a real requirement proves it cannot work. Typical reasons that do justify AspectJ are domain objects that Hibernate creates with new and that need injected services, auditing of field changes, and advising a legacy class you cannot turn into a bean.

Before choosing it I ask whether the same result is possible by moving the method to another bean (question 8). That usually costs less than changing how the application starts.

Picture it Here is one object made with new, calling its own private method, and one aspect that wants to advise every method of the class. First without AspectJ, then with the AspectJ weaver as a Java agent.

The setup: The class Plain has a public hello() that calls a private secret(). The @Aspect class prints before each execution. It is not a Spring bean. An aop.xml file names it for the weaver. The runner does new Plain().

Plain.java and LtwAspect.java · Boot 4.2runs offline
public class Plain {
    public String hello() { return "hello " + secret(); }
    private String secret() { return "from a private method"; }
}

@Aspect
public class LtwAspect {
    @Before("execution(* com.quickbite.ltw.Plain.*(..))")
    public void before(JoinPoint jp) {
        System.out.println("   [aspectj] before "
            + jp.getSignature().toShortString());
    }
}

Spring AOP only

No agent. Spring never saw the object, so nothing is advised.

run · no agent (F/ltw-off.out)runs offline
   result: hello from a private method

With the weaver

Run with the AspectJ weaver as a Java agent.

run · with agent (F/ltw-on.out)runs offline
   [aspectj] before Plain.hello()
   [aspectj] before Plain.secret()
   result: hello from a private method

The shift: The same jar and the same aspect now advise a new object and a private method.

run · Boot 4.2runs offline
$ java -javaagent:aspectjweaver-1.9.27.jar \
       -jar f-demo-0.0.1-SNAPSHOT.jar --demo=ltw

What you see: Without the agent the output has only the result line, because Spring AOP cannot see a new object. With the agent two advice lines appeared, one for hello() and one for the private secret().

Why: The weaver rewrote Plain as the JVM loaded it, so the advice is inside the class and does not need a proxy. That is also why self-invocation, private methods and new all work. The primer's AOP section has the full comparison table.

Land it I stay on Spring AOP by default and reach for AspectJ weaving only when I must advise private methods, constructors or objects that Spring does not create.

Likely follow-ups
"What does load-time weaving need in a Spring Boot application?"

Three things. The aspectjweaver jar, which Boot's spring-boot-starter-aspectj already brings. A file META-INF/aop.xml that lists the aspects and which packages to weave. And a Java agent on the command line: -javaagent:aspectjweaver-1.9.27.jar.

The aop.xml in the demo is five lines: the aspect's class name and <include within="com.quickbite.ltw.*"/>. Keep the include narrow. The weaver inspects every class the JVM loads, and a wide include slows start-up and can weave libraries you did not mean to.

Spring has its own helper, @EnableLoadTimeWeaving, but on a plain JVM the simple -javaagent flag is what I used and it is the clearest. In containers, put the flag in JAVA_TOOL_OPTIONS or the entry-point command.

Test it the way the demo does: run once without the agent and once with it, and compare the printed lines. A build that "works" without the agent only proves Spring AOP is working.

"Does AspectJ weaving work with Spring's @Transactional and @Cacheable?"

Yes, through a mode switch. @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) makes @Transactional woven by AspectJ instead of proxied, and @EnableCaching and @EnableAsync have the same mode attribute. You need the spring-aspects dependency and a weaver.

In that mode, self-invocation, private methods and new objects work for the annotation too. That is the reason people choose it: "I want @Transactional to work on my private method, from inside the class".

The cost is the one above, and a subtler one: the behaviour now depends on how the application is started. A unit test that does not use the agent runs without the transaction advice and may pass while production fails, or the other way round.

For almost every team I would rather extract a bean and keep one way of working in all environments.

"Why does the Spring reference still call it "Spring AOP" if it uses AspectJ annotations?"

Because Spring borrowed only the annotations and the pointcut language from AspectJ, and wrote its own proxy engine to apply them. When you write @Aspect and execution(...) in a normal Spring Boot application, no AspectJ weaving happens. Spring parses the same expressions (with the AspectJ library's pointcut parser) and builds proxy advisors.

That is why the supported pointcut designators are a subset: execution, within, this, target, args, @annotation, @within and a few more, plus Spring's own bean(). Designators such as call, get, set and initialization belong to full AspectJ and fail with an "unsupported pointcut primitive" error under Spring AOP.

Boot 4 reflects this in its starter name: spring-boot-starter-aspectj supplies the AspectJ library (the annotations and the parser), and not a weaver you must run.

I explain it as: same language, two engines. Spring AOP is the small, proxy-based engine. AspectJ is the full one.

"Is there a performance difference between the two?"

Yes in principle, and I did not measure it here, so take this as the usual picture. Woven advice is compiled into the method, so a call has no proxy hop and no interceptor chain. A proxy adds a small, fixed cost per call: building the invocation object and walking the chain.

For service methods that touch a database or a network, that cost disappears next to the work, so it does not decide the choice. For a method called millions of times in a tight loop it could matter, and that is also a case where you would not want any advice on it.

The start-up cost goes the other way. Load-time weaving adds work to every class load, so start-up is slower, and with a wide include it is noticeably slower. Compile-time weaving moves that cost to the build.

So the decision is about capability and operations, not speed. I choose AspectJ because I need something Spring AOP cannot do, not because I expect a faster application.

Q11 · Design. "Design an @Audited annotation and aspect that records who changed what, with minimal overhead."

Reveal answer

Strong answer I design it in four decisions: how the developer opts in, how the aspect finds who and what, where the record goes, and what it costs.

Opt-in. A small annotation on a method: @Audited(action = "price.change"). A pointcut @annotation(audited) selects only those methods, so there is zero cost for every other method, and the code says in plain view that the change is audited.

Who and what. "Who" comes from the security context (SecurityContextHolder) or a request-scoped holder, read on the calling thread. "What" is the action name, the method's identifying arguments (an order id, an item name) and the outcome, success or failure. I do not dump every argument, because arguments can hold personal data.

Where it goes. For records that must match the data, write the audit row in the same transaction as the change. With the measured default order (transaction, then your aspect), a plain aspect runs inside the transaction, so its insert commits or rolls back together with the change. A failure record would roll back with it, so write failures to a log or a separate REQUIRES_NEW call.

Cost. The pointcut is static, so unannotated methods pay nothing. The advice builds one small string and one insert. I would not make it @Async: audit rows that vanish on crash defeat the purpose (question 44).

Finally, I test it: a test that calls an audited method and checks the row, and a test that checks an unaudited method writes none.

Picture it The demo is the small version of this design: an annotation, an @Around aspect that reads the current user and builds the "what", and the three kinds of outcome. Three methods are called: changePrice and cancel are annotated, list is not, and one cancel fails.

Audited.java and AuditAspect.java · Boot 4.2runs offline
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Audited { String action(); }

@Around("@annotation(audited)")
Object audit(ProceedingJoinPoint pjp, Audited audited)
        throws Throwable {
    String who = CurrentUser.get();
    String what = audited.action() + " "
        + Arrays.toString(pjp.getArgs());
    try {
        Object result = pjp.proceed();
        System.out.println("AUDIT user=" + who
            + " action=" + what + " outcome=OK");
        return result;
    } catch (Throwable t) {
        System.out.println("AUDIT user=" + who
            + " action=" + what + " outcome=FAILED " + t.getMessage());
        throw t;
    }
}

Make the invisible visible: Run the three calls and read the audit lines.

output · Boot 4.2 (A/audited.out)runs offline
   (changing biryani to 25900)
AUDIT user=asha@quickbite.test action=price.change [biryani, 25900] outcome=OK
   (cancelled A-100)
AUDIT user=asha@quickbite.test action=order.cancel [A-100] outcome=OK
AUDIT user=asha@quickbite.test action=order.cancel [shipped-7] outcome=FAILED already shipped
   caller saw: already shipped

What you see: Two annotated calls produced outcome=OK, the failing cancel produced outcome=FAILED already shipped, and the caller still saw the exception. list() is not annotated and produced no audit line at all.

Why: @annotation(audited) is a static pointcut, so only marked methods are touched, and the aspect rethrows, so it never changes behaviour. See the annotation pointcut idiom in section 02.

DecisionMy choiceReason
WhoSecurity context on the calling threadLost on another thread, so do not audit inside @Async code
WhatAction name plus identifying argumentsAvoids leaking personal data
WhereSame transaction as the change, failures via REQUIRES_NEW or logRow exists if and only if the change committed
CostStatic pointcut, one insertUnannotated code pays nothing

Land it I make the audit opt-in with a custom annotation, read the user on the calling thread, write the row in the same transaction as the change, and keep the advice to one cheap insert.

Likely follow-ups
"Should the audit row be written in the same transaction as the change?"

For a record of what really changed, yes. If the audit row is in the same transaction, the two commit together or roll back together, so you can never have a price change without its audit row, or an audit row for a change that never happened.

The ordering matters. By default the measured chain is cache, then transaction, then your aspect, so a plain aspect runs inside the transaction. If you give the aspect @Order(HIGHEST_PRECEDENCE) it moves outside the transaction, and its insert then runs in its own transaction or none at all (question 15).

The drawback: a failed change rolls back, and its audit row rolls back with it. If you must record failures, write them separately, for example in a REQUIRES_NEW method or a log line, so they survive the rollback.

Some regulated systems want the opposite, a record of attempts even when they fail. In that case the aspect goes outside the transaction on purpose and writes in its own transaction. State the choice in a comment.

"How do I record the old and new values, not only the arguments?"

The aspect alone cannot see them, because it only knows the arguments and the result. For field-level history I use the persistence layer: Hibernate Envers, or JPA entity listeners (@PreUpdate) that write a history row with before and after values.

A simple pattern for service methods: the audited method returns a small change object, PriceChange(item, oldCents, newCents), and the aspect puts its fields in the record through a known interface. The service knows both values at the moment of the change.

Do not load the old row inside the aspect just for the audit. That adds a query to every call, which breaks the "minimal overhead" goal, and the old value may change between your read and the real update.

I choose the layer by the question: "who called what" belongs to the aspect, and "which columns changed" belongs to the data layer.

"How do I test that the right methods are audited?"

Two tests. A positive test calls an annotated method inside a Spring test with a known user and asserts that one audit record exists with the right user, action and outcome. A negative test calls an unannotated method and asserts that no record was written.

For a safety net across the whole code base, a small reflective test can scan the service classes for methods whose names start with change, cancel or delete and fail if one lacks @Audited. The rule is crude but it catches a forgotten annotation before production does.

Test the failure path too: a call that throws must produce a FAILED record, and the exception must still reach the caller, which proves the aspect rethrows (question 7).

I also assert AopUtils.isAopProxy(service). If somebody removes the aspect starter or breaks the pointcut, that single assertion fails loudly.

"What about audit in code that runs on another thread?"

The user is the first thing lost. The SecurityContextHolder and any ThreadLocal are bound to the calling thread, so inside an @Async method or a scheduled job the user is anonymous or missing. The @Async questions below (question 41) show the fix with a task decorator.

My rule is to capture the user before the hop. The aspect on the web thread reads the user and passes it as an argument to the async work, or the executor copies the context. Do not read the user lazily inside the worker.

For jobs that have no user, audit them as a system user with a fixed name such as system:invoice-job. A record with a clear system identity is more useful than one with "anonymous".

And keep the audit write itself synchronous. If the audit row is queued to a background thread, a crash or a deploy drops it, which is the exact failure the audit exists to prevent.

Q12. "JDK proxy or CGLIB proxy — how does Spring choose, and what breaks with each?"

Reveal answer

Strong answer Spring has two ways to build a proxy. A JDK dynamic proxy (java.lang.reflect.Proxy) creates a new class that implements the interfaces of your bean. CGLIB creates a subclass of your bean's class. Both forward each call through the advisor chain and then to the real object.

The choice follows one rule: if proxyTargetClass is true, use CGLIB. If it is false, use a JDK proxy when the bean implements at least one interface, and CGLIB otherwise. Spring Boot sets spring.aop.proxy-target-class=true by default, so in Boot you get CGLIB almost always, even for beans that have an interface.

What breaks with each:

ProxyWhat breaksHow it shows up
JDK proxyYou cannot inject or look up the bean by its class, only by its interface. Methods that are not on the interface are not reachable on the proxy.NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException
CGLIB proxyfinal classes cannot be subclassed. final and private methods are not advised. The class needs a visible constructor setup.Startup failure for a final class, silent skipping for methods

Since Spring 4 the constructor of a CGLIB bean is not run a second time for the proxy (Objenesis), so a constructor with side effects is no longer a problem.

I leave Boot's default (CGLIB) alone. It gives the fewest surprises, because code that injects a class keeps working. If a team wants strict interface-based design, they set the property to false knowingly and inject interfaces everywhere.

Picture it The same bean runs twice, once with Boot's default and once with --spring.aop.proxy-target-class=false. The bean implements an interface Pricing. The demo prints the proxy class, then looks the bean up by interface and by class.

CGLIB (Boot default)

A subclass of the class. Lookup by class works.

application.properties · Boot 4.2runs offline
spring.aop.proxy-target-class=true

JDK proxy

Implements the interface only. Lookup by class fails.

application.properties · Boot 4.2runs offline
spring.aop.proxy-target-class=false

The shift: One property flips the proxy kind, and the same code that injected the class now fails.

output · default run (F/jdk.out)runs offline
bean class      : com.quickbite.jdk.JdkDemo$MenuService$$SpringCGLIB$$0
is JDK proxy    : false
is CGLIB proxy  : true
implements      : [SpringProxy, Advised, Factory]
   [aspect] before
by interface    : 24900
output · proxy-target-class=false (F/jdk-iface.out)runs offline
bean class      : jdk.proxy2.$Proxy102
is JDK proxy    : true
is CGLIB proxy  : false
implements      : [Pricing, SpringProxy, Advised, DecoratingProxy]
   [aspect] before
by interface    : 24900
by class        : NoSuchBeanDefinitionException: No qualifying bean of type 'com.quickbite.jdk.JdkDemo$MenuSer

What you see: Default run: MenuService$$SpringCGLIB$$0, "is CGLIB proxy: true". With the property off: jdk.proxy2.$Proxy102 that implements Pricing. The aspect fired in both. Only the second run threw NoSuchBeanDefinitionException when the class was requested.

Why: A JDK proxy is not an instance of your class, it is only an instance of its interfaces. So anything that asks for the class type fails to find the bean. A CGLIB proxy is a subclass, so it passes every instanceof and injection test. This is the main reason Boot made CGLIB the default.

Land it Spring Boot uses CGLIB proxies by default, so I inject classes freely, and I remember that final classes and final methods are the things that break.

Likely follow-ups
"Why did Spring Boot switch the default to CGLIB?"

Because injecting by class is common in real code, and with JDK proxies it fails in a confusing way. A developer writes @Autowired MenuService menu, adds @Transactional to the class, and the application stops with "bean is of type $Proxy, expected MenuService". That error cost many people hours.

Boot 2.0 changed the default to spring.aop.proxy-target-class=true, so the proxy is a subclass and the injection works whether the bean has an interface or not. The measured demo confirms it on 4.2: the default run produced a $$SpringCGLIB$$0 class.

There is also a consistency benefit. Whether a bean implements an interface does not change its proxy kind, so adding an interface later cannot suddenly break an injection point.

The cost is the final-class and final-method rules, which are easy to follow, and a bit more memory for generated classes. I accept both.

"When would I deliberately choose a JDK proxy?"

When the design says "callers depend on interfaces only" and I want the framework to enforce it. With proxy-target-class=false and a bean that implements an interface, the only way to use the bean is through the interface, which stops a teammate from injecting the concrete class.

A second reason is a class that cannot be subclassed: a final class from a library that you wrap in a bean, with an interface in front. A JDK proxy works there, where CGLIB fails at startup.

A third is Java platform code that expects interfaces, such as some remoting setups.

I rarely make this choice across the whole application. When I do, I set spring.aop.proxy-target-class=false for the whole application and design every bean around an interface, so the rule is the same everywhere.

"How do I tell which kind of proxy a bean has at runtime?"

Use Spring's AopUtils. AopUtils.isAopProxy(bean) tells you if it is a proxy at all, AopUtils.isJdkDynamicProxy(bean) and AopUtils.isCglibProxy(bean) tell you the kind, and AopUtils.getTargetClass(bean) returns the real class behind it. The demo above printed all of these.

For the chain, cast to Advised and print getAdvisors(); question 17 does that. ((Advised) bean).getTargetSource().getTarget() gives you the real object, which is useful in a test that wants to bypass the proxy.

The class name is a quick hint too: $$SpringCGLIB$$ means CGLIB, and jdk.proxy2.$Proxy102 or com.sun.proxy.$Proxy means a JDK proxy.

In production code you should almost never need these calls. If you find yourself asking whether a bean is a proxy, you probably have a self-invocation or a type-injection problem to fix instead.

"Does Spring Data use JDK or CGLIB proxies?"

Repository interfaces are proxied with JDK proxies, because a Spring Data repository is only an interface. Spring creates an implementation object and wraps it in a JDK proxy that implements your repository interface, then adds advisors such as the transaction and exception-translation ones.

That is why you always inject a repository by its interface and why @Autowired SomeRepositoryImpl would never work. There is no class to inject.

When a custom aspect advises a repository, the pointcut must therefore match on the interface, as in the Repository+ pattern from question 5. A pointcut written against a concrete repository class will not find one.

Everything else in this answer still applies to your own services: those are classes, and with Boot's default they get CGLIB proxies.

Drill · Ordering the interceptor chain

These six questions test whether you can predict what runs first when several annotations meet. Every answer here uses the order measured on Spring Boot 4.2.0: retry, cache, transaction, your aspect, then the method.

Q13. "@Transactional, @Cacheable, @Async and @Retryable are all aspects. How are they ordered on one method?"

Reveal answer

Strong answer Each annotation adds an advisor to the same proxy, and the advisors run as a chain, outermost first. On Spring Boot 4.2 with defaults I measured this order for a bean that has @Retryable, @Transactional, @Cacheable and one custom aspect:

  1. Retry: the @Retryable advisor is always outermost. Spring Framework 7 adds it first, whatever order you configure.
  2. Expose: an internal ExposeInvocationInterceptor that makes the current call available to the others.
  3. Cache: the @Cacheable interceptor, so a hit returns before anything below it runs.
  4. Transaction: the @Transactional interceptor opens the transaction.
  5. Your aspect: an unordered custom aspect sits in registration order, which is not a promise.
  6. Target: your method.

@Async is different. Its advisor has the order Integer.MIN_VALUE, so it is outermost on its bean. It does not run the rest of the chain on the caller's thread at all: it hands the whole call to an executor, and the rest of the chain (retry, cache, transaction) then runs on the worker thread. That is why @Async @Transactional starts its transaction on task-1.

What this means in practice:

  • A cache hit opens no transaction and never reaches your aspect.
  • Each retry attempt gets a fresh transaction and a fresh cache lookup.
  • An aspect with @Order(HIGHEST_PRECEDENCE) moves up, but even then it still runs inside retry, once per attempt.

Three of these (cache, transaction, an unordered aspect) report the same order value Integer.MAX_VALUE, so their relative position comes from registration order. I measured it, but if your design depends on it, set the order explicitly (question 15). Fig. 22.4 in section 03 draws the onion.

Picture it The stacked demo has one method with @Retryable, @Transactional and @Cacheable, plus a timing aspect. The first output is the chain printed from the bean itself, outermost first. The second is a call that fails twice before it works.

output · advisor chain (A/stacked.out)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  4. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$Plain.around
advisor chain of NotificationService (@Async @Transactional):
  1. order=-2147483648 AsyncAnnotationAdvisor / AnnotationAsyncExecutionInterceptor
  2. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor

Make the invisible visible: Call the method once (cache miss, two failures) and once more (cache hit).

output · Boot 4.2 (A/stacked.out)runs offline
== (a) first call: cache miss, fails twice, third attempt works
      [aspect] enter price
      price() attempt 1, transaction active = true
      [aspect] exit  price after 5 ms
      attempt 1 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 2, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 2 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 3, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 3 transaction COMMITTED
   result 24900 after 305 ms
== (b) second call: cache hit
   result 24900 after 2 ms
method body ran 3 times in total

What you see: The chain lists retry first, then the exposure interceptor, cache, transaction and the aspect. The NotificationService chain (@Async @Transactional) starts with the async interceptor. Call (a) entered the aspect and a new transaction three times, rolled back twice and committed on the third attempt. Call (b), the cache hit, printed no aspect line and no transaction line, and took 2 ms.

Why: Retry is outside, so it can start a new attempt, with a new transaction and a new cache lookup. The cache is outside the transaction, so a hit costs no database connection. The method body ran three times in total, because the second call never reached it. Compare the retry-outside-transaction idiom.

Land it I say it in one line: retry outermost, then cache, then transaction, then my aspect, then the method, and @Async hands the whole chain to another thread first.

Likely follow-ups
"Why does a cache hit not open a transaction?"

Because the cache interceptor is outside the transaction interceptor in the measured chain. On a hit, CacheInterceptor returns the stored value and never calls proceed(), so the TransactionInterceptor below it is never entered. No transaction begins, no connection is taken from the pool, and nothing reaches the database.

This is the order you want. A cache exists to avoid the cost of the database call, and a transaction around a cache hit would waste a connection on every request. The demo's call (b) took 2 ms and printed no transaction line.

The reverse order (transaction outside, cache inside) would open a transaction on every call and hold it while the cache answers. The txFirst variant in the demo folder shows that this order is possible if you configure it, and the cache hit then runs inside an open transaction.

So the default is the efficient one. Keep it unless you have a reason, such as a cache that must read data inside the same transaction snapshot, which is rare.

"Why does @Async run before everything else?"

Because the call has to leave the caller's thread before any of the other work starts. If the transaction were opened first on the caller's thread and then the method ran on another thread, the transaction would not follow the call: transactions are bound to a thread. The async interceptor therefore wraps the whole chain and submits it as one task.

Its order, Integer.MIN_VALUE, makes it the first advisor on its bean. The remaining advisors run later on the worker thread. In the demo, the NotificationService chain printed the async interceptor first and the transaction interceptor second.

That explains a common surprise. With @Async @Transactional on one method, the transaction belongs to the worker thread, and the caller's transaction (if it has one) is a different one. A caller that has not committed yet can run the worker before its data is visible. The demo A/asynctx.out printed thread main with a transaction and then task-1 with another one.

The primer covers the fix in section 05: pass identifiers, and start async work after the commit.

"Does the order of the annotations in my source file matter?"

No. Writing @Transactional above @Retryable or below it changes nothing. The annotations are not read in source order. Each one is found by its own bean post-processor, which adds an advisor, and the order of the advisors comes from their order values.

The demo class declares @Retryable @Transactional @Cacheable in that order, but the measured chain is retry, cache, transaction, which is a different order. The order in the file is a reading order for humans.

This is worth saying because many developers believe the annotation closest to the method runs first, as with decorators in some other languages. In Spring that is not how it works.

If the order matters to you, set it in the places that control it: @Order on aspects, and the order attribute on @EnableTransactionManagement, @EnableCaching and @EnableAsync. Then it is written down in code and not left to registration.

"Is the measured order guaranteed to stay the same in the next Spring version?"

Only some of it. The statement "the @Retryable advice always runs outside @Transactional and @Cacheable" is a documented rule of Spring Framework 7. I would rely on it.

The relative order of cache, transaction and a custom aspect, when none of them has an explicit order, comes from equal order values and registration order. That is an implementation detail. It was stable in my runs on Boot 4.2.0, but a later release could change which post-processor registers first.

My practice: if a design needs "cache outside transaction", say so in the configuration (@EnableCaching(order = ...)) and add a test that checks the order by printing the advisor chain (question 17). Then a framework change fails a test instead of production.

For a rule that nobody relies on, such as the order of two unrelated timing aspects, I do not bother.

Q14 · Scenario. "@Retryable on a @Transactional method kept failing because every attempt reused the same broken transaction. What happened, and how does Spring Framework 7 order them now?"

Reveal answer

Strong answer This is the classic "retry inside the transaction" bug. When the retry loop sits inside an open transaction, every attempt joins that one transaction. The first failure marks it rollback-only. From then on the transaction is doomed: later attempts may even succeed in Java, but at the end the commit fails with UnexpectedRollbackException ("Transaction silently rolled back because it has been marked as rollback-only"). No attempt ever had a clean transaction.

Why it happens: a @Transactional method called from inside another transaction joins it by default (REQUIRED). An exception that leaves the inner method marks the shared transaction rollback-only, and catching the exception in the outer method does not clear the mark.

The order matters. With the older Spring Retry library the order of its advice against @Transactional depended on the order settings, and with the wrong setting the retry ended up inside the transaction (check your version), or a hand-written retry loop lived inside a @Transactional method.

Spring Framework 7's @Retryable removes the choice: its advice always runs outside @Transactional and @Cacheable, whatever order is configured. Each attempt starts a new transaction, the failed one rolls back cleanly, and the next attempt starts from a fresh state.

The rules that follow: retry around the transaction, never inside it. Only retry operations that are safe to repeat (question 48). And remember that a retry of a method that has already committed side effects elsewhere repeats those effects too.

Picture it Two runs of the same failing method, one with the loop inside the transaction and one with Framework 7's @Retryable. The method fails twice with "db timeout" and works on the third attempt.

Retry inside

A loop inside a @Transactional method. All attempts share one transaction.

PriceService.java · Boot 4.2runs offline
@Transactional
public int price(String item) {
  for (int i = 1; i <= 3; i++) {
    try { return loader.load(item, i); }
    catch (IllegalStateException e) {}
  }
  throw new IllegalStateException();
}

Framework 7

@Retryable is outside the transaction. Each attempt gets its own.

MenuService.java · Boot 4.2runs offline
@Retryable(maxRetries = 3, delay = 50)
@Transactional
@Cacheable("prices")
public int price(String item) {
  // fails twice, then works
}

The shift: Moving the retry from inside the transaction to outside it turns one doomed transaction into three independent ones.

Make the invisible visible: Run both.

output · retry inside the transaction (A/doomed.out)runs offline
   load(biryani) attempt 1
   caught "db timeout"; outer transaction rollback-only = true
   load(biryani) attempt 2
   caught "db timeout"; outer transaction rollback-only = true
   load(biryani) attempt 3
caller got UnexpectedRollbackException:
   Transaction silently rolled back because it has been marked as rollback-only
output · Framework 7 @Retryable (A/stacked.out)runs offline
== (a) first call: cache miss, fails twice, third attempt works
      [aspect] enter price
      price() attempt 1, transaction active = true
      [aspect] exit  price after 5 ms
      attempt 1 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 2, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 2 transaction ROLLED BACK
      [aspect] enter price
      price() attempt 3, transaction active = true
      [aspect] exit  price after 0 ms
      attempt 3 transaction COMMITTED
   result 24900 after 305 ms

What you see: In the first run every attempt printed "outer transaction rollback-only = true", and the final result was UnexpectedRollbackException even though attempt 3 itself would have returned a value. In the second run each attempt printed its own line "transaction active = true", then ROLLED BACK, ROLLED BACK, COMMITTED, and the caller got 24900.

Why: A transaction is a single all-or-nothing unit that cannot be partly retried. A retry needs to be outside it, so it can throw the old one away and start a new one. The retry-outside-transaction idiom and Fig. 22.4 show the same rule.

Land it I put retry outside the transaction so every attempt gets a fresh one, and Framework 7 enforces that order for me.

Likely follow-ups
"Why can't I just catch the exception and continue in the same transaction?"

Because the transaction state is not in your hands once an inner @Transactional method has thrown. With the default propagation REQUIRED, the inner method's proxy sees the exception and calls setRollbackOnly() on the shared transaction. Catching the exception in the caller does not undo that.

The demo shows it in the first output: after each failure the caller caught the exception and printed rollback-only = true. The transaction was already condemned. The third attempt returned normally, but the commit at the end found the flag and threw UnexpectedRollbackException.

A way out is Propagation.REQUIRES_NEW on the inner method, which runs it in a separate transaction so its rollback does not touch the outer one. That works, but it uses a second database connection at the same time, and with a small connection pool you can deadlock yourself.

Retrying outside the transaction is simpler and cheaper: nothing is shared, nothing is doomed.

"How would the same bug look with the old Spring Retry library?"

It depended on configuration. Spring Retry's @Retryable was an ordinary advisor with its own order. With @EnableRetry at the default order and @EnableTransactionManagement also at the default order, the two tied and the result followed registration order. In some setups the retry advice ended up inside the transaction advice, giving exactly this failure. People fixed it by setting the orders by hand, for example @EnableRetry(order = ...) lower than the transaction order.

I ran a plain Spring Retry @Retryable(maxAttempts = 3) on Boot 4.2 and it worked in a simple case (three calls, then the exception), but I did not run the transaction combination with it, so I cannot say what order it gives in your setup. Print the chain (question 17) if you still use it.

The reason Framework 7's version is attractive is that the question disappears. The documented rule is that retry advice always runs outside @Transactional and @Cacheable, with no ordering to configure and no way to get it wrong.

If you stay on Spring Retry, write the order down in the configuration and add a test that proves each attempt has a fresh transaction.

"What if the whole retried method must be atomic with other work I do before it?"

Then the retry boundary is in the wrong place. If a method does step A, then step B inside one transaction, and step B is flaky, retrying the whole method repeats A as well. If A has already committed an effect elsewhere (an email, a call to another service), the retry repeats it.

The fix is to make the retry as small as the flaky step. Move B into its own bean method, annotate that with @Retryable, and let the outer method call it. Now only B repeats, and its own transaction (if it has one) is fresh each time.

If A and B must be atomic, retry the entire unit but make A safe to repeat: use an idempotency key, or write A so that doing it twice gives the same result. Question 48 shows the key.

Do not use REQUIRES_NEW as a patch for a wrongly placed retry. It makes the failure harder to see, and it can leave A committed while B never happens.

"How can I verify in a test that each attempt really gets its own transaction?"

I count them. In the method I read isActualTransactionActive() from TransactionSynchronizationManager and register an afterCompletion callback that records COMMITTED or ROLLED BACK. That is exactly what the stacked demo does, and its output is printed above.

A test then asserts the sequence [ROLLED_BACK, ROLLED_BACK, COMMITTED] after a method that fails twice. If someone later changes the order so attempts share a transaction, the sequence changes and the test fails.

RetryTxTest.java (idea) · Boot 4.2runs offline
@Test void everyAttemptHasItsOwnTransaction() {
    service.price("biryani");          // fails twice
    assertThat(service.completions())
        .containsExactly("ROLLED_BACK",
                         "ROLLED_BACK",
                         "COMMITTED");
}

I did not run this exact test class, but the same recording was done in the demo above. Run it against a real transaction manager and a real database such as H2, since a mocked transaction manager proves nothing here.

Q15. "How do you set the order of your own aspect relative to @Transactional?"

Reveal answer

Strong answer Give the aspect an @Order, and remember one rule: a lower number runs outer (closer to the caller). @Order(1) wraps @Order(2).

The transaction advisor's own order is set where you enable transactions: @EnableTransactionManagement(order = ...), and it defaults to Integer.MAX_VALUE, the lowest priority. So:

  • @Order(Ordered.HIGHEST_PRECEDENCE) on your aspect puts it outside the transaction. It sees the call before a transaction opens and after it commits or rolls back, so its timing includes the commit.
  • A larger number than the transaction's order puts it inside. It runs in the open transaction and can write rows in the same unit of work.
  • No @Order at all: your aspect ties with the transaction, and the position comes from registration order. I measured it inside on Boot 4.2, but it is not a contract.

The same attribute exists on @EnableCaching(order = ...) and @EnableAsync(order = ...). The retry advisor is the exception: Framework 7 keeps it outermost regardless.

Which side do you want? Put the aspect outside the transaction for timing, audit of attempts, and anything that must run even if the commit fails. Put it inside for work that must be part of the same transaction, such as an audit row or an outbox record.

If your design needs a specific side, write explicit numbers on both ends (for example transaction order = 100, aspect @Order(200)) so the next reader does not depend on a tie.

Picture it The stacked demo ran the same timing aspect in three positions: unordered, HIGHEST_PRECEDENCE (outside everything but retry), and ordered after the cache. Below are the chains, outermost first, and what a cache hit looked like each time.

Default

No @Order. The aspect ties with the others and sits last.

Aspects.java · Boot 4.2runs offline
@Aspect @Component
public static class Plain {
  @Around("execution(* ...MenuService.price(..))")
  Object around(ProceedingJoinPoint pjp)
      throws Throwable { return time(pjp); }
}

Highest precedence

@Order lowest number: outside cache and transaction.

Aspects.java · Boot 4.2runs offline
@Aspect @Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public static class First {
  @Around("execution(* ...MenuService.price(..))")
  Object around(ProceedingJoinPoint pjp)
      throws Throwable { return time(pjp); }
}

The shift: One annotation moves the aspect from the inside of the chain to the outside.

Make the invisible visible: The chains for both runs, and the second (cache hit) call of each.

output · default (A/stacked.out)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  4. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$Plain.around
output · highest precedence (A/stacked-aspectFirst.out)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483648 com.quickbite.aop.stacked.Aspects$First.around
  3. order=-2147483647  / ExposeInvocationInterceptor
  4. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  5. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
output · cache hit, default (A/stacked.out)runs offline
== (b) second call: cache hit
   result 24900 after 2 ms
output · cache hit, highest precedence (A/stacked-aspectFirst.out)runs offline
== (b) second call: cache hit
      [aspect] enter price
      [aspect] exit  price after 0 ms
   result 24900 after 1 ms

What you see: With @Order(HIGHEST_PRECEDENCE) the aspect moved from last place to second place, right behind retry and in front of cache and transaction. On the cache hit, the default aspect printed nothing, but the outer aspect printed "enter" and "exit after 0 ms".

Why: The aspect now wraps the cache, so it sees every call, including hits. It is still inside retry, so it ran once per attempt (three times in call (a)). To time a whole retried call, time it one level up. The primer's ordering section has the table of knobs.

Land it I give the aspect an explicit @Order where I need a side, lower means outer, and I add explicit orders on both the aspect and the transaction when the position matters.

Likely follow-ups
"What does a lower number really mean? I keep mixing it up."

Lower number means higher priority, which means outer, which means it runs first on the way in and last on the way out. Ordered.HIGHEST_PRECEDENCE is Integer.MIN_VALUE, the lowest number, so it is the outermost possible. Ordered.LOWEST_PRECEDENCE is Integer.MAX_VALUE, the innermost.

The names are confusing because "highest precedence" sounds like a big number. A way to remember: the numbers are positions in a queue. Position 1 enters first.

The demo shows it with real orders. A/order.out listed Outer with @Order(1) and Inner with @Order(2), and printed "enter Outer, enter Inner, method, exit Inner, exit Outer".

In code review I ask people to write a one-line comment next to any @Order that says "outside the transaction" or "inside the transaction". The number alone does not tell the reader the intent.

"Where does my aspect sit if I put it inside the transaction, and why would I want that?"

Inside means the transaction is already open when your advice runs, and it closes after your advice returns. Anything your advice writes to the same database through the same transaction manager is part of the same unit of work.

The best reason is an audit row or outbox record that must exist if and only if the business change committed. Question 11 designed that.

A second reason is to read the transaction state: isActualTransactionActive() on TransactionSynchronizationManager is only true inside.

The cost is that your advice cannot see the commit. If the commit fails (a constraint violation at commit time, a connection error), your advice already returned normally. For timing that includes the commit, or for anything that must report commit failures, go outside.

"How do I make sure my aspect sees the call even when the cache answers?"

Put it outside the cache. With the aspect at HIGHEST_PRECEDENCE, the demo printed "enter price" and "exit price after 0 ms" on the cache hit, which the default position never showed.

That is what you want for timing and for counting requests, because a cache hit is a request too. A dashboard built on an inside aspect would show only cache misses, and your real request rate would look far lower than it is. That was the incident behind the next question.

An alternative is to use the cache's own metrics (cache.gets with hit and miss tags, question 32), which count hits separately from the method timing.

If you need both, time the outside and let the cache metrics tell you the hit ratio.

"Does @Order work on an aspect that is declared with a @Bean method?"

Yes. Spring reads the order of an aspect bean from either the @Order annotation on its class or the Ordered interface if the class implements it. For a bean registered by a @Bean method, the reliable place is the annotation on the class of the returned object. I did not test an @Order placed on the @Bean method itself, so I do not rely on it.

When you cannot touch the aspect class (a library aspect), wrap it: declare a subclass or implement Ordered through a small adapter bean, or use the library's own configuration property for ordering if it has one.

Test it the same way as everything else in this chapter: print the advisor chain and see where the aspect landed. I treat any ordering claim that I have not printed as a guess.

Q16 · Scenario. "After you added caching, a timing aspect stopped logging most calls. Why?"

Reveal answer

Strong answer Because the cache interceptor sits outside the timing aspect, and a cache hit returns before the call goes any deeper. The aspect only runs on a miss, the one time the real method is called. After a warm-up, 99 of 100 requests are hits, so 99 of 100 never reach the aspect, and its log looks nearly empty.

It is not a bug in the cache or in the aspect. It is the order of the chain, measured on Spring Boot 4.2: retry, cache, transaction, then an unordered custom aspect. Anything below the cache is skipped on a hit.

There are two consequences, and the second is the dangerous one:

  • Your logs and counters show about 1% of the real traffic.
  • Your average time looks terrible. The aspect sees only the slow misses, so a dashboard says "price() takes 224 ms" while users mostly get 2 ms answers.

Hand-worked example from the demo's numbers: one miss of 224 ms and 99 hits of about 2 ms. The real average is (224 + 99 x 2) / 100, which is about 4.2 ms. The inside aspect reports one call at 224 ms.

There are three fixes, and the right one depends on what you want to measure:

  1. Move the aspect outside the cache: @Order(Ordered.HIGHEST_PRECEDENCE). It then sees hits and misses and times what the caller really experienced.
  2. Keep the aspect inside, and use it deliberately as "time spent in real work", named MissTimingAspect so nobody misreads it.:
  3. Use the cache's own hit and miss counters (cache.gets, question 32) for the ratio, and the outside aspect for latency.:

Whichever you pick, write the intent down. A timer that sits inside the cache measures the database, and a timer outside measures the user.

Picture it The same method with the same aspect, once at the default position and once with @Order(HIGHEST_PRECEDENCE). Only the second call of each run (a cache hit) is shown.

The setup: MenuService.price() has @Cacheable. The first call misses and runs the real method. The second call hits.

Make the invisible visible: Look at the second call in each run.

output · aspect inside the cache, the default (A/stacked.out)runs offline
== (b) second call: cache hit
   result 24900 after 2 ms
output · aspect outside the cache, HIGHEST_PRECEDENCE (A/stacked-aspectFirst.out)runs offline
== (b) second call: cache hit
      [aspect] enter price
      [aspect] exit  price after 0 ms
   result 24900 after 1 ms

What you see: In the default run the cache hit printed only the result line (2 ms): the aspect did not run at all. With the outer aspect the same hit printed [aspect] enter price and exit price after 0 ms.

Why: The cache interceptor returns the stored value without calling proceed(), so everything that sits below it in the chain is skipped on a hit. Moving the aspect above the cache makes it part of every call. See section 03 and Fig. 22.4.

Land it When a timing aspect goes quiet after caching, I check whether it sits inside the cache, and I move it outside if I want to measure what the caller experiences.

Likely follow-ups
"How do I time the cache hit rate itself?"

I do not use an aspect for that. The cache abstraction publishes metrics. With Actuator and Micrometer you get cache.gets with a result tag of hit or miss, plus cache.puts, cache.evictions and cache.size. The ratio is hits divided by all gets.

The measured caveat from the caching section: the metrics for a Caffeine cache appeared only after I set spring.cache.cache-names and turned on recordStats. A cache that Spring creates lazily on first use was not bound to the metrics registry. Without that setting the metric endpoint showed nothing, which looks like "no caching" when it is really "no metrics".

For a dashboard I plot the hit ratio next to the outside timing aspect. A falling hit ratio with a rising latency tells you the cache stopped helping, for example after a deploy cleared it or a key change broke it.

Question 32 shows the curl output.

"Should the timing aspect be outside retry as well?"

For "how long did the caller wait", yes, but the aspect cannot be outside retry. Measured order: the retry advisor is always the outermost advisor on the bean, even with HIGHEST_PRECEDENCE on the aspect. The demo showed the outer aspect running three times for a call that retried twice.

So an aspect on the same bean times each attempt, not the whole retried call. To time the whole call, measure one level up: in the caller, or on a thin facade bean that calls the retried method. A @Timed on the facade or a timer in the web layer works.

Both numbers are useful. Per-attempt time tells you how slow the dependency is. Whole-call time tells you what the user waited, including the delays between retries.

Name them differently (price.attempt and price.call) so a graph cannot mix them up.

"A teammate says "just add logging inside the method". Why is that worse?"

Because it measures even less. A log line inside the method runs only when the method body runs, so it is skipped on a hit in the same way, and it is also below the transaction, so it ignores the time to open and commit the transaction.

It also puts the same timing code in every method again, which is the copy-and-paste problem that AOP solves (question 1).

More important, it hides the real mechanism. When a developer sees "price() took 224 ms" in the logs and nothing from the cache, the fix is not a new log line. The fix is to know the order of the chain and decide which position you want to measure.

My advice to the team is to keep the aspect, set its order on purpose, and write one sentence in its Javadoc about what it measures.

"Will @Cacheable hit data before security or validation runs?"

It depends on where those advisors sit. Method security (@PreAuthorize) is also an advisor on the same proxy, and its order relative to the cache decides whether a cache hit skips the permission check. If the cache is outside the security advisor, a cached value is returned to a caller who has not been checked.

That is a real data leak: user A loads a protected value, it is cached under a key that does not include the user, and user B gets it from the cache without passing the check. The cache key must therefore include everything the security decision depends on, or the security check must sit outside the cache.

I did not run this combination for the course, so I treat it as a design warning and not a measured result. In a review I look for @Cacheable and @PreAuthorize on the same method and ask for a test: call as an allowed user, then as a forbidden user, and assert that the second call is denied.

Where in doubt, cache below the security boundary: cache a service method that has no per-user data, and put the permission check on a method above it.

Q17. "How do you see the actual advisor chain on a bean at runtime?"

Reveal answer

Strong answer Cast the proxy to Advised and print getAdvisors(). The list is the chain, outermost first. It is five lines of code, and I use it any time I am unsure about order.

Chain.java · Boot 4.2runs offline
static void print(Object bean) {
    int i = 1;
    for (Advisor a : ((Advised) bean).getAdvisors()) {
        String order = a instanceof Ordered o
                ? String.valueOf(o.getOrder()) : "-";
        System.out.printf("  %d. order=%-11s %s%n",
                i++, order, a.getAdvice().getClass().getSimpleName());
    }
}

Every @Transactional, @Cacheable, @Retryable, @Async and @Aspect method that applies to the bean shows up as an advisor. The order value is what Spring sorts by, and two equal values mean "tied", so position comes from registration. Advisors that do not implement Ordered print a dash.

Three more checks round it out. AopUtils.isAopProxy(bean) tells you whether the bean is a proxy at all. AopUtils.getTargetClass(bean) tells you the real class. And getClass() shows $$SpringCGLIB$$ for a CGLIB proxy.

Use it in a startup runner while you investigate, or in a test that pins the order you depend on. I do not leave it in production code. If the chain is wrong, you want a failing test, not a log line nobody reads.

Picture it One bean with the stacked annotations printed by the five-line method. The second chain is a bean with @Async @Transactional.

Make the invisible visible: Print both chains.

output · Boot 4.2 (A/stacked.out)runs offline
advisor chain, outermost first:
  1. order=2147483647  DefaultPointcutAdvisor / RetryAnnotationInterceptor
  2. order=-2147483647  / ExposeInvocationInterceptor
  3. order=2147483647  BeanFactoryCacheOperationSourceAdvisor / CacheInterceptor
  4. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor
  5. order=2147483647  com.quickbite.aop.stacked.Aspects$Plain.around
advisor chain of NotificationService (@Async @Transactional):
  1. order=-2147483648 AsyncAnnotationAdvisor / AnnotationAsyncExecutionInterceptor
  2. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor

What you see: For MenuService the chain is retry, then the exposure interceptor, then cache, transaction and the custom aspect. For NotificationService the first advisor is AnnotationAsyncExecutionInterceptor with the order -2147483648. The retry line reports 2147483647 and is still first, because Framework 7 adds it at the front on purpose.

Why: The printed order values are not the full story. The retry advisor reports the same value as the cache and transaction advisors, and its position comes from where its post-processor puts it. That is why I trust the printed position and not the printed number. See the advisor-chain idiom and section 03.

Land it I cast the proxy to Advised and print its advisors in order, then I trust the position in the list and not just the number.

Likely follow-ups
"What is ExposeInvocationInterceptor and why is it in the chain?"

It is an internal Spring interceptor that stores the current MethodInvocation in a ThreadLocal, so that later interceptors and pointcut matching can read it. AspectJ-style advice needs this to bind parameters such as JoinPoint.

Spring adds it automatically when any AspectJ advice is present. You do not configure it and you cannot remove it. It prints with an order of Integer.MIN_VALUE + 1 (-2147483647), which is why in the demo it comes right after retry and before cache and transaction, but behind an aspect with HIGHEST_PRECEDENCE.

The detail that surprised me: the HIGHEST_PRECEDENCE aspect sits in front of the exposure interceptor. In the aspectFirst run, the chain printed retry, the aspect, the exposure interceptor, then cache and transaction.

You can ignore it when reading the chain. It does not change behaviour, it only supplies the call context.

"Can I see the chain without writing code, for example in a debugger or the logs?"

Yes, with a debugger. Put a breakpoint after the context starts, evaluate the bean, and expand the CGLIB proxy object. It has a field CGLIB$CALLBACK_0 that holds a DynamicAdvisedInterceptor with an advised field, and that has the list of advisors. The same list as the five-line method, just slower to reach.

For logs, set the logging level for org.springframework.aop and org.springframework.cache to debug or trace. Spring then logs the proxies it creates and what each interceptor does, for example the computed cache key. I did not capture that output here, so check the output on your own version.

There is also Actuator. /actuator/beans lists beans and their types, which shows $$SpringCGLIB$$ class names, but it does not list the advisors.

I prefer the code route in a test. A test that prints or asserts the chain documents the order, and it keeps documenting it after I leave the team.

"How do I get the real object behind the proxy, for example in a test?"

((Advised) proxy).getTargetSource().getTarget() returns the real bean. Spring Test also has AopTestUtils.getTargetObject(proxy), which unwraps nested proxies and is safer in tests.

A common use: verify a field or call a method directly, bypassing the advisors. A test might call AopTestUtils.getTargetObject(service).price("biryani") to prove the raw method does not cache.

Be careful in production code. Calling the target directly skips every advisor on purpose, including security and transactions. That is rarely what you want, and it is a clear sign of a design that fights the framework.

Avoid @InjectMocks or reflection on a proxy. The proxy has none of your fields, and the result looks confusing: values are null because you are looking at the wrapper, not the bean.

"What does it mean when the chain for my bean is empty or the bean is not a proxy?"

It means no advisor matched any method of the class, so Spring did not create a proxy and handed out the plain object. AopUtils.isAopProxy(bean) returns false, and getClass() shows your own class name without $$SpringCGLIB$$.

The usual causes are a pointcut that does not match (a typo in the package), an aspect class that is not a bean (no @Component), a missing spring-boot-starter-aspectj dependency, @EnableCaching or @EnableAsync missing, or an annotation placed on a private method or on an interface that the lookup does not read.

In the demo, the @Cacheable bean printed the CacheInterceptor line only after @EnableCaching was present. Without that annotation the same class had no cache advisor at all.

My debugging order: is the bean a proxy, what is in the chain, does the pointcut match the method, and is the call coming through the proxy. Four checks, in that order, find most problems.

Q18 · Design. "You need retries on transient database errors, a transaction per attempt, a cache in front and timing metrics. Order them and justify it."

Reveal answer

Strong answer I decide the order from what each concern needs to see. The target I aim for, outermost first:

  1. Whole-call timing (on a thin caller or facade bean): measures what the user waited, including the pauses between retries.
  2. Retry: it must be outside the transaction so each attempt gets a fresh one. Framework 7 forces this.
  3. Cache: outside the transaction, so a hit opens no transaction and costs no connection. A cache outside retry is also valid. A miss that fails is never cached, because an exception stores nothing.
  4. Transaction: one per attempt.
  5. Per-attempt timing aspect: inside the retry, so it records the latency of the database call alone.
  6. Method: the repository call.

Why this order:

  • Retry outside the transaction. A failed attempt marks its transaction rollback-only. Only a new transaction can succeed (question 14).
  • Cache outside the transaction. On a hit, nothing below runs. In the measured chain a hit took 2 ms and printed no transaction line.
  • Timing in two places. An aspect on the same bean can only sit inside retry, so it measures attempts. The whole call is measured one level up.

The retry rule needs care. Retry only transient errors, for example TransientDataAccessException and its subclasses such as CannotAcquireLockException, never DataIntegrityViolationException, which a retry cannot fix. Give it a small maxRetries (a few), a delay that grows, and jitter (question 49). Only retry an operation that is idempotent, or protect it with a key (question 48). A read such as price() is safe to repeat.

Last, test the order. Print the chain once and keep a test that counts transactions per attempt.

Picture it The stacked demo already has retry, transaction, cache and an aspect. The sketch below adds the exception filter and the facade. Then the real run shows retry attempts, each with its own transaction and its own timing line.

MenuService.java (design) · Boot 4.2runs offline
@Retryable(maxRetries = 3, delay = 50, multiplier = 2,
           includes = TransientDataAccessException.class)
@Cacheable("prices")
@Transactional(readOnly = true)
public int price(String item) {
    return repo.find(item);          // the flaky database call
}

@Timed("price.call")                 // outside retry: whole call
public int priceTimed(String item) { return menu.price(item); }

The demo method has the same three annotations. It fails twice with a stand-in error.

Make the invisible visible: Run it, with the aspect at the outer position, so each attempt is timed.

output · Boot 4.2 (A/stacked-aspectFirst.out)runs offline
== (a) first call: cache miss, fails twice, third attempt works
      [aspect] enter price
      price() attempt 1, transaction active = true
      attempt 1 transaction ROLLED BACK
      [aspect] exit  price after 91 ms
      [aspect] enter price
      price() attempt 2, transaction active = true
      attempt 2 transaction ROLLED BACK
      [aspect] exit  price after 2 ms
      [aspect] enter price
      price() attempt 3, transaction active = true
      attempt 3 transaction COMMITTED
      [aspect] exit  price after 6 ms
   result 24900 after 224 ms

What you see: Three attempts. Each printed its own transaction active = true, and each ended with ROLLED BACK, ROLLED BACK, COMMITTED. The aspect printed enter and exit for every attempt: 91 ms for the first (it includes first-call warm-up), then 2 ms and 6 ms. The second call, a hit, ran none of the method.

Why: The aspect is inside retry, so it measures each attempt and not the call. The whole call took 224 ms, which only the facade or the caller can see. That is why I time in two places.

ConcernPositionReason
Whole-call timingFacade, outside everythingIncludes retry pauses
RetryOutermost advisorFresh transaction per attempt
CacheOutside transactionA hit costs no connection
TransactionInside cacheOne unit per attempt
Attempt timingInside retryLatency of one database call

Land it I put retry outermost, then cache, then transaction, time attempts with an aspect inside retry, time the whole call on a facade, and only retry transient, repeatable errors.

Likely follow-ups
"Why not put the cache outside retry and also outside everything else?"

It already is. In the measured chain the cache sits right behind retry, outside the transaction. The only thing in front of it is the retry advisor, and Framework 7 puts that first for a reason.

Retry outside the cache is the right way round: a retry after a failed miss performs a new cache lookup, and if another thread filled the cache in the meantime, the retry returns that value without touching the database again. A failed call stores nothing, so there is no risk of caching an error.

The reverse (cache outside retry) is not available with @Retryable, because retry is always outermost. You would only get it with a hand-built chain, and I see no benefit.

What I do check is the cache key and the null handling (questions 21 and 23), because those, and not the order, are the usual source of wrong cached values.

"Which database errors are really transient and safe to retry?"

Errors caused by timing, not by your data: a deadlock victim (CannotAcquireLockException), a lost connection, a failover in progress, a short lock timeout. Spring translates many of these into subclasses of TransientDataAccessException, and that is the type I list in includes.

Errors caused by the data or the code are not transient: a unique-key violation, a not-null violation, a bad SQL grammar error, a type mismatch. Retrying them gives the same failure three times and delays the real error by the total backoff.

Know your driver. Some failures surface as a generic exception wrapping the cause, so the filter may need to accept a wider type or inspect the cause. I test the filter by throwing the exceptions I expect and counting the calls.

Pair the list with a timeout on the query and the pool, since a retry that waits 30 seconds per attempt is worse than a quick failure.

"Where does the per-attempt timing end up in the metrics?"

In whatever meter the aspect records to. I would use a Micrometer Timer named for the attempt, tagged with the method and the outcome, so the graphs separate successes from failures.

AttemptTimer.java (idea) · Boot 4.2runs offline
Timer.Sample sample = Timer.start(registry);
try {
    Object r = pjp.proceed();
    sample.stop(registry.timer("price.attempt", "outcome", "ok"));
    return r;
} catch (Throwable t) {
    sample.stop(registry.timer("price.attempt", "outcome", "error"));
    throw t;
}

This is a design sketch and I did not run it for this answer. The shape follows the timing aspect from question 1, with a rethrow as in question 7.

Beware of high-cardinality tags. Use the method name and a small set of outcomes, not an item id, or the metric store grows without limit. For the whole call, record a second timer, price.call, one level up.

"Would you change this design for a write method?"

Yes, in three ways. First, retry only if the write is idempotent or carries an idempotency key. A retry of an insert that actually committed before the connection dropped inserts a second row. Question 48 covers the payment version.

Second, the cache is not read by a write. Instead a @CacheEvict or @CachePut runs after the write, and I decide whether it should run only when the transaction commits (a transactional event or a cache that is transaction-aware) so it never evicts for a rolled-back change.

Third, I make the retry smaller or remove it. A write that failed with a deadlock is safe to retry, but only if the transaction is the only thing the method does. If the method also sends an email or publishes an event inside the retried scope, the retry repeats it.

The structure stays the same: retry outermost, transaction per attempt. What changes is the scope of what is repeated.

Drill · Caching with @Cacheable

These seventeen questions test whether you can cache without surprises: keys, nulls, expiry, stampedes, several instances, metrics and memory. The demos come from the caching section and use real timings and counters.

Q19. "How does Spring's cache abstraction work under @Cacheable?"

Reveal answer

Strong answer It is a proxy with a small set of cooperating parts. @EnableCaching registers an advisor, and that advisor wraps the CacheInterceptor. Behind it stand three more objects: the CacheManager (a registry of named caches), the Cache (one named store) and the KeyGenerator (turns the method arguments into a key).

The steps for one call are the classic cache-aside pattern:

  1. Find the operation: the interceptor reads @Cacheable("prices") from the method (the annotation is read once and remembered).
  2. Build the key: one argument is used as it is, several arguments are wrapped in a SimpleKey, none gives SimpleKey.EMPTY.
  3. Look up: cacheManager.getCache("prices").get(key).
  4. On a hit, return the stored value and do not call the method.:
  5. On a miss, call the method, store the result with put(key, value) and return it.:

Spring does not store anything itself. The real storage is a provider behind the Cache interface: Caffeine, Redis, a plain ConcurrentHashMap and others. That is why the abstraction has no time-to-live and no size limit (question 24). Those belong to the provider.

Spring Boot picks the CacheManager for you. With Caffeine on the classpath it creates a CaffeineCacheManager, with Redis configured a RedisCacheManager, and as a last resort a ConcurrentMapCacheManager. The spring.cache.type property forces a choice.

Because it is a proxy, all the usual rules apply: only calls from another bean are cached, and the cache sits at the position in the chain you saw in question 13, outside the transaction.

Picture it A hand-written cache-aside and the same method with @Cacheable, then the real objects the interceptor used in the demo.

By hand

Every method that needs a cache repeats the lookup.

MenuService.java · Boot 4.2runs offline
Integer price(String item) {
  Integer v = cache.get(item);
  if (v == null) {
    v = repo.find(item);
    cache.put(item, v);
  }
  return v;
}

With the annotation

The proxy does the lookup and the store.

MenuService.java · Boot 4.2runs offline
@Cacheable("prices")
public Integer price(String item) {
  return repo.find(item);
}

The shift: The method now contains only the real work, and the proxy owns the get and the put.

Make the invisible visible: Four cached methods with different parameters, then a print of the manager, each cache and its keys.

output · Boot 4.2 (F/keys.out)runs offline
cache manager class : CaffeineCacheManager
cache 'one' (CaffeineCache) keys: [String[biryani]]
cache 'two' (CaffeineCache) keys: [SimpleKey[SimpleKey [biryani, Mysuru]]]
cache 'none' (CaffeineCache) keys: [SimpleKey[SimpleKey []]]
cache 'named' (CaffeineCache) keys: [String[biryani:Mysuru]]
advisor: CacheInterceptor

What you see: The manager is a CaffeineCacheManager, each named cache is a CaffeineCache, and the advisor chain contains one CacheInterceptor. The keys show the key rule: one argument is the key itself (biryani), two arguments become a SimpleKey, and no arguments give an empty SimpleKey.

Why: The abstraction is three small interfaces over any store. See section 04 for the figure of the cache-aside steps and the explicit key idiom.

Land it I describe it as a proxy that does a cache-aside lookup through a CacheManager, with the real storage, TTL and size in the provider.

Likely follow-ups
"Who decides which CacheManager Spring Boot uses?"

Boot's cache auto-configuration. If you define your own CacheManager bean, Boot backs off and uses yours. If not, it goes through the supported providers in a fixed order and takes the first one it can configure, for example Redis when a Redis connection factory exists, Caffeine when Caffeine is on the classpath, and the simple ConcurrentMapCacheManager if nothing else fits.

The setting spring.cache.type overrides the guess, and the demo projects set it to caffeine. A line in the startup output or a call to cacheManager.getClass() tells you what you actually got, as the demo printed above.

This matters when a dependency changes. If somebody adds a Redis starter to a service that used Caffeine, the cache may silently move to Redis, and its serialization rules apply to your cached objects.

My habit is to set spring.cache.type explicitly in application.yml, so the choice is written down.

"What is the difference between CacheManager, Cache and CacheResolver?"

A Cache is one named store, such as prices, with get, put, evict and clear. A CacheManager is the registry of those caches, found by name. A CacheResolver is the strategy that answers "which cache or caches does this operation use?" for a given call.

The default resolver simply looks up the names in the annotation (@Cacheable("prices")) in the CacheManager. You write your own only for unusual needs, such as choosing a cache by tenant at run time.

In the demo, cacheManager.getCache("one") returned a CaffeineCache, and getNativeCache() gave the Caffeine object itself, which has its own asMap() and stats().

Most applications never touch the resolver. They configure the manager once and annotate methods.

"Where is the cached value actually stored, and is it a copy?"

It is stored in the provider's memory. For Caffeine and the simple manager that is a Java object in the heap of the same JVM, and the cache keeps the same reference you returned, not a copy. If you cache a mutable object and a caller changes it, the next hit returns the changed object.

That is a real source of bugs. Cache immutable values (records, strings, numbers) or return copies. With Redis the value is serialized, so each hit returns a new object, and changing it does no harm, but the serialization format becomes a compatibility issue across deployments.

The demo's blob test shows the other side: a Caffeine cache with 200,000 entries stayed near 34 MB because it was bounded, while an unbounded simple cache ran out of memory (question 33).

So the three facts to remember are: the value is a shared reference for in-process caches, a serialized copy for remote ones, and bounded only if you bound it.

"Does @Cacheable work on a private method or on a constructor?"

No. It is a proxy feature, so the same limits as every advice apply (question 9): the method must be public (or at least reachable through the proxy) and called from another bean. A constructor cannot be cached at all.

With the usual proxy mode, a self-call also bypasses the cache. The demo in question 8 shows three database calls for three same-class calls to a @Cacheable method.

If you need a cached helper inside a class, move it into its own small bean, as you would for @Transactional.

There is a second case that looks like a bug but is not. @Cacheable on a method of a class that is not a Spring bean, or one created with new, does nothing, because no proxy was ever built around it.

Q20. "@Cacheable versus @CachePut versus @CacheEvict versus @Caching."

Reveal answer

Strong answer They are four annotations over the same cache, and each answers a different question.

AnnotationWhat it doesRuns the method?Typical use
@CacheableReturn the cached value if present, otherwise call the method and store the resultOnly on a missReads
@CachePutAlways call the method and store its result in the cacheAlwaysWrites that return the new value
@CacheEvictRemove an entry (or all with allEntries = true)AlwaysWrites and deletes
@CachingGroup several of the above on one methodAs each saysAn update that evicts two caches
@CacheConfigClass-level defaults such as cacheNamesn/aAvoid repeating the name

The pair people confuse is @Cacheable and @CachePut. @Cacheable skips the method on a hit, so it is for reads. @CachePut never skips, so it is for writes that want to refresh the entry with the value just produced. Do not put both on one method. The two aims conflict.

@CacheEvict has two switches. allEntries = true clears the whole cache, which is simple but forces every key to reload. beforeInvocation = true evicts before the method runs. By default eviction happens after a successful return, so a method that throws leaves the old entry in place. That is what you want for a failed write (the data did not change) and not what you want when the method might fail halfway.

Timing: with the measured order, the cache interceptor is outside the transaction, so the eviction runs after the commit. A reader cannot reload the old value from the database while the transaction is still open. A short window remains between commit and evict, and a TTL covers it.

Picture it One cached read and the three write styles against it. The calls print the elapsed time and a database-call counter.

MenuService.java (excerpt) · Boot 4.2runs offline
@Cacheable("prices")
public Integer price(String item) { return repo.find(item); }

@CachePut(value = "prices", key = "#item")
public Integer setPrice(String item, int cents) {
    repo.update(item, cents); return cents; }

@CacheEvict(value = "prices", key = "#item")
public void changePrice(String item, int cents) {
    repo.update(item, cents); }

@CacheEvict(value = "prices", key = "#item", beforeInvocation = true)
public void changePriceFailsBeforeEvict(String item, int cents) {
    throw new IllegalStateException("db down"); }

Make the invisible visible: Read, evict, put, a failing evict, a failing evict with beforeInvocation, and allEntries.

output · Boot 4.2 (B/evict.out)runs offline
cache manager: CaffeineCacheManager
price(biryani)                     -> 24900     224 ms   db calls so far: 1 (MISS)
price(biryani)                     -> 24900       6 ms   db calls so far: 1 (hit)
-- changePrice(biryani, 26900) with @CacheEvict
price(biryani) after evict         -> 26900     200 ms   db calls so far: 2 (MISS)
-- setPrice(biryani, 27900) with @CachePut
price(biryani) after put           -> 27900       0 ms   db calls so far: 2 (hit)
-- changePriceThenFail: the method throws, so the evict is skipped
   threw commit failed
price(biryani) still cached        -> 27900       0 ms   db calls so far: 2 (hit)
-- changePriceFailsBeforeEvict: beforeInvocation=true evicts first
   threw db down
price(biryani) after early evict   -> 27900     201 ms   db calls so far: 3 (MISS)
-- clearPrices() with allEntries=true
price(biryani)                     -> 27900     202 ms   db calls so far: 5 (MISS)
price(dosa)                        -> 8900      202 ms   db calls so far: 6 (MISS)

What you see: After @CacheEvict the next read missed and reloaded 26900. After @CachePut the next read hit with 27900, with no database call. When the method threw "commit failed", the entry stayed (still cached). With beforeInvocation = true the entry was removed even though the method threw. allEntries = true emptied everything, so both items reloaded.

Why: @CacheEvict normally runs on success, which keeps the cache in step with a change that really happened. See the evict-on-write idiom for the full set.

Land it I use @Cacheable for reads, @CachePut when a write already knows the new value, @CacheEvict when it does not, and @Caching when one write touches several caches.

Likely follow-ups
"When is @CachePut better than @CacheEvict on a write?"

When the write method already returns the new value and the next read will almost certainly ask for it. A @CachePut refreshes the entry in the same step, so the next read is a hit. With @CacheEvict the next read is a miss and pays the full database cost.

The demo shows both: after setPrice (@CachePut) the next price() took 0 ms, and after changePrice (@CacheEvict) it took 200 ms.

Prefer @CacheEvict when the cached shape differs from what the write returns, or when many keys depend on the change. A price list cached by city and by item has many keys, and a put cannot refresh them all. Evicting is safer: a missing entry is only a slower read, while a wrong entry is a wrong answer.

My default is evict. I switch to put only for a hot key where the extra miss would be visible.

"What does @Caching look like, and when do I need it?"

It groups several cache annotations on one method. The attributes are cacheable, put and evict, each taking an array.

Caching.java (idea) · Boot 4.2runs offline
@Caching(evict = {
    @CacheEvict(value = "prices", key = "#item"),
    @CacheEvict(value = "menuList", allEntries = true)
})
public void changePrice(String item, int cents) { ... }

You need it because Java annotations of the same type cannot be repeated on one method here. A price change might evict the item's own entry and also the cached menu list that contains it.

I did not run this exact method for the course, but the single-annotation versions above were run. The mechanism is the same: the interceptor applies each operation in turn.

If @Caching gets long, I take it as a hint that the design caches too many views of the same data, and I reduce the number of caches.

"What happens to the cache if the write succeeds but the transaction rolls back later?"

With the measured order, the cache interceptor is outside the transaction interceptor. The @CacheEvict runs after the transaction interceptor has returned, which means after the commit or rollback. If the transaction rolls back, the exception propagates out of the method, and a normal @CacheEvict does not run, so the old entry stays. That is correct, because the data did not change.

A different problem is a write inside a larger transaction where the cache annotation is on an inner method. The inner method returns before the outer transaction commits, so the eviction happens early. A reader can reload the old value before the commit and put it back in the cache, which leaves a stale value until the TTL expires.

The remedies are to put the cache annotation on the outermost transactional method, or to evict from a @TransactionalEventListener(phase = AFTER_COMMIT), or to rely on a short TTL as the final safety.

I always set a TTL as the backstop. An eviction bug then costs minutes, not days.

"Can an eviction be missed, so that stale data stays in the cache?"

Yes, in several ways, and a TTL is the answer to all of them. Another service writes to the same table, a batch job updates rows directly, a different instance has its own local cache (question 27), or the eviction ran before the commit as described above.

The cache abstraction cannot see changes made outside the method that carries the annotation. It only knows what passes through its own proxy.

So I treat the cache as eventually consistent by design. The question to ask the business is "how stale may this value be?" For a menu price, a few minutes may be fine. For a stock count at checkout, it is not, and I would not cache that value at all (question 34).

Write the answer down next to the TTL setting, so the number has an owner.

Q21. "How are cache keys built by default, and when must you write your own?"

Reveal answer

Strong answer By default Spring uses SimpleKeyGenerator, and the rule has three cases:

ParametersKeyExample from the demo
NoneSimpleKey.EMPTYnone() stored under SimpleKey []
OneThe parameter itselfone("biryani") stored under biryani
SeveralA SimpleKey that wraps all of themtwo("biryani","Mysuru") stored under SimpleKey [biryani, Mysuru]

The key is compared with equals() and hashCode(), so two calls hit the same entry only if their parameters are equal in that sense. Strings and numbers are fine. Your own objects need those two methods, or the cache never hits (question 22).

Write your own key when:

  • A parameter is an object without a sensible equals, such as a request DTO or an entity: use a field, key = "#q.item + ':' + #q.city".
  • Some parameters do not change the result (a request id, a locale you ignore): leave them out of the key.
  • Some state must be part of the key but is not a parameter, such as the tenant or the user: add it with SpEL (#root.target, a bean reference) or a custom KeyGenerator.
  • You want readable keys in Redis, where a debugging engineer has to look at them.

Two more points. Cache names are separate namespaces, but all methods that use the same name share it. Two methods that both say @Cacheable("prices") with the same argument produce the same key and overwrite each other's values. Use one cache name per kind of value, or put the method into the key.

And key and keyGenerator are alternatives: Spring rejects an annotation that sets both.

Picture it Four methods with different shapes, and one with an explicit SpEL key. The runner printed the keys that ended up in each cache, with the class of each key.

KeysDemo.java (excerpt) · Boot 4.2runs offline
@Cacheable("one")   public String one(String item) ...
@Cacheable("two")   public String two(String item, String city) ...
@Cacheable("none")  public String none() ...
@Cacheable(cacheNames = "named",
           key = "#item + ':' + #city")
public String named(String item, String city) ...

Make the invisible visible: Read the keys back from the native Caffeine maps.

output · Boot 4.2 (F/keys.out)runs offline
cache manager class : CaffeineCacheManager
cache 'one' (CaffeineCache) keys: [String[biryani]]
cache 'two' (CaffeineCache) keys: [SimpleKey[SimpleKey [biryani, Mysuru]]]
cache 'none' (CaffeineCache) keys: [SimpleKey[SimpleKey []]]
cache 'named' (CaffeineCache) keys: [String[biryani:Mysuru]]

What you see: The single argument is its own key (String[biryani]). Two arguments became SimpleKey[biryani, Mysuru]. With no arguments the key is an empty SimpleKey. The SpEL version produced the readable string biryani:Mysuru.

Why: The default key is correct for simple parameters and wrong for objects without equals. The readable key is the one you can search for in Redis. See the explicit key idiom.

Land it By default the key is the single parameter or a SimpleKey of all of them, and I write my own whenever a parameter is an object without equals, or the key must be readable.

Likely follow-ups
"What is a custom KeyGenerator and when is it better than SpEL?"

It is a bean with one method, generate(target, method, params), that returns the key. You select it with keyGenerator = "myGenerator" on the annotation, or set it once for the whole application by implementing CachingConfigurer.

It is better than SpEL when the same rule applies to many methods. A rule such as "tenant id plus method name plus all arguments" would be repeated in every annotation as a SpEL string. In a generator it is written once, tested once, and read by every method.

It is also easier to unit-test, since it is plain Java, and SpEL strings are only checked when the method is first called. A typo in #iem shows up at run time.

SpEL is better for a one-off key where the rule is a single short expression. In a code review I accept SpEL for one method and ask for a generator at the third repetition.

"Two different methods share a cache name and return different data. What goes wrong?"

They share the key space, so with equal arguments one overwrites the other. Take price(String item) and calories(String item), both marked @Cacheable("menu"). The call price("biryani") stores the key biryani. Then calories("biryani") finds an entry under the same key and returns the price to a caller who asked for calories, probably as a ClassCastException.

I did not run this combination for the course. It follows from the key rule shown above: the key does not contain the method name.

The fixes are easy. Use one cache name per kind of value (prices, calories), or add the method to the key (key = "'price:' + #item").

In the review checklist I scan for duplicate cache names with different return types. It is a bug you do not see until two code paths meet in production.

"Is it a problem to use a whole entity or DTO as the key?"

Yes, unless it has equals and hashCode based on immutable fields. Without them, each call creates a new object that is not equal to the earlier one, so the cache grows and never hits. Question 22 shows it with real numbers.

Even with equals, an entity key is a bad habit. It holds references to other data (lazy collections, parent objects), makes the key large, and ties the cache to the object's class, which matters with Redis serialization.

Use the identifier instead: key = "#order.id". For a query object, use a record, since a record gives you equals and hashCode over its fields for free, or build a string from the fields that matter.

The key should be small, stable and readable. An id or a short string meets all three.

"How does the key behave for null arguments?"

A single null argument as the key makes Spring raise an IllegalArgumentException, because a cache key cannot be null: "Null key returned for cache operation". With several arguments, a null inside a SimpleKey is accepted, and the key is built with the null in it.

The rule I follow is to avoid null parameters on cached methods. If a parameter is optional, use an overload or a default value, or handle the null case before the cached method, so the cached method always receives real values.

If you cannot avoid it, give the key an explicit SpEL expression that substitutes a marker, for example key = "#city ?: 'ALL'".

I have not run the null-key case in these demos, so check the message on your Spring version. The principle holds either way: a cache key should never depend on a value that can be missing.

Q22 · Scenario. "A cache keyed on an entity object never hits. Why?"

Reveal answer

Strong answer Because the key is compared with equals(), and the entity does not define it, so Java falls back to object identity. Each call builds a new object, and a new object is never "equal" to an earlier one even if every field matches. The cache looks for the new key, finds nothing, calls the method, stores one more entry, and the same thing happens on the next call.

Two bad things follow at once. The hit rate is 0%, so the cache only adds work. And the cache grows by one entry per call, so it also leaks memory until the provider's bound or the heap stops it (question 33).

The cause is easy to miss because the keys print identically. PriceQuery[biryani,Mysuru] appears three times in the cache's key set, and a person reading the log believes they are the same.

Fixes, in the order I would choose:

  1. Use an explicit key from the fields that matter: key = "#q.item + ':' + #q.city". Short, readable, no class changes.
  2. Make the type a record (or give it equals and hashCode over immutable fields), so the default key works.:
  3. Pass the identifying values as plain parameters (String item, String city) instead of an object.:

Never base equals and hashCode on a mutable field that changes after the key is stored. The entry then sits in the wrong bucket and cannot be found.

Picture it The demo calls a method with a PriceQuery object three times, using a class with no equals or hashCode, then calls a second method that uses an explicit key.

Broken

A plain class. Equal-looking objects are different keys.

PriceQuery.java · Boot 4.2runs offline
public class PriceQuery {
  private String item, city;
  // no equals(), no hashCode()
}
@Cacheable("byQuery")
Integer priceBy(PriceQuery q)

Fixed

An explicit key from the fields that matter.

MenuService.java · Boot 4.2runs offline
@Cacheable(value = "byQueryFixed",
    key = "#q.item + ':' + #q.city")
Integer priceByFixed(PriceQuery q)

The shift: The key is now a short string built from the two fields, and the object's identity no longer matters.

Make the invisible visible: Call each method three times with an equal-looking query.

output · Boot 4.2 (B/keys.out)runs offline
== entity as key, no equals/hashCode: three equal-looking queries
priceBy(new PriceQuery(biryani,Mysuru)) -> 24900     203 ms   db calls so far: 3 (MISS)
priceBy(new PriceQuery(biryani,Mysuru)) -> 24900     201 ms   db calls so far: 4 (MISS)
priceBy(new PriceQuery(biryani,Mysuru)) -> 24900     202 ms   db calls so far: 5 (MISS)
   cache 'byQuery' holds 3 entries: [PriceQuery[biryani,Mysuru], PriceQuery[biryani,Mysuru], PriceQuery[biryan
== same queries, explicit key = #q.item + ':' + #q.city
priceByFixed(new PriceQuery(...))  -> 24900     217 ms   db calls so far: 6 (MISS)
priceByFixed(new PriceQuery(...))  -> 24900       0 ms   db calls so far: 6 (hit)
priceByFixed(new PriceQuery(...))  -> 24900       0 ms   db calls so far: 6 (hit)
   cache 'byQueryFixed' holds 1 entries: [biryani:Mysuru]

What you see: The broken method missed every time (203, 201, 202 ms), and the cache ended up with three entries that all print the same. The fixed method missed once (217 ms) and then hit twice at 0 ms, and its cache holds one entry, biryani:Mysuru.

Why: The default key for a single object parameter is the object itself, and an object without equals is only equal to itself. The explicit key idiom avoids the problem and gives you readable keys.

Land it When a cache never hits, I look at its keys: if equal-looking keys appear many times, the key class has no equals, and I switch to an explicit key.

Likely follow-ups
"How can I spot this problem in production before it causes an outage?"

Two signals. The hit ratio from the cache metrics (cache.gets with result=hit and miss, question 32) sits near zero for a method that should be hot. And cache.size keeps rising without a plateau.

A third check is cheap in a test: call the method twice with equal arguments and assert that the repository was called once (question 31). That test fails immediately for this bug.

In a debugger or an admin endpoint you can print cache.getNativeCache().asMap().keySet() and read the keys. Repeats of the same text are the clue, as in the output above.

I also put a size bound on every cache (question 33). Then a key mistake costs a poor hit rate, not an out-of-memory crash.

"Is a record a good cache key?"

Yes, a record is one of the best. It gives you equals, hashCode and toString over all components automatically, it is immutable, and it prints readably. record PriceQuery(String item, String city) {} works as a default key with no extra annotation.

Watch two points. Every component takes part in equals, so a component that does not affect the result (a request id) makes equal queries different. And a record that contains a mutable collection gives a mutable key, which breaks the rule above.

With Redis the key is turned into a string by the key conversion, which uses toString() for most types, so a record's toString() becomes part of the Redis key. That is fine, but changing the record's fields changes the key text, and old entries are orphaned until they expire.

For a Redis cache I still prefer an explicit string key, because I control the text.

"What if I cannot change the class, for example it comes from a library?"

Then do not use it as a key. Build the key from its fields with SpEL, key = "#q.item + ':' + #q.city", or from a custom KeyGenerator bean that knows how to read the library type.

If the key needs several values from a type you do not own, a small generator class is cleaner than a long SpEL string, and it can be unit-tested.

Another option is a thin wrapper: your cached method takes plain String parameters, and a non-cached method converts the library object into those values and calls it. The wrapper bean keeps the conversion out of the annotation.

What I avoid is subclassing the library type just to add equals. That ties your cache to a class hierarchy you do not control.

"Does the same mistake happen with Redis?"

Yes, with an extra twist. Redis keys are strings, so Spring converts the key object to a string, usually with toString(). A class with no toString() override gives com.quickbite.PriceQuery@1b6d3586, and the number differs for every object, so you again get a new key per call, now stored in Redis where every pod can see the growing set.

The data stays in Redis until its TTL ends. With no TTL, it stays forever. That is why a TTL is not optional for a Redis cache (question 28).

The explicit key fixes it in the same way. And an explicit key gives you a readable name such as quickbite:prices::biryani:Mysuru, which you can search with redis-cli --scan.

The measured Redis output in the caching section shows keys in the form prefix + cacheName + "::" + key.

Q23. "condition versus unless — what is the difference, and how do you avoid caching nulls?"

Reveal answer

Strong answer Both are SpEL expressions that decide whether to cache, and they differ in when they run and what they can see.

AttributeEvaluatedCan use #result?If it is false/true
conditionBefore the method runsNocondition false: the cache is skipped completely, no lookup and no store
unlessAfter the method returnsYesunless true: the result is not stored

condition answers "should this call use the cache at all?" It sees the arguments, for example condition = "#item.length() > 4". When it is false, the call behaves as if the annotation were absent. unless answers "is this particular result worth storing?" It sees #result, so unless = "#result == null" keeps nulls out.

To avoid caching nulls, use unless = "#result == null". Without it, Spring does cache null for stores that allow it (the default CaffeineCacheManager does). A missing item then stays "missing" until the entry expires, even if it is created a second later.

There is a counter-argument, and it is a real design choice. Not caching nulls means a request for an item that does not exist always hits the database, and an attacker or a bug can send millions of such requests. This is called cache penetration. A short-lived cached null protects the database. Choose deliberately: skip nulls when new items must appear at once, and cache nulls with a short TTL when you worry about repeated lookups of absent data.

Picture it Four methods against a missing item and a short name. The runner prints time, result and a database-call counter for each call.

MenuService.java (excerpt) · Boot 4.2runs offline
@Cacheable(value = "unlessNull", unless = "#result == null")
Integer priceUnlessNull(String item)

@Cacheable("nullsCached")
Integer priceNullsCached(String item)

@Cacheable(value = "cond", condition = "#item.length() > 4")
Integer priceCond(String item)

Make the invisible visible: Call each twice: a missing item with unless, a missing item without it, then a short and a long name with condition.

output · Boot 4.2 (B/condition.out)runs offline
== unless="#result == null" on a missing item
priceUnlessNull(ghost) 1st         -> null      270 ms   db calls so far: 1 (MISS)
priceUnlessNull(ghost) 2nd         -> null      202 ms   db calls so far: 2 (MISS)
== no unless: the null is cached too
priceNullsCached(ghost) 1st        -> null      202 ms   db calls so far: 3 (MISS)
priceNullsCached(ghost) 2nd        -> null        0 ms   db calls so far: 3 (hit)
== condition="#item.length() > 4"
priceCond(dosa) 1st                -> 8900      208 ms   db calls so far: 4 (MISS)
priceCond(dosa) 2nd                -> 8900      200 ms   db calls so far: 5 (MISS)
priceCond(biryani) 1st             -> 24900     201 ms   db calls so far: 6 (MISS)
priceCond(biryani) 2nd             -> 24900       0 ms   db calls so far: 6 (hit)

What you see: With unless the null was not stored, so both calls to ghost missed (270 and 202 ms). Without it the null was stored, so the second call hit at 0 ms. With condition, dosa (4 letters) skipped the cache and missed twice, while biryani missed once and then hit.

Why: condition decides before the call whether the cache is involved, and unless decides after the call whether the result is kept. Only unless can see the result. See section 04 for the table.

Land it I use condition to decide before the call whether to use the cache, unless to veto a result after the call, and unless result is null to keep nulls out, unless I want a short negative cache on purpose.

Likely follow-ups
"Can I combine condition and unless on one annotation?"

Yes, and they work in order. First condition runs on the arguments. If it is true, Spring does the lookup, and on a miss calls the method. Then unless runs on the result, and if it is true the result is returned but not stored.

A realistic example is shown below. It says "use the cache for real item names, and never store absent or absurd values".

Combined · Boot 4.2runs offline
@Cacheable(value = "prices",
    condition = "#item.length() > 2",
    unless = "#result == null || #result > 100000")

Be careful about one thing. When condition is false, nothing is looked up, so a stale entry from an earlier call with different arguments is not returned, and also nothing is stored. The call goes straight through.

Both expressions are checked at run time. A typo gives an error on the first call, not at startup, so I put a test on each cached method.

"What is cache penetration and how do I defend against it?"

It is a flood of requests for keys that do not exist. Each one misses the cache, hits the database, finds nothing, and with unless = "#result == null" stores nothing, so the next request does the same. A script that asks for random item names can keep the database busy while the cache sits idle.

Defences, cheapest first: cache the null for a short time (30 to 60 seconds), validate the input before it reaches the cached method (only known item ids), and rate-limit the endpoint. A Bloom filter in front is the heavy option for very large key spaces.

The caching demo shows the null stored and returned from the cache at 0 ms on the second call. That is the protection, and the TTL decides how long a newly created item stays invisible.

I choose the TTL from the business rule: how soon must a new menu item appear?

"Why can't condition use #result?"

Because it runs before the method. The result does not exist yet, so Spring evaluates the expression without it and an attempt to read #result fails (or is not available). That is by design: condition can also skip the lookup, and a lookup happens before any call.

If you need the result in the decision, use unless. If you need to decide before the call from the arguments, use condition. There is no way to make condition depend on the outcome of the call.

A tip for reading SpEL: parameters are available as #name (needs -parameters, which Boot's parent enables) or #p0, #a0. The target object is #root.target and the method is #root.method. The result, only in unless and @CachePut, is #result.

Keep the expressions short. A long SpEL string in an annotation is hard to read and only checked at run time. Move complex rules into a method and call it: condition = "@cacheRules.shouldCache(#item)".

"How do I test condition and unless so that a typo does not reach production?"

I write one test per expression that calls the method twice with the arguments that should be cached and twice with the ones that should not, and counts the calls on a mocked repository. That is exactly what the demo's call counter does.

ConditionTest.java (idea) · Boot 4.2runs offline
@Test void shortNamesBypassTheCache() {
    menu.priceCond("dosa");  menu.priceCond("dosa");
    verify(repo, times(2)).find("dosa");      // not cached
    menu.priceCond("biryani"); menu.priceCond("biryani");
    verify(repo, times(1)).find("biryani");   // cached
}

A typo inside the SpEL string, such as #iem, is only found when the method runs, so the first call fails with an evaluation error. A test finds it in the build.

I did not run this class, but the same four calls were run in the demo above and gave the counts shown. See question 31 for the full test setup with @MockitoBean.

Keep each expression short, so one test explains it, and move complex rules into a method call such as a bean reference.

Q24. "Why is there no TTL on @Cacheable, and where do you set one?"

Reveal answer

Strong answer Because the Spring cache abstraction is deliberately small. It defines "get, put, evict" and nothing about time or size. Expiry is a feature that only some stores have and each one has it in its own way, so the abstraction leaves it to the provider.

That is why @Cacheable has no ttl attribute, and why a cache without any provider setting never expires. With the default ConcurrentMapCacheManager, entries live until the application stops.

Where to set it:

ProviderSettingWhat it means
Caffeinespring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10mSize limit and time since the entry was written, for all caches of the manager
Redisspring.cache.redis.time-to-live=10mEvery entry expires after 10 minutes
Per-cache TTLsA custom CacheManager or a customizer beanDifferent lifetimes for different caches
Simple mapNoneNo expiry, no size limit: avoid in production

expireAfterWrite counts from when the entry was stored, so after the time passes the next call is a miss and reloads. expireAfterAccess counts from the last read, so a hot entry never expires, which can keep very old data alive. For prices I use expireAfterWrite.

A trap from the Redis measurements: when you define your own RedisCacheConfiguration bean, Boot's spring.cache.redis.* properties stop applying. The demo printed a TTL of 30 seconds from the bean, not the 20 seconds from the property.

Choose the TTL from the business: how long may this value be wrong?

Picture it Same idea, two providers: the cache key, the annotation and the method are identical, and only the provider setting differs. Then the real expiry run with a 2-second TTL.

Caffeine

Size and expiry in the provider spec, per JVM.

application.properties · Boot 4.2runs offline
spring.cache.type=caffeine
spring.cache.caffeine.spec=\
  maximumSize=500,expireAfterWrite=2s,recordStats

Redis

Expiry as a property, shared by all pods.

application.properties · Boot 4.2runs offline
spring.cache.type=redis
spring.cache.redis.time-to-live=2s
spring.cache.redis.key-prefix=quickbite:

The shift: The annotation on the method did not change, only the provider setting did.

Make the invisible visible: Read at t=0, t=1.0 s, t=2.3 s (after expiry) and t=2.5 s, with a 2-second TTL.

output · Boot 4.2 (B/expiry.out)runs offline
cache manager: CaffeineCacheManager
price(biryani) t=0.0s              -> 24900     276 ms   db calls so far: 1 (MISS)
price(biryani) t=1.0s              -> 24900       2 ms   db calls so far: 1 (hit)
price(biryani) t=2.3s (expired)    -> 24900     200 ms   db calls so far: 2 (MISS)
price(biryani) t=2.5s              -> 24900       0 ms   db calls so far: 2 (hit)
caffeine stats: CacheStats{hitCount=2, missCount=2, loadSuccessCount=0, loadFailureCount=0, totalLoadTime=0, e

What you see: The first call missed (276 ms). At 1.0 s it hit (2 ms). At 2.3 s the entry had expired, so the call missed again (200 ms) and reloaded. At 2.5 s it hit again. The statistics show 2 hits, 2 misses and 1 eviction.

Why: The TTL is a property of the store, not of the annotation, so the same @Cacheable method gets a different lifetime when you change the setting. The TTL-in-provider idiom collects the settings.

Land it The abstraction has no TTL on purpose, so I set expiry in the provider, and I always set one, even if it is long, as the safety net behind invalidation.

Likely follow-ups
"How do I give different TTLs to different caches?"

The simple properties apply one setting to all caches of a manager. For different lifetimes you configure each cache. With Redis, a RedisCacheManagerBuilderCustomizer bean registers a named configuration, for example prices for 5 minutes and menuList for 1 hour. With Caffeine, you register each cache with its own Caffeine builder in a custom CaffeineCacheManager setup.

I did not run the per-cache variants for the course. The single-setting versions were run and are shown above, so check the reference for your version when you write the per-cache form.

A simpler design is often enough: group data by lifetime into two or three caches with sensible defaults, instead of tuning each. Fast-changing data (prices) gets minutes, slow-changing data (restaurant addresses) gets hours.

Write the TTL next to the cache name in a comment, and in the same place note who owns the staleness decision.

"What is the difference between expireAfterWrite and expireAfterAccess?"

expireAfterWrite starts the clock when an entry is written and never resets it on reads. After the time passes, the entry is gone even if it was read a second ago. expireAfterAccess resets the clock on every read or write, so an entry that is used often never expires.

For data that can become wrong, use expireAfterWrite. It gives a firm upper limit on staleness. With expireAfterAccess, a popular price could stay cached for weeks, still showing the value from the day it was first loaded.

expireAfterAccess fits data that never goes stale but should be dropped when unused, such as the result of an expensive but pure computation. It bounds memory, not correctness.

Caffeine also has refreshAfterWrite, which reloads in the background while the old value is still served, but it needs a loading cache and is not driven by @Cacheable alone. I mention it as an option and do not rely on it in this answer.

"Does the TTL start again when the entry is evicted and reloaded?"

Yes. Eviction removes the entry, and the next miss stores a new one with a new write time, so the full TTL starts again. The demo shows it at t=2.3 s: the expired entry was reloaded, and at t=2.5 s the new entry was a hit with a fresh lifetime.

This is why a stampede after expiry can happen. If many callers wait for the same hot key to expire, they all miss at the same moment and all reload (question 25). sync = true solves it within one JVM.

Another effect: many keys written at the same time expire at the same time, which can produce a wave of reloads. A little random jitter on the TTL spreads the reloads out. With Redis you can add it in a custom configuration. With the plain properties you cannot.

I keep a simple rule: pick a TTL, watch the hit ratio and the database load after expiry, and only add refinements if the graph shows a wave.

"Can a very long TTL be a problem even if I evict on every write?"

It can, because eviction is not reliable on its own. A write from another service, a script run directly on the database, an instance with its own local cache, or an eviction that ran before a commit (question 20) can all leave a stale value. With a 24-hour TTL it stays wrong for a day.

I keep the TTL short enough that an eviction bug is tolerable. For prices, 10 minutes is usually acceptable and cheap. For a hot key, 10 minutes of caching still removes most of the load: at 100 requests per second that is 60,000 requests answered per database read.

Hand-worked: 100 requests per second for 600 seconds is 60,000 requests. With one miss per 10 minutes, the hit ratio is 59,999 / 60,000.

The best compromise is a short TTL plus eviction. The TTL limits damage, and the eviction gives fast updates in the normal case.

Q25 · Scenario. "200 requests miss the cache at the same moment after a deploy and hammer the database. Fix it."

Reveal answer

Strong answer This is a cache stampede, also called a thundering herd. The cache is empty after the deploy, a popular key is requested by 200 callers at once, every one of them misses, and every one runs the slow database query for the same value. The cache only helps after the first load finishes, but by then 200 queries are already running.

Spring has a one-attribute fix for the in-process part: @Cacheable(sync = true). With it, only the first caller for a key runs the method, and the other callers for the same key wait and then take the stored value. The demo shows 20 threads on a cold cache: 20 database calls without sync, 1 with it.

Why it matters in numbers (hand-worked): a connection pool of 10 and a 180 ms query. 200 simultaneous queries need 200 / 10 = 20 rounds of 180 ms, so the last caller waits about 3.6 seconds, and everything else that needs a connection waits too. With sync = true there is one query and about 0.2 seconds of waiting.

sync = true is per JVM. With 5 pods you still get one query per pod, so 5, which is fine. It is also per key, so different keys still load in parallel.

Beyond sync, three more things help after a deploy:

  • Warm the cache at start-up with the hot keys (before the pod joins the load balancer, using the readiness probe).
  • Spread expiry with a little jitter on the TTL, so many keys do not expire together.
  • Roll out gradually, so not every pod starts cold at the same moment.

Use sync = true on expensive reads of hot keys. It has a small cost: waiting callers hold a thread while the first one loads.

Picture it Twenty threads call a slow cached method for the same key at once on a cold cache: first without sync, then with it. A counter in the "database" counts the calls.

Plain

Every miss runs the method.

MenuService.java · Boot 4.2runs offline
@Cacheable("plain")
public Integer slow(String item) {
    return repo.find(item);
}

With sync

Only the first caller runs it.

MenuService.java · Boot 4.2runs offline
@Cacheable(value = "synced", sync = true)
public Integer slowSync(String item) {
    return repo.find(item);
}

The shift: One attribute turns 20 database calls into 1.

Make the invisible visible: Run both versions with 20 threads released together.

output · Boot 4.2 (B/stampede.out)runs offline
cache manager: CaffeineCacheManager
sync=false 20 threads, same key, cold cache: db calls = 20, wall time = 221 ms
sync=true  20 threads, same key, cold cache: db calls = 1, wall time = 205 ms

What you see: Without sync: 20 database calls. With sync = true: 1 database call. The wall time stayed about 200 ms in both runs, because every caller waits for one 200 ms load.

Why: The first caller takes a per-key lock inside the cache provider, loads the value, and the others wait on the same lock. That is why the total time does not grow, while the database load drops 20 times. The cache-sync idiom and Fig. 22.6 show the same picture.

Land it I add sync = true on expensive hot reads so only one caller loads a missing key, and I warm the cache and add TTL jitter so a deploy does not start cold.

Likely follow-ups
"How does sync = true work inside, and is there a cost?"

Spring calls the cache's get(key, valueLoader) instead of separate get and put calls. With Caffeine, that maps to an atomic compute-if-absent, which holds a lock for that key only while the loader runs. Other threads asking for the same key block until the value arrives. Threads asking for other keys are not blocked.

The cost is waiting threads. If the load takes 3 seconds and 200 threads wait, 200 request threads are parked for 3 seconds. On a small thread pool that can exhaust it. Put a timeout on the underlying query, so a slow load fails fast and releases everyone.

Also, the load runs while the lock is held, so avoid doing anything slow or risky in the cached method beyond the fetch itself.

Without sync, the same hot key gives you a thundering herd on the database. With sync, it gives you a short queue in the application. The queue is much cheaper than the herd.

"Does sync = true protect me when I run ten pods?"

Only inside each pod. Each pod has its own cache and its own lock, so a cold start of ten pods produces ten loads for the hot key, one per pod. For most databases ten identical queries are fine.

If ten is still too many, for example a query that takes 30 seconds, use a shared cache (Redis) so one pod's result serves all, and take a short distributed lock or use a "single flight" approach so only one pod loads. That is more machinery, so ask first whether the query should be that slow.

The other cure is to avoid the cold start at all: pre-warm the hot keys before a new pod takes traffic, and roll pods out one or two at a time.

I measure first. Look at the database load right after a deploy: if it peaks only briefly at a few times the normal rate, sync = true is enough.

"What is "stale-while-revalidate", and can Spring do it?"

It means serving the old value while a background task fetches a fresh one, so that no caller ever waits for a reload. It removes the wave of waiting at expiry.

Caffeine supports it through refreshAfterWrite: after the refresh time, the next read returns the old value at once and starts an asynchronous reload. It needs a loading cache with a loader function, and the plain @Cacheable path does not set one up for you, so you would build the cache yourself or use a library on top.

I did not run this for the course. The simpler options (sync = true, jitter, warm-up) cover most services.

If you do build it, accept the trade-off: callers may see a value up to the refresh interval older than the database, and an error in the background refresh must not wipe out the good value.

"A stampede still happens after the deploy even with sync = true. What else could it be?"

Four things I check. Different keys. sync is per key, so 200 requests for 200 different items all load in parallel. That is not a stampede on one key but a cold-cache load, and warming is the cure. A key mistake. If the key includes something that changes per request (a request id, a new object without equals), every call is a different key (question 22).

No sync on that method. One method with @Cacheable but without sync is enough. Check each hot method. And many pods starting together, which is the per-JVM point above.

I also check that the cache is not being cleared on a schedule. A @CacheEvict(allEntries = true) run every minute turns every minute into a cold start.

Metrics show it quickly: the miss counter jumps at the same moment the database load jumps (question 32).

Q26. "Caffeine versus Redis versus ConcurrentMapCache — when do you use each?"

Reveal answer

Strong answer I choose by three questions: must several pods share the cache, must it survive a restart, and how large can it grow?

OptionPick it whenCost or catch
ConcurrentMapCache (Boot's fallback)Tests, demos, a tiny fixed set of keysNo TTL, no size limit: it grew until OutOfMemoryError in the demo
Caffeine (in-process)One pod's own hot data: prices, lookups, config. Fastest, no networkEach pod has its own copy, so pods can disagree (question 27). Lost on restart
Redis (remote)Pods must share one cache, you need a shared TTL or survive restartsA network hop per read, values must be serialized, one more system to run and secure
Two-level (Caffeine in front, Redis behind)Very hot reads, many pods, and you can accept short stalenessTwo layers to invalidate; more moving parts

The measured picture from the caching section: a hit in Caffeine took 0 ms. A hit in Redis took about 43 ms in the demo, with a local container, a first call of 1,356 ms that included connecting, and Java serialization. Treat those as a rough size, not as a Redis benchmark. Redis is still far cheaper than a database query, but it is not free.

My default for a single service is Caffeine with a size limit and a TTL. It is fast, has no extra system, and the staleness window is bounded by the TTL. I move to Redis when pods must agree immediately or when the cached data is large and expensive to rebuild after every deploy.

Never ship the simple map to production for anything that has many keys.

Picture it Two runs of the same method with 200,000 distinct keys and a 128 MB heap. One uses the default simple map. The other uses Caffeine bounded to 10,000 entries.

Make the invisible visible: The simple map: used heap after every 20,000 keys.

output · ConcurrentMapCacheManager (B/growth-simple.out)runs offline
cache manager: ConcurrentMapCacheManager
max heap = 128 MB
keys=20,000  used heap=43 MB
keys=40,000  used heap=64 MB
keys=60,000  used heap=86 MB
keys=80,000  used heap=106 MB
keys=100,000  used heap=125 MB
output · the failure (B/growth-simple.out)runs offline
Caused by: java.lang.OutOfMemoryError: Java heap space

Make the invisible visible: Caffeine with maximumSize=10000.

output · CaffeineCacheManager (B/growth-caffeine.out)runs offline
cache manager: CaffeineCacheManager
max heap = 128 MB
keys=20,000  used heap=33 MB
keys=40,000  used heap=34 MB
keys=60,000  used heap=34 MB
keys=80,000  used heap=34 MB
keys=100,000  used heap=35 MB
keys=120,000  used heap=35 MB
keys=140,000  used heap=34 MB
keys=160,000  used heap=34 MB
keys=180,000  used heap=35 MB
keys=200,000  used heap=33 MB
finished 200,000 keys

What you see: The simple map used more heap with every batch of keys (43, 64, 86, 106, 125 MB) and died with OutOfMemoryError: Java heap space at about 100,000 keys. Caffeine stayed near 34 MB for all 200,000 keys, because it kept only the most recent 10,000.

Why: The simple map never removes anything, and Caffeine removes entries once it passes the size limit. The measured Redis numbers (hit 43 ms, JSON values) are in section 04. See the TTL idiom for the settings.

Land it I default to Caffeine with a size limit and a TTL, move to Redis when pods must share one cache, and never use the plain map in production.

Likely follow-ups
"When is a two-level cache worth the extra complexity?"

When the read rate is very high, the data is shared across many pods, and a Redis round trip on every read is too slow or too costly. The local Caffeine layer answers most reads in nanoseconds, and Redis answers the rest, so the database sees almost nothing.

The price is invalidation. A change must clear Redis and also every pod's local copy. The usual way is a Redis pub/sub message "evict key X" that every pod listens to. If a message is lost, the local copy stays stale until its short local TTL runs out, and that is why the local TTL is much shorter than the Redis TTL.

Spring does not give you this layered cache out of the box with annotations only. You build a CacheManager that composes two, or use a library for it.

I would reach for it after measuring that Redis latency is the bottleneck, not before. A single Caffeine layer with a short TTL covers most services.

"What does JCache (JSR-107) add, and should I use it?"

JCache is a standard Java caching API with its own annotations and a provider model. Spring supports it behind its own abstraction, and Boot can configure a JCache provider such as Ehcache.

Its benefit is portability between providers and richer standard features such as listeners. Its cost is a second set of annotations (@CacheResult, @CacheRemove) that most Spring developers do not know, and an extra layer between you and the provider.

In practice, Spring's own @Cacheable with Caffeine or Redis covers what most teams need, and I rarely see JCache chosen for new code. I use it only when a company standard or a legacy provider requires it.

I did not run a JCache setup for the course, so treat this as the usual guidance and check the Boot reference for the supported providers on your version.

"What changes about my cached objects when I move from Caffeine to Redis?"

Three things. Serialization: the values must be turned into bytes. Boot's Redis cache uses JDK serialization by default, which needs Serializable classes and writes opaque bytes. Boot 4 uses Jackson 3 for JSON when you configure it, and the demo printed readable values such as {"@class":"...","name":"biryani","cents":24900}.

Copies: each hit returns a new object, so a caller that changes it does no harm, unlike an in-process cache that shares one reference.

Compatibility: an old entry written by version 1 of the class must be readable by version 2 during a rolling deploy, or you get errors, so keep cached classes stable or change the cache prefix when the shape changes.

The measured detail: after defining a custom RedisCacheConfiguration bean, the spring.cache.redis.* properties stopped applying. Configure either with properties or with the bean, and know which one is active.

"How do I choose the size bound for Caffeine?"

From memory and from the working set: how many distinct keys are used often. I estimate the size of one entry, multiply by the count, and leave room. 10,000 entries of about 1 KB is roughly 10 MB, which is small. In the demo, 10,000 entries of a 1,000-character string kept the heap near 34 MB in total.

Then I watch the metrics. A steady rate of evictions with a low hit ratio means the bound is too small for the working set. A hit ratio that is already high and an eviction rate near zero means there is room to spare.

For entries of very different size, use maximumWeight with a weigher instead of maximumSize. I did not run that variant here.

Always bound the cache. A bound you guessed wrongly costs some hits. No bound can cost the whole application.

Q27 · Scenario. "Three pods each keep a local Caffeine cache, and a price change shows old prices on some pods for 10 minutes. What are your options?"

Reveal answer

Strong answer The change reaches the database, but only the pod that handled the update evicts its own entry. The other two pods keep their cached copy until it expires, which is the 10-minute TTL. This is the price of a local cache: each pod is its own copy of the truth.

Options, from the cheapest to the most work:

OptionHow it helpsCost or catch
Shorter TTLBounds staleness (a 1-minute TTL means up to 1 minute wrong)More database reads, and still stale in between
Shared cache (Redis)One copy for all pods, so one eviction clears it for everyoneA network hop per read, a system to run
Broadcast eviction (Redis pub/sub or a message bus)Every pod hears "evict biryani" and clears its local copyA lost message leaves a stale copy until the TTL, so keep the TTL too
Versioned keysThe key contains a version, for example price:v17:biryani, so a new version is a new keyNeeds a version source that all pods read cheaply
Do not cache that valueAlways correctHigher load and latency

My usual answer is a combination: keep the local cache for speed, set a short TTL as the safety net, and broadcast evictions so a change reaches every pod in milliseconds. If prices must be exactly right, for example at checkout, read the price from the database inside the order transaction, and use the cache only for browsing.

Ask the business first how stale a price may be. "Ten minutes" may be fine for the menu page and wrong for the payment page.

Picture it Three simulated pods in one JVM, each with its own Caffeine cache and one shared database. A price change evicts only the pod that took the request. Then the two fixes: a broadcast eviction (a stand-in for Redis pub/sub), and a TTL-only run.

Make the invisible visible: Run the three situations.

output · Boot 4.2 (B/pods.out)runs offline
cache manager: CaffeineCacheManager
all pods warm: pod-A=24900  pod-B=24900  pod-C=24900
-- price changes to 26900; the request hit pod-A, which evicts its own entry only
after change:  pod-A=26900  pod-B=24900  pod-C=24900
-- fix 1: broadcast the eviction (stand-in for Redis pub/sub)
after broadcast: pod-A=27900  pod-B=27900  pod-C=27900
-- fix 2: TTL only. Change the price, evict nowhere, wait for the 3 s TTL
t=0.0s:        pod-A=27900  pod-B=27900  pod-C=27900
t=3.2s:        pod-A=28900  pod-B=28900  pod-C=28900

What you see: After the change, pod-A showed 26900 but pod-B and pod-C still showed 24900. The broadcast made all three agree at once (27900). With TTL only, all three showed the old price until the 3-second TTL ran out, and then all showed 28900.

Why: A local cache has no idea what the other pods do. A broadcast gives agreement in milliseconds, and the TTL gives agreement eventually, even when a message is lost. Fig. 22.7 draws the same picture, and the evict-on-write idiom covers the single-pod half.

Land it I keep the local cache for speed, add a short TTL as the safety net, and broadcast evictions so every pod clears its copy, and I read the exact price from the database where correctness matters.

Likely follow-ups
"How does a Redis pub/sub eviction work in practice?"

The pod that handles the price change publishes a small message on a Redis channel, for example cache-evict with the text prices:biryani. Every pod subscribes to that channel through a listener container. When a message arrives, the pod evicts that key from its local cache.

Spring Data Redis provides the listener infrastructure, and Boot 4.1 added auto-configured Redis listener endpoints, so the plumbing is short. The listener method is a few lines that call cache.evict(key).

Two cautions. Redis pub/sub is fire and forget: a pod that is disconnected at that moment misses the message and keeps the stale entry until its TTL expires. And a pod's own message comes back to itself, so evicting twice is harmless but pointless. Keep the TTL as the backstop.

I did not run the Redis variant for the course. The broadcast in the demo is a loop over three caches in one JVM, which shows the effect and not the network behaviour.

"Why not just make the TTL one second?"

Because the TTL controls two things at once: how stale data can be and how much load the database sees. A one-second TTL means the hot key is reloaded every second by each pod. With 3 pods that is 3 queries per second for that key instead of 3 queries every 10 minutes, which is 600 times more load.

Hand-worked: with a 10-minute TTL each pod loads the key once per 600 seconds, so 3 pods load it 3 times in 600 seconds. With a 1-second TTL, 3 pods load it 1,800 times in 600 seconds, which is 600 times more.

A very short TTL also brings the stampede problem back at every expiry. It can end up worse than no cache for popular keys.

A TTL of tens of seconds to a few minutes plus eviction is the usual compromise. The right number comes from how wrong the business can tolerate the data being.

"What are versioned keys, and what makes them hard?"

A versioned key puts a version number into the key, so that a change creates a new key and the old entries simply stop being used, then expire. For prices, key = "'v' + @priceVersion.current() + ':' + #item": when the version goes from 17 to 18, every pod starts reading and writing v18:... keys.

The advantage is that no eviction message is needed and no stale read is possible once a pod knows the new version. The difficulty is knowing the version cheaply. Every pod must read it on every call, so it has to come from something fast and shared, such as a Redis counter, and then you again depend on a network call.

Old entries still occupy memory until they expire, so a TTL and a size bound remain necessary.

I use versioned keys for data that changes in big batches (a whole menu republished at once), and eviction for single-item changes.

"How can I show the team that stale data is a real risk and not a theoretical one?"

By reproducing it in a small test, the way the demo does. Create two cache managers in one test, warm both, change the data through one, and assert that the other still returns the old value. The test documents the behaviour and fails the day somebody adds a broadcast that works.

Then add a line to the incident notes: a stale price on one pod shows up as "the customer sees one price and pays another", which is a support ticket, not a bug in the cache.

I also add a metric: record the age of the cached value when served, or log the pod name next to the price on the order page in a test environment. When different pods show different values, the problem is visible at once.

After the team has seen it, the discussion about TTL, broadcast and shared cache is about numbers instead of opinions.

Q28. "What does a Redis cache need that a local cache does not?"

Reveal answer

Strong answer A local cache keeps Java objects in the same JVM. A Redis cache lives in another process, so five things appear that a local cache never needed.

  1. Serialization: each value is turned into bytes and back. The default is JDK serialization (opaque bytes, needs Serializable). A JSON serializer is easier to read and to evolve. Boot 4 uses Jackson 3 for this.
  2. A mandatory TTL: Redis keeps data until it expires or memory runs out, so set spring.cache.redis.time-to-live.
  3. Key naming: keys are strings in a space shared by every application on that Redis. Boot builds them as prefix + cache name + :: + key, so set a prefix such as quickbite:.
  4. Failure handling: Redis can be down or slow. By default a cache error becomes an error in your method. Decide with a CacheErrorHandler whether a cache failure means "skip the cache and call the database".
  5. Operations: authentication, TLS, a maxmemory limit with an eviction policy, timeouts on the connection, and monitoring.

Also remember the compatibility rule: during a rolling deploy, version 1 and version 2 of your class share one Redis. An entry written by one must be readable by the other, or you get errors until the TTL passes. Change the key prefix when a cached class changes shape.

One measured trap: when you define your own RedisCacheConfiguration bean, the spring.cache.redis.* properties stop applying. The demo printed a TTL of 30 seconds from the bean, not 20 seconds from the property. Use properties or the bean, not both.

Picture it The same cached method run against a real Redis in Docker, first with Java serialization and then with a JSON serializer bean. After each run the demo read the key and the stored bytes with redis-cli.

JDK serialization

The default. The stored value is binary.

application.properties · Boot 4.2runs offline
spring.cache.type=redis
spring.cache.redis.time-to-live=20s
spring.cache.redis.key-prefix=quickbite:

JSON serializer

A RedisCacheConfiguration bean with Jackson 3.

RedisJsonConfig.java · Boot 4.2runs offline
.entryTtl(Duration.ofSeconds(30))
.prefixCacheNameWith("quickbite:")
.serializeValuesWith(fromSerializer(
  GenericJacksonJsonRedisSerializer
    .builder()...build()))

The shift: The bean gives readable JSON, and it also replaces the properties, so its 30 seconds beat the 20.

Make the invisible visible: Call the method twice, then list the key, its TTL and its value.

output · Boot 4.2 (B/redis.out)runs offline
# JDK serialization (default)
cache manager: RedisCacheManager
item(biryani) 1st                  -> MenuItem[name=biryani, cents=24900] 1356 ms   db calls so far: 1 (MISS)
item(biryani) 2nd                  -> MenuItem[name=biryani, cents=24900]   43 ms   db calls so far: 1 (hit)
$ redis-cli --scan
quickbite:items::biryani
$ redis-cli TTL quickbite:items::biryani
19
$ redis-cli GET (escaped)
"\xac\xed\x00\x05sr\x00\x1ccom.quickbite.cache.MenuItem\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x02I\x00\x05ce

# JSON serializer bean (demo.redis-json=true)
cache manager: RedisCacheManager
item(biryani) 1st                  -> MenuItem[name=biryani, cents=24900]  951 ms   db calls so far: 1 (MISS)
item(biryani) 2nd                  -> MenuItem[name=biryani, cents=24900]   42 ms   db calls so far: 1 (hit)
quickbite:items::biryani
30
{"@class":"com.quickbite.cache.MenuItem","name":"biryani","cents":24900}

What you see: The first call took 1,356 ms because it also opened the connection, and the second hit took 43 ms. The key was quickbite:items::biryani. With JDK serialization the value was unreadable bytes. With the JSON serializer it was {"@class":"...","name":"biryani","cents":24900}, and the TTL was 30.

Why: A Redis hit is far cheaper than a database read, but it is a network call and not free. The serializer decides what other tools and later versions of your class can read. See section 04 for the provider table.

Land it A Redis cache needs serialization, a TTL, a key prefix, a plan for Redis being down, and a rule for evolving the cached classes.

Likely follow-ups
"What happens to my request if Redis is down?"

By default the cache call throws, and because the cache interceptor is outside your method, the exception reaches the caller: a request that could have been served from the database fails instead. A cache outage becomes a service outage.

You can change that with a CacheErrorHandler, registered through a CachingConfigurer. Its methods (handleCacheGetError, handleCachePutError and so on) can log and return normally, so a failed get behaves like a miss and the method runs against the database.

That trades one risk for another. If every request now goes to the database while Redis is down, the database may be overloaded, so combine it with a short Redis timeout, a local Caffeine layer, and a circuit breaker.

I did not run a Redis outage for the course, so test it on your setup: stop the container and watch what the endpoint returns.

"Why do I need a key prefix?"

Because a Redis server is usually shared. Without a prefix, two services that both have a cache called prices write to the same keys and overwrite each other. With the prefix quickbite: the demo's key was quickbite:items::biryani, and you can list only your own keys with redis-cli --scan --pattern 'quickbite:*'.

Boot builds the final key as the prefix, the cache name, two colons and your key. The properties spring.cache.redis.key-prefix and use-key-prefix control it.

Put a version in the prefix when the cached shape changes, for example quickbite:v2:. Old entries then stay unused until they expire, and a rolling deploy never reads a value in the wrong format.

Keep the prefix short, since it is repeated in every key and counts against memory.

"JDK serialization or JSON for the cached values?"

JSON for almost everything. JDK serialization needs every cached class to be Serializable, ties the stored bytes to the exact class and version (a small field change can make old entries unreadable), and gives you data you cannot inspect. The demo's stored value was a block of escaped bytes.

JSON is readable with redis-cli, easier to evolve (extra fields are ignored if you configure it so), and usable from other languages. The cost is configuration: type information is needed to turn JSON back into the right class, and a safe allow-list of packages for that, as the demo's allowIfSubType("com.quickbite") does.

Be careful with type information from untrusted data. A permissive polymorphic setting is a known security risk, so always list the packages you allow.

Boot 4 moved to Jackson 3 (tools.jackson packages), so an old Jackson 2 serializer class from a Boot 3 example will not compile. Use the Jackson 3 one shown in the demo.

"Do I still want a local cache in front of Redis?"

Often yes, for the hottest keys. A local Caffeine hit takes nothing, while a Redis hit took 43 ms in the demo, which was a first-time local container with Java serialization, so read it as a rough size. A hundred hot reads per request would add up.

The price is staleness between the layers: a change clears Redis at once, but each pod's local copy lives until its own TTL or a broadcast eviction (question 27). So the local TTL must be short.

A reasonable shape is local TTL of tens of seconds, Redis TTL of minutes, and an eviction message on every write.

Measure first. If Redis latency is a few milliseconds and the request needs a handful of cached values, a single Redis layer is simpler and often enough.

Q29 · Scenario. "@Cacheable on a method called from the same class doesn't cache. Fix it."

Reveal answer

Strong answer This is self-invocation again (question 8). The call this.price(...) goes straight to the method and never enters the proxy, so the cache interceptor never runs. The annotation is correct and the cache works for outside callers, but not for calls from inside the class.

The ranked fixes:

  1. Move the cached method to another bean: for example MenuPriceCache, injected into MenuService. The call then crosses that bean's proxy. This is the fix I choose, because the cached lookup is a separate responsibility anyway.
  2. Inject the bean into itself with @Lazy and call through that field. It works, but the class now depends on itself, which confuses readers.:
  3. Use AopContext.currentProxy() with exposeProxy = true. It works and couples the class to Spring AOP (question 8).:
  4. Use AspectJ mode: @EnableCaching(mode = AdviceMode.ASPECTJ) with weaving. It also covers private methods but changes how the application starts (question 10).

Check first that this is the cause. Call the method from another bean in a test: if that call caches, the problem is the same-class call.

A related slip is calling a private cached method, or a cached method on an object made with new. Both fail for the same reason: there is no proxy in the path.

Picture it A same-class call to a cached method, then the same call through another bean. The counter shows database calls.

Same class

this.cachedPrice() skips the proxy.

MenuService.java · Boot 4.2runs offline
public String viaSame(String i) {
  return cachedPrice(i);
}

Other bean

The caller holds the proxy of a second bean.

MenuPriceCache.java · Boot 4.2runs offline
public String viaBean(String i) {
  return priceCache.cachedPrice(i);
}

The shift: Extracting the cached method into its own bean is the whole fix.

Make the invisible visible: Three calls each way, with time and the database counter.

output · Boot 4.2 (A/selfinv.out)runs offline
   same-class call #1 -> Rs 249 in 101 ms, db calls so far: 1
   same-class call #2 -> Rs 249 in 100 ms, db calls so far: 2
   same-class call #3 -> Rs 249 in 100 ms, db calls so far: 3
   other-bean call #1 -> 24900 in 113 ms, db calls so far: 4
   other-bean call #2 -> 24900 in 0 ms, db calls so far: 4
   other-bean call #3 -> 24900 in 0 ms, db calls so far: 4

What you see: The same-class calls missed three times (counter 1, 2, 3, each about 100 ms). The calls through another bean missed once (counter 4, 113 ms) and then hit twice at 0 ms.

Why: this is the real object, so the interceptor is skipped. The fix puts the method behind a proxy. The self-invocation idiom shows the full set, and E4, data has the @Transactional version.

Land it I extract the cached method into its own bean so the call goes through a proxy, and I check the cause by calling it from another bean first.

Likely follow-ups
"Is self-injection with @Lazy really acceptable?"

It works. Spring injects a proxy of the same bean (a lazy one, to avoid a start-up cycle), and a call through that field goes through the advisors. Since Spring 4.3 a bean may even inject itself.

I accept it as a quick fix in legacy code. I do not like it in new code, because the class now has a field that points at itself, a new developer has to learn why, and the cached method is still living in a class that does not own it.

The extraction costs about ten lines and removes the question. It also makes the cached lookup easy to test alone.

If you use self-injection, add a comment above the field that says "call through this field so the cache applies". The code looks strange without one.

"Would making the cached method static or final help?"

No, both make things worse. A static method has no object and no proxy, so no advice applies. A final method cannot be overridden by the CGLIB proxy, so the call runs on the proxy object itself and skips the cache (question 9 shows the null fields).

The cache applies to public, non-final instance methods called through a proxy. Every other shape is outside it.

If the method must be shared by several callers, put it in a bean and inject that bean. Static helpers are for pure calculations that you do not want to cache.

When a cached method seems to do nothing, my first check is its shape: public, instance, non-final, on a Spring bean.

"How do I make sure nobody reintroduces this bug later?"

With a test that calls through the public entry point and counts the calls on a mocked dependency, as in question 31. A test that calls the cached method twice and verifies a single repository call fails if somebody moves the method back into the calling class.

Add a short comment on the extracted bean: "kept separate so the cache proxy applies". Without it, a tidy-minded colleague will merge the two classes.

In review, look for @Cacheable, @Async, @Transactional or @Retryable methods that are called by other methods of their own class. A quick search for the annotation and a glance at the callers finds most of them.

Some teams add an architecture test (ArchUnit) that forbids calls between methods of the same class when one of them has a proxy annotation. I did not run that for the course.

"Does the same fix work for @Async and @Retryable?"

Yes, the same one. Move the annotated method into another bean and call it through that bean. The demo shows @Async too: the same-class call ran on main and returned after 300 ms, and the call through another bean ran on task-1 and returned in 4 ms.

For @Retryable the same-class call is not retried, because no retry advisor ran. The exception goes straight to the caller.

Whenever an annotation from this chapter "does nothing", the checklist is short: is it a Spring bean, is the call from another bean, is the method public and non-final, is the feature enabled (@EnableCaching, @EnableAsync, @EnableResilientMethods).

These four questions find the cause nearly every time.

Q30. "How do you cache Optional and null results safely?"

Reveal answer

Strong answer Spring handles both, but the defaults surprise people, so know what is stored.

Null. By default the cache stores null (Caffeine and the simple manager both allow it). A missing item is then answered as "missing" from the cache until it expires, even if it is created a second later. To keep nulls out, use unless = "#result == null". To keep them on purpose (cache penetration, question 23), give the cache a short TTL.

Optional. Spring unwraps an Optional return value: it stores the contained value, or null for an empty Optional, and on a hit it wraps it again, so callers still receive an Optional. The demo shows the stored map: {lassi=5900, ghost=null}, and the empty answer for ghost was served as Optional.empty at 0 ms on the second call.

In unless and @CachePut, #result refers to the unwrapped value, according to the Spring documentation, so unless = "#result == null" also skips empty Optionals. I did not run that combination, so test it on your version.

Safe rules:

  • Decide on purpose whether "not found" is cached, and for how long.
  • Do not cache an Optional as a parameter or put one in a key.
  • Cache immutable values.
  • Never return null from a cached method that is not documented to do so, because a stored null cannot be told from "no entry" without checking ValueWrapper.

Picture it Four calls to methods that return a missing item: one with unless, one without, and two with Optional. The demo prints what was stored.

MenuService.java (excerpt) · Boot 4.2runs offline
@Cacheable(value = "unlessNull", unless = "#result == null")
Integer priceUnlessNull(String item)

@Cacheable("opt")
Optional<Integer> optPrice(String item) {
    return Optional.ofNullable(repo.find(item));
}

Make the invisible visible: Call each twice and print the contents of the opt cache.

output · Boot 4.2 (B/condition.out)runs offline
== unless="#result == null" on a missing item
priceUnlessNull(ghost) 1st         -> null      270 ms   db calls so far: 1 (MISS)
priceUnlessNull(ghost) 2nd         -> null      202 ms   db calls so far: 2 (MISS)
== no unless: the null is cached too
priceNullsCached(ghost) 1st        -> null      202 ms   db calls so far: 3 (MISS)
priceNullsCached(ghost) 2nd        -> null        0 ms   db calls so far: 3 (hit)
output · Optional (B/condition.out)runs offline
== Optional return type
optPrice(lassi) 1st                -> Optional[5900]  201 ms   db calls so far: 7 (MISS)
optPrice(lassi) 2nd                -> Optional[5900]    0 ms   db calls so far: 7 (hit)
optPrice(ghost) 1st                -> Optional.empty  200 ms   db calls so far: 8 (MISS)
optPrice(ghost) 2nd                -> Optional.empty    0 ms   db calls so far: 8 (hit)
   stored in 'opt': {lassi=5900, ghost=null}

What you see: The unless version missed twice for ghost (the null was not stored). The version without it stored the null and answered from the cache at 0 ms. For Optional, the empty answer for ghost was also a hit on the second call, and the cache held ghost=null.

Why: The cache stores plain values, with null for "empty". The wrapper is added and removed at the boundary. See section 04 for the table of condition and unless.

Land it I decide on purpose whether "not found" is cached and for how long, I use unless to keep nulls out, and I remember Spring stores the inside of an Optional.

Likely follow-ups
"Why does the cache hold ghost=null and is that a problem?"

The cache stores the unwrapped content of the Optional, and for an empty one that is null. It is not a problem by itself. It is the "negative cache" that protects the database from repeated lookups of absent items.

It becomes a problem when the item is created later: callers keep getting Optional.empty until the entry expires, so a new menu item can be invisible for the whole TTL.

The fix is not to avoid it but to match the TTL to the business rule, and to evict the key when an item is created (@CacheEvict on the create method).

In the demo, the second call for ghost took 0 ms. That is the hit the negative cache gives, and it is also the staleness risk.

"How can I tell a cached null from a missing entry in code?"

With the Cache API, not the annotation. cache.get(key) returns a ValueWrapper. If the wrapper itself is null, there is no entry. If the wrapper is not null and wrapper.get() is null, a null was stored.

That distinction is what lets the interceptor decide between "hit with null" and "miss". You rarely write this by hand, but it explains why a stored null still counts as a hit in the metrics.

If you disable null storage (allowNullValues is off on some managers), caching a method that returns null raises an exception such as "Cache is configured to not allow null values". Combine such a cache with unless = "#result == null".

Redis caches with default settings accept nulls by wrapping them in a special marker value, so the rule holds there too.

"Should a repository return Optional or throw an exception when nothing is found?"

For caching, both work, but they differ in what is stored. Optional.empty is a normal return value and can be stored as a negative entry. An exception is never stored by @Cacheable, so every request for a missing item hits the database again.

If you want a negative cache, return Optional or a clear "not found" value. If you want every miss to be retried, throw and let the exception skip the cache.

My preference in service code is Optional for "may be absent" and an exception for "must exist", and I pick the caching rule from that. A price of an unknown item is a normal question. A price of an item in an order that must exist is a bug.

Write the choice in the Javadoc of the cached method so the next developer does not change it by accident.

"Does caching an Optional change my API?"

No. The caller still receives an Optional, and the stored form is internal. That is the advantage of Spring unwrapping it.

The one thing to check is serialization in a remote cache. The stored value is the inner type (here an Integer), so a JSON serializer needs no special support for Optional, which is easier than caching the Optional object itself.

Avoid mixing return types between versions of a method. If version 1 returned Integer and version 2 returns Optional<Integer>, the Redis entries written by version 1 are still valid inner values, which is fine, but a cache of a different shape under the same name would not be.

When unsure, change the cache name or prefix whenever the stored shape changes.

Q31. "How do you test that a method is really cached?"

Reveal answer

Strong answer Call it twice with the same arguments and check that the thing behind the cache was used once. Behind the cache is usually a repository, so replace it with a mock and verify the number of calls. If the cache works, the mock sees one call. If it does not, it sees two.

The test needs the real proxy, so it must start a Spring context. A plain unit test that creates the service with new has no proxy and no cache, so it proves nothing.

  1. Start the context with @SpringBootTest (or a slice that imports the cache configuration).:
  2. Replace the repository with @MockitoBean so you can count calls.:
  3. Clear the caches before each test, so tests do not see each other's entries.:
  4. Call twice and verify(repo, times(1)).:

Test the other side as well: an eviction must make the next call hit the repository again. A cache that never forgets passes the first test and fails the second.

Add a negative test for each condition and unless (question 23), and a test that a method called from the same class is not cached if that is a known limit. Keep these tests in the normal build. They run in seconds, apart from the context start.

Picture it The test class from the caching demo, and its real result. The first test checks a hit, the second checks that a price change evicts the entry.

MenuServiceCachingTest.java · Boot 4.2runs offline
@SpringBootTest(args = "--demo=none")
class MenuServiceCachingTest {
  @Autowired MenuService menu;
  @Autowired CacheManager cacheManager;
  @MockitoBean PriceRepository repo;

  @BeforeEach void clean() {
    cacheManager.getCacheNames()
        .forEach(n -> cacheManager.getCache(n).clear());
  }
  @Test void secondCallIsServedFromTheCache() {
    when(repo.find("biryani")).thenReturn(24900);
    menu.price("biryani");
    menu.price("biryani");
    verify(repo, times(1)).find("biryani");
  }
  @Test void changingThePriceEvictsTheEntry() {
    when(repo.find("biryani")).thenReturn(24900);
    menu.price("biryani");
    menu.changePrice("biryani", 26900);
    when(repo.find("biryani")).thenReturn(26900);
    assertThat(menu.price("biryani")).isEqualTo(26900);
    verify(repo, times(2)).find("biryani");
  }
}

Make the invisible visible: Run the two tests with Maven.

output · mvn -o test (B/test.out)runs offline
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 14.84 s -- in com.quickbite.MenuService
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

What you see: Two tests, no failures. Most of the 14.84 seconds is the Spring context starting, not the test bodies.

Why: verify(repo, times(1)) is the proof: the repository was called once for two reads, so the second answer came from the cache. The eviction test proves the cache forgets. This is the pattern in section 04.

Land it I mock the repository, call the cached method twice, verify one repository call, and add a second test that an eviction brings the call back.

Likely follow-ups
"Why must the test start a Spring context?"

Because the cache is a proxy that Spring builds when the bean is created. Without a context there is no CacheInterceptor, no proxy and no cache, and a unit test that does new MenuService(repo) gets plain method calls. Both calls hit the repository, and a "verify once" assertion fails for the wrong reason.

You can keep the context small. A @SpringBootTest with only the service and the cache configuration, or a test class with @ImportAutoConfiguration(CacheAutoConfiguration.class) and @EnableCaching, avoids loading the web layer and the database. I ran the full @SpringBootTest here, and did not time a slimmer version.

Reuse the context across test classes. Spring caches it when the configuration is identical, so only the first test pays the start-up cost.

The mock replaces the repository inside the context, so the proxy still wraps the real service and the real cache sits in front of the mock.

"How do I stop tests from affecting each other through the cache?"

Clear every cache before each test, as the example does in @BeforeEach. The cache belongs to the Spring context, and the context is shared between tests, so an entry written by one test is visible to the next.

The alternative is @DirtiesContext, which discards the context after the test. It works, but it forces a new context start (14 seconds in my run), so use it only when a test changes the configuration.

Use distinct keys per test only as a last resort. A test that depends on keys being different hides the real issue, which is shared state.

Also make the mock return fresh values per test. A mock that still has an earlier test's stub can confuse the call counts.

"Can I test the TTL without waiting 10 minutes?"

Yes, in two ways. Configure a short TTL for the test (spring.cache.caffeine.spec=expireAfterWrite=2s as in the expiry demo) and sleep a little longer than that. It is simple and a bit slow, so keep it to one test.

The cleaner way is a fake ticker. Caffeine lets you provide a Ticker, so a test can advance time without sleeping. You build the cache manager in the test configuration with that ticker. I did not run this variant here.

Test only that the expiry setting is wired, not Caffeine itself. Caffeine's own tests cover its expiry. Yours should prove that your configuration enables it and that your method reloads after expiry.

The demo's expiry run is the manual version of the same check: a miss at 0 s, a hit at 1.0 s, a miss at 2.3 s.

"Should the cache test use the real database?"

Usually not. The point is to show that the repository is called once, and a mock does that with an exact count. A real H2 or Postgres adds time and cannot count calls without extra tools.

Use the real database in a separate test that checks the query is right, and in an integration test that exercises the whole path including the eviction on write. There you can count with a spy or query statistics.

For a Redis-backed cache, a test with Testcontainers and a real Redis is worth having once, to prove the serializer and the TTL work together. The Redis demo above ran against a real container for that reason.

Keep the fast mock test as the everyday check and the slow container test as the occasional one.

Q32. "Which metrics tell you a cache is working, and where do you see them?"

Reveal answer

Strong answer Four numbers, all available through Micrometer when Actuator is present: cache.gets (with a result tag of hit or miss), cache.puts, cache.evictions and cache.size. They are tagged with the cache name and the cache manager.

How to read them:

MetricWhat it tells youWarning sign
cache.gets with result=hit / missThe hit ratio = hits / (hits + misses)Ratio near zero on a hot method (key bug, TTL too short)
cache.putsHow often values are storedPuts equal to gets: nothing is ever reused
cache.evictionsEntries removed by size or expiryA steady high rate: the bound is too small
cache.sizeEntries now in the cacheA line that keeps rising: no bound or a key bug

You see them at /actuator/metrics/cache.gets (expose metrics and caches in management.endpoints.web.exposure.include), or in your monitoring system if Micrometer is connected to one. /actuator/caches lists the caches and their native types.

A measured catch from the demo: the metrics for Caffeine appeared only after I set spring.cache.cache-names and recordStats in the Caffeine spec. A cache that Spring creates lazily on first use was not bound to the metrics registry, so the endpoint showed nothing and it looked like no caching happened.

Compare the hit ratio with the latency of the method. A ratio of 95% with a slow method means the 5% of misses are expensive, and that is where to look.

Picture it A small web app with Caffeine and Actuator. The demo called the cached method four times (two misses, two hits) and then read the endpoints with curl.

settings the demo ran with (passed as arguments) · Boot 4.2runs offline
spring.cache.type=caffeine
spring.cache.cache-names=prices
spring.cache.caffeine.spec=recordStats
management.endpoints.web.exposure.include=caches,metrics

Make the invisible visible: Read the cache list, the metric names, and the hit and miss counts.

output · curl · Boot 4.2 (B/serve-curl.out)runs offline
$ curl -s localhost:18431/actuator/caches
{
    "cacheManagers": {
        "cacheManager": {
            "caches": {
                "prices": {
                    "target": "com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalManualCache"
                }
            }
        }
    }
}
$ curl -s localhost:18431/actuator/metrics | (names containing "cache")
cache.eviction.weight
cache.evictions
cache.gets
output · curl, trimmed · Boot 4.2 (B/serve-curl2.out)runs offline
$ curl -s 'localhost:18431/actuator/metrics/cache.gets?tag=name:prices&tag=result:hit'
cache.gets [{'statistic': 'COUNT', 'value': 2.0}]
$ curl -s 'localhost:18431/actuator/metrics/cache.gets?tag=name:prices&tag=result:miss'
cache.gets [{'statistic': 'COUNT', 'value': 2.0}]
cache.size [{'statistic': 'VALUE', 'value': 2.0}]

What you see: /actuator/caches showed the prices cache with its Caffeine class. The metric list contained cache.gets, cache.puts, cache.evictions, cache.eviction.weight and cache.size. The result=hit count was 2 and result=miss was 2, so the hit ratio was 2 / (2 + 2) = 50%.

Why: Hits and misses are separate series of one metric, told apart by the result tag. The numbers are the same ones the method call counter would show, but they come from the cache itself, so they also count calls that never reached your aspect (question 16). See section 04.

Land it I watch the hit ratio from cache.gets, the size and evictions for bounds, and I make sure the metrics are really bound, since lazily created caches are not.

Likely follow-ups
"Why did my cache metrics not show up?"

Most often the cache is created lazily. Spring Boot's CaffeineCacheManager can create a cache the first time a method asks for it, and a lazily created cache is not bound to the Micrometer registry, so no cache.* meter appears. In the demo the endpoint stayed empty until spring.cache.cache-names=prices told Boot the cache names at start-up.

The second cause is statistics: Caffeine must record them, with recordStats in the spec. Without it, hit and miss counts stay at zero.

Third, the endpoint must be exposed: management.endpoints.web.exposure.include=metrics,caches. And Micrometer must be on the classpath, which Actuator brings.

My checklist is: names declared, recordStats on, endpoint exposed, then call the cached method at least once and look again.

"What hit ratio should I aim for?"

There is no universal number. It depends on how often the same key is asked for before it expires. For a menu page with a few hundred popular items, 95% or more is normal. For per-user data where each key is read twice, 50% would be good.

I judge the ratio by the savings, not by the percentage alone. If a miss costs 180 ms and a hit costs about 1 ms, then at 90% the average is 0.9 x 1 + 0.1 x 180 = 18.9 ms, and at 99% it is 0.99 x 1 + 0.01 x 180 = 2.8 ms. The last nine points of ratio cut the average by almost 7 times.

A falling ratio matters more than a low one. It tells you something changed: a deploy changed the key, the TTL got shorter, or the traffic pattern moved.

Alert on a drop of the ratio together with a rise in database load, not on the ratio alone.

"Should the metrics endpoint be public?"

No. Actuator endpoints expose internals, and /actuator/caches even lists cache names and types. Put them on a separate management port (management.server.port) or protect them with Spring Security, and expose only what you need.

For a Prometheus setup, expose just prometheus and let the monitoring system scrape it from inside the network. Do not expose env or heapdump on any public interface.

The cache metrics themselves are low-risk, but the same endpoint can leak much more. Treat the whole Actuator surface as private.

The production section of E4 covers securing Actuator in more detail.

"Can I get hit and miss counts per method instead of per cache?"

Not from the cache metrics. They are per cache name, so two methods that share a cache name are counted together. If you want per-method numbers, give each method its own cache name, or add a small timing aspect outside the cache (question 16) that records a hit or miss by checking whether the method body ran.

The cleaner way is one cache per kind of value (prices, menuList), which also keeps keys apart (question 21). Then the cache name is already the per-purpose label.

Do not add the method name as a tag to the cache metric by hand if the name set is large. High-cardinality tags overload the metrics store.

For deeper analysis, Caffeine's own CacheStats gives load times and eviction weights, as the expiry demo printed.

Q33 · Scenario. "Memory grows until OutOfMemoryError after adding @Cacheable with the default cache manager. Why?"

Reveal answer

Strong answer Because the default cache manager has no limit and no expiry. When no real cache provider is on the classpath, Spring Boot falls back to ConcurrentMapCacheManager, which is a plain ConcurrentHashMap per cache. Entries stay until you remove them or the application stops. Every new key adds an entry, and nothing ever leaves.

Whenever the number of distinct keys is large or unbounded (a search term, a user id, a date and time, an object key without equals), the map grows with every new key until the heap is full. The demo shows it: with a 128 MB heap, used memory went 43, 64, 86, 106, 125 MB and the program died with OutOfMemoryError: Java heap space at about 100,000 keys.

The fix has three parts:

  1. Use a real provider: add Caffeine and set spring.cache.type=caffeine (or Redis).
  2. Bound it: maximumSize=... (or maximumWeight), so old entries are dropped.
  3. Expire it: expireAfterWrite=..., so data cannot live forever.

Also look for the cause of the key explosion. Keys with timestamps, request ids or objects without equals make every call a new key (question 22), and no bound can make such a cache useful. Fix the key as well as the bound.

How to find it in production: take a heap dump on out-of-memory (-XX:+HeapDumpOnOutOfMemoryError), and look for a huge ConcurrentHashMap owned by a cache. I did not run that analysis for the course. The cache.size metric shows the growth earlier, before the crash.

Picture it Two runs of the same method with 200,000 distinct keys and a 128 MB heap: the default simple manager, then Caffeine with a bound.

Default (simple)

No limit, no expiry. Entries stay forever.

application.properties · Boot 4.2runs offline
spring.cache.type=simple

Bounded Caffeine

A size limit drops the oldest entries.

application.properties · Boot 4.2runs offline
spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=10000

The shift: Two lines of settings turn a memory leak into a fixed 34 MB.

Make the invisible visible: Run both with -Xmx128m and print the used heap after every 20,000 keys.

output · simple manager (B/growth-simple.out)runs offline
cache manager: ConcurrentMapCacheManager
max heap = 128 MB
keys=20,000  used heap=43 MB
keys=40,000  used heap=64 MB
keys=60,000  used heap=86 MB
keys=80,000  used heap=106 MB
keys=100,000  used heap=125 MB
output · simple manager, the end (B/growth-simple.out)runs offline
Caused by: java.lang.OutOfMemoryError: Java heap space
output · Caffeine, maximumSize=10000 (B/growth-caffeine.out)runs offline
cache manager: CaffeineCacheManager
max heap = 128 MB
keys=20,000  used heap=33 MB
keys=40,000  used heap=34 MB
keys=60,000  used heap=34 MB
keys=80,000  used heap=34 MB
keys=100,000  used heap=35 MB
keys=120,000  used heap=35 MB
keys=140,000  used heap=34 MB
keys=160,000  used heap=34 MB
keys=180,000  used heap=35 MB
keys=200,000  used heap=33 MB
finished 200,000 keys

What you see: The simple manager grew by about 21 MB per 20,000 keys and ended with OutOfMemoryError: Java heap space. Caffeine stayed between 33 and 35 MB for all 200,000 keys, because it holds at most 10,000 of them.

Why: A cache that never removes entries is a memory leak by design. The bound makes the cache a working set, not a log of everything seen. The TTL-in-provider idiom lists the settings.

Land it A cache with no bound and no expiry is a memory leak with a nice name, so I always use a real provider with a size limit and a TTL.

Likely follow-ups
"Why does Boot use the simple map if I did not choose anything?"

Because it needs some CacheManager for @EnableCaching to work, and the simple one has no dependencies. Boot tries the real providers first (Redis, Caffeine and others) if their libraries and settings are present, and falls back to ConcurrentMapCacheManager if none applies. The demo printed cache manager: ConcurrentMapCacheManager in that case.

That fallback is friendly for a first try and dangerous for production, because it works perfectly until the key set grows.

Make the choice visible: set spring.cache.type explicitly, and add a startup log or a test that asserts the manager class with isInstanceOf(CaffeineCacheManager.class).

Then a missing dependency breaks the build instead of quietly giving you the unbounded map.

"How can I tell whether it is the cache and not another leak?"

Look at the cache.size metric (question 32). If it rises steadily while traffic is level, the cache is the cause. If the cache size is flat, look elsewhere.

A heap dump confirms it. A cache leak shows up as one large ConcurrentHashMap (or a Caffeine node chain) retained by a ConcurrentMapCache object, with millions of small entries of your value type. I did not take a dump for the course, so treat this as the usual shape.

A quick experiment: set a small bound or disable the cache (spring.cache.type=none) in a test environment and watch whether memory stops growing.

Also check the values. Large objects (whole entity graphs, big lists) fill memory with far fewer entries. Cache small, immutable values.

"Is maximumSize enough, or do I also need a TTL?"

You need both, for different reasons. The size bound protects memory. The TTL protects correctness, because it limits how long a wrong value can live.

Size alone leaves a hot, stale entry in the cache forever, since a popular key is never evicted for lack of space. TTL alone leaves memory unbounded between expiries, so a burst of new keys can still fill the heap.

In the demo, the Caffeine run had a bound but no TTL, and that was enough to show stable memory. For real data add expireAfterWrite too.

I write them together in the spec: maximumSize=10000,expireAfterWrite=10m,recordStats, and I put the reason next to each number.

"What if my values vary a lot in size?"

Then a count bound is a poor guide: 10,000 small strings and 10,000 large documents use very different memory. Caffeine offers maximumWeight with a weigher, which charges each entry by its size, for example the length of a string or the number of items in a list.

You then set the total weight to a budget, say 50 MB worth. I did not run a weighted cache here.

The simpler approach is not to cache large values at all. Cache identifiers or small summaries, and fetch the large content on demand.

If you must cache big values, a remote cache such as Redis (with its own maxmemory) moves the pressure out of your JVM heap.

Q34. "When should you not cache at all?"

Reveal answer

Strong answer When the cache costs more than it saves, or when a stale answer is worse than a slow one. I run through five checks before I add @Cacheable.

SituationWhy caching hurtsDo this instead
The query is already fast (a primary-key read in 1 to 2 ms)The hit saves almost nothing, and you add keys, TTLs and bugsLeave it, or tune the query
Data is read once per key (per-user, per-request)Hit rate is near zero, memory fillsCache a shared, reused part only
The value must be exactly current (stock at checkout, account balance, payment status)A stale value causes a wrong actionRead the source of truth inside the transaction
The result depends on the caller (permissions, tenant) and the key does not include itOne user's data leaks to anotherInclude the user or tenant in the key, or do not cache
The value is huge or changes every few secondsMemory pressure, constant evictionCache a summary, or nothing

A way to decide with numbers: expected saving per call = hit ratio x (miss cost - hit cost). If a miss costs 5 ms, a hit 0.1 ms and the hit ratio is 10%, the saving is 0.1 x 4.9 = 0.49 ms per call, not worth the complexity. If a miss costs 180 ms and the ratio is 95%, the saving is 0.95 x 179 = 170 ms per call, which is clearly worth it.

Add a second test: what happens to users if the value is wrong for the whole TTL? If the answer is "money moves incorrectly", do not cache that value.

I also ask whether a cache is hiding a real problem. A slow query that can be fixed with an index should be fixed, and then the cache may be unnecessary.

Picture it A small table of the saving formula for four real cases from QuickBite. The numbers are hand-worked from the formula above, not measured, and the first row uses the measured 180 ms miss and 1 to 2 ms hit from the caching demos.

# illustrative · expected saving per callillustration
case                         miss    hit   ratio   saving/call
menu price (180 ms query)    180 ms  1 ms   95%    0.95 x 179 = 170 ms   -> cache
customer by id (2 ms read)     2 ms  1 ms   60%    0.60 x   1 = 0.6 ms   -> skip
cart contents (per user)      15 ms  1 ms    5%    0.05 x  14 = 0.7 ms   -> skip
stock at checkout             10 ms  1 ms   90%    fast, but may be wrong -> never

What you see: Only the first row pays. The second and third save under one millisecond per call, and the fourth is fast but can be wrong at the one moment where being wrong costs money.

Why: The value of a cache is the ratio times the difference between a miss and a hit, and the risk is what a wrong value costs. Both must be good. The decision table is the same one the primer's caching section ends with.

Land it I cache only data that is slow to fetch, read many times, and safe to be a little old, and I read the source of truth for money and stock.

Likely follow-ups
"What about caching to protect a database that is struggling?"

It can be the right emergency step, but I do it knowingly. A cache in front of an overloaded database can cut the read load by 10 to 100 times for hot keys, and that may save the system for the day. The risk is the stampede when the cache is cold (question 25) and the staleness you now have to explain.

Treat it as a stopgap and find the cause: a missing index, an N+1 query pattern, a connection pool that is too small, or a report running on the live database. Each of these is cheaper to fix than to hide.

If you do add the cache, bound it, give it a short TTL, add metrics, and put a note in the backlog to review it. "Temporary" caches that nobody owns tend to stay for years and surprise later teams.

Measure the database before and after. If the load did not drop, the keys or the hit ratio are wrong.

"Why is caching per-user data usually a bad idea?"

Because each user asks for their own keys, so the reuse is low, the hit ratio is small and memory grows with the number of users. A cache of 100,000 user carts each read twice has a poor ratio and a large footprint.

It also raises the leak risk. If the key does not include the user, another user can read the entry (question 16). If the key does include it, the cache is large.

There are good exceptions: expensive per-user results that are read many times in a short window, such as a recommendation list computed from a heavy query and used by every page in a session. Give it a short TTL tied to the session and a size bound.

Otherwise cache the shared parts (the menu, the restaurant details) and assemble the user's page from them.

"Is it fine to cache the result of a method that has side effects?"

No. A cached call does not run the method on a hit, so the side effect (a write, an email, a counter) happens only on a miss. A method that "gets the next order number" must never be cached. A method that sends a notification and returns a status must not be either.

Cache only pure reads: the same arguments give the same answer and the call changes nothing. The annotation looks harmless, but it changes behaviour for every hit.

If a read method also records statistics or an audit line, the hits no longer record them. That is the same effect as question 16 and surprises people reading the logs.

Split the method: a pure cached read, and a separate non-cached method for the side effect.

"How do I decide the TTL when I do decide to cache?"

I ask the owner of the data a plain question: "if this value is wrong, for how long can that be acceptable?" That answer is the upper limit of the TTL. Then I look at the load: a hot key read 100 times a second gains almost everything in the first few seconds, so a TTL of one to ten minutes is usually enough.

Hand-worked: at 100 reads per second, a 60-second TTL answers 6,000 reads with 1 database read, a 99.98% hit ratio. Going from 60 seconds to 10 minutes only adds 0.01 points more, but multiplies the possible staleness by ten.

So pick the shortest TTL that already gives a high ratio. It limits wrongness at a small cost.

Review the number after a month, using the hit ratio and the eviction metrics.

Q35 · Design. "Design caching for QuickBite's menu service: keys, TTLs, invalidation on price change and multi-instance consistency."

Reveal answer

Strong answer I start from what changes and how wrong each value may be, then choose the layers.

What is cached and for how long

DataKeyTTLReason
Item priceprice:{restaurantId}:{itemId}5 minutesChanges a few times a day. Reads are the hottest.
Item details (name, photo, description)item:{itemId}1 hourRarely changes
Restaurant menu listmenu:{restaurantId}10 minutesBuilt from many items. Evicted on any change.
Search resultsnot cachednoneToo many distinct keys

Layers. Caffeine inside each pod (fast, bounded: maximumSize=10000), with expireAfterWrite as the safety net. A shared Redis only if pods must agree faster than the TTL allows, or if cold starts are too heavy. I begin with Caffeine alone and add Redis pub/sub for eviction when stale prices become a complaint.

Invalidation. Price change: @CacheEvict for the item price and the restaurant menu in one @Caching, and a broadcast message so every pod evicts its local copy. The eviction runs after the commit because the cache interceptor is outside the transaction. The TTL covers any missed message.

Consistency rule. The menu page may show a price up to the TTL old. Checkout reads the price from the database inside the order transaction and stores it on the order line, so a customer never pays a price that was not current at the moment of purchase.

Protection and visibility. sync = true on the hot reads, TTL jitter on the menu list, recordStats plus Actuator for the hit ratio, and a test that proves a price change evicts.

The numbers behind it: a 180 ms query, 99% hits, and one load per pod per key every five minutes.

Picture it The pieces of the design, each with a measured result from the caching section: the key and TTL setting, the @Caching eviction, the broadcast, and the stampede protection.

MenuService.java (design sketch) · Boot 4.2runs offline
@Cacheable(value = "prices", sync = true,
           key = "#restaurantId + ':' + #itemId")
public int price(long restaurantId, long itemId) { ... }

@Caching(evict = {
  @CacheEvict(value = "prices",
              key = "#restaurantId + ':' + #itemId"),
  @CacheEvict(value = "menus", key = "#restaurantId")
})
@Transactional
public void changePrice(long restaurantId, long itemId, int cents) {
    ...   // write, then publish "evict" for the other pods
}
application.yml · Boot 4.2runs offline
spring:
  cache:
    type: caffeine
    cache-names: prices,menus,items
    caffeine:
      spec: maximumSize=10000,expireAfterWrite=5m,recordStats
management:
  endpoints:
    web:
      exposure:
        include: caches,metrics

Make the invisible visible: Three pods, a price change, and a broadcast eviction (the measured version of the invalidation step).

output · Boot 4.2 (B/pods.out)runs offline
cache manager: CaffeineCacheManager
all pods warm: pod-A=24900  pod-B=24900  pod-C=24900
-- price changes to 26900; the request hit pod-A, which evicts its own entry only
after change:  pod-A=26900  pod-B=24900  pod-C=24900
-- fix 1: broadcast the eviction (stand-in for Redis pub/sub)
after broadcast: pod-A=27900  pod-B=27900  pod-C=27900
output · stampede, sync = true (B/stampede.out)runs offline
cache manager: CaffeineCacheManager
sync=false 20 threads, same key, cold cache: db calls = 20, wall time = 221 ms
sync=true  20 threads, same key, cold cache: db calls = 1, wall time = 205 ms

What you see: Without a broadcast only the pod that took the update showed the new price. With the broadcast all three pods showed 27900. The stampede run shows one database call for 20 simultaneous misses with sync = true.

Why: Eviction gives speed, the TTL gives the guarantee, and the database read at checkout gives correctness where money moves. Each protects against the failure of the others. Compare evict on write, cache sync and TTL in the provider.

Land it I cache hot, tolerant data in Caffeine with a bounded size and a TTL, evict on write and broadcast to the other pods, and read the price from the database at checkout.

Likely follow-ups
"Why not put every price in Redis only, so there is one copy?"

It is a valid design and sometimes the right one. One shared copy means one eviction fixes every pod, with no broadcast, and a cold pod starts warm. The cost is a network call on every read (the measured hit in the demo was 43 ms with a first-time local container, so a real network is not free), another system to run and secure, and a service that now depends on Redis being up.

For the menu page, the read rate is high and a few minutes of staleness is fine, so the local cache's speed is worth more than a single copy. I would add Redis when the pods must agree immediately, or when rebuilding the cache after each deploy puts too much load on the database.

A two-level design takes the best of both, at the price of two layers to invalidate (question 26).

I would start simple, measure, and add a layer only when a measurement asks for it.

"What do you do when a restaurant uploads a whole new menu at once?"

Evict by group instead of per key. A bulk update calls a method with @CacheEvict(value = "menus", key = "#restaurantId") and @CacheEvict(value = "prices", allEntries = true) is too broad for a large system, so I prefer a versioned key: the key contains a menu version for that restaurant, price:{restaurantId}:v{version}:{itemId}, and the upload increments the version. Old entries simply stop being used and expire.

The version has to come from somewhere every pod can read cheaply, such as a small cached value that is itself evicted by broadcast, or a field on the restaurant row.

Do the upload in one transaction and bump the version at the end, so readers never see half of the new menu with the old version.

Test it with a concurrent read during the upload, and check that a reader sees either all old or all new prices.

"How do you prove in a test that the design works across pods?"

I build two or three application contexts (or two cache managers) in one test, warm them, change a price through one, and assert what the others return. The pods demo does the same thing inside one JVM: before the broadcast the other pods return the old price, after it they return the new one.

The test then covers the three promises: eviction works on the pod that wrote, the broadcast reaches the others, and the TTL ends staleness even if a message is dropped (simulate the drop by skipping the broadcast and advancing the clock).

For the checkout rule, a separate test places an order after a price change and asserts that the order line holds the database price, even when the cache still holds the old one.

The measured pods output is the manual version of these assertions.

"Which numbers would you watch after the launch?"

Four. The hit ratio per cache from cache.gets. The size and evictions to see whether the bound is right. The database read rate for the price table, which should be a small fraction of the request rate. And the age of stale complaints: how many support tickets mention a wrong price, and for how long they lasted.

If the hit ratio falls, I look for a changed key or a TTL that became shorter. If evictions rise with a falling ratio, the bound is too small. If the database load is high with a good ratio, I look at stampedes at expiry.

Set alerts on a drop in the ratio together with a rise in database load, and review the TTL after a month.

These four numbers tell me whether the design works without reading any code.

13 · DrillAsync, Resilience, Scheduling, Events, Security and Validation — Q36–Q65

This block moves from the proxy you now know to the work that leaves the calling thread, and to what happens when that work fails, repeats or runs on every pod. The first ten questions are about @Async: which thread runs the work, what is lost on the way, and what must never be left to it. The next five open the retry and concurrency questions.

Each answer links to the primer: section 05 for @Async, section 06 for retries, limits and circuit breakers, and section 07 for scheduling, events, method security and validation. E4 has the first look at @Async in its data drill, and this drill goes further.

Outputs come from real runs on Spring Boot 4.2.0 and Java 25. The async programs are in code/e22-spring-in-depth/B/, the retry and breaker programs in C/, and the extra ones for this drill in F/. Questions 36 to 50 are in this part, and questions 51 to 65 follow.

Drill · @Async

These ten questions test whether you know which thread runs the work, how the default pool is sized, and what the caller gives up when it hands a call to another thread.

Q36. "How does @Async work under the hood, and what does @EnableAsync add?"

Reveal answer

Strong answer @Async is one more proxy advisor, with a twist: instead of running your method around some extra code, it moves the whole call to another thread.

@EnableAsync registers a bean post-processor. When a bean has a method marked @Async, the post-processor adds an AsyncAnnotationAdvisor to its proxy, and that advisor holds an AnnotationAsyncExecutionInterceptor. Spring Boot does not switch it on for you. You add @EnableAsync yourself. Without it the annotation is ignored and the method runs on the caller's thread.

What happens on a call:

  1. The caller calls the method on the proxy.:
  2. The async interceptor wraps the rest of the chain and the method into a task (a Callable).:
  3. It finds an executor: the one named in @Async("name"), else a TaskExecutor bean (Boot's applicationTaskExecutor), else a simple one that starts a new thread per call.
  4. It submits the task and returns at once: null for void, or a Future/CompletableFuture for the callers that want the result.
  5. A worker thread later runs the task: the remaining advisors (transaction, aspects) and then your method.

Its order is Integer.MIN_VALUE, so it is outermost on its bean. That is why @Async @Transactional starts the transaction on the worker thread (question 42).

Everything that holds for proxies holds here: only calls from another bean are async, and a same-class call runs on the caller's thread.

What is left behind on the caller's thread: its ThreadLocal values (the security context, the MDC), its transaction, and any exception from the method.

Picture it The same method called as a plain method and as an @Async one, with a simulated 2-second email send, then the advisor chain of an @Async @Transactional bean.

Synchronous

The caller waits for the whole send.

MailService.java · Boot 4.2runs offline
public void sendSync(String to) {
    sleep(2000);          // the SMTP call
}

With @Async

The proxy hands the call to an executor.

MailService.java · Boot 4.2runs offline
@Async
public void sendAsync(String to) {
    sleep(2000);          // runs on task-1
}

The shift: The caller's checkout path no longer contains the two seconds.

Make the invisible visible: Time a checkout that sends one email each way.

output · Boot 4.2 (B/sync-vs-async.out)runs offline
caller thread = [main]
  email to asha@example.com sent on [main]
checkout with sendSync : 2001 ms
checkout with sendAsync: 3 ms
  email to asha@example.com sent on [task-1]

Make the invisible visible: And the chain printed from an @Async @Transactional bean.

output · Boot 4.2 (A/stacked.out)runs offline
advisor chain of NotificationService (@Async @Transactional):
  1. order=-2147483648 AsyncAnnotationAdvisor / AnnotationAsyncExecutionInterceptor
  2. order=2147483647  BeanFactoryTransactionAttributeSourceAdvisor / TransactionInterceptor

What you see: Checkout with the synchronous send took 2,001 ms. With @Async it took 3 ms, and the email was sent a moment later on thread task-1. In the chain, the async interceptor comes first, with the order -2147483648, and the transaction interceptor second.

Why: The interceptor returned to the caller as soon as the task was queued. See section 05 and Fig. 22.8 for the picture of the caller and the worker.

Land it I describe @Async as a proxy that wraps the whole call into a task and hands it to an executor, and I remember it must be enabled with @EnableAsync.

Likely follow-ups
"Why does @Async do nothing in my application?"

Four causes cover almost every case. @EnableAsync is missing, so the annotation is never read. The call is from the same class, so the proxy is skipped (question 8). The method is not public, or the class is not a Spring bean. Or the bean is not a proxy for another reason (final class, created with new).

The quick proof is the thread name. Print Thread.currentThread().getName() inside the method. On main or a http-nio thread, it did not go async. On task-1, it did.

The demo's same-class call printed main and blocked for 300 ms, while the call from another bean ran on task-1 and returned after 4 ms (question 8).

Check these four in order, and you will find the reason within a minute.

"Which return types does @Async allow?"

void, Future<T> and CompletableFuture<T> (and Spring's ListenableFuture in older code). Any other return type is not allowed for an async method, because the caller gets its value immediately, before the work has run.

With void, the caller learns nothing: no result and no exception (question 39). With CompletableFuture, the proxy returns a future at once, and your method returns CompletableFuture.completedFuture(value) when it has the value. The caller can then wait, chain, or handle errors.

Choose CompletableFuture whenever someone needs the outcome, and void only for work where nobody will ever ask (and give it an exception handler, question 40).

Do not block on the future inside the same thread pool that runs it. If all pool threads wait for tasks that cannot start, the application deadlocks.

"How is @Async different from calling new Thread(...) or an ExecutorService myself?"

The result is the same: work on another thread. The difference is where the code lives and what you get for free. @Async keeps the threading out of your business method, uses a pool that Spring manages and shuts down with the application, and joins the advisor chain, so a @Transactional on the same method works on the worker.

Hand-written executors give you full control and no hidden rules, but you must manage the lifecycle (shutdown, naming, rejection) and the propagation of context yourself. Many production problems with new Thread() come from missing shutdown handling.

I use @Async for simple fire-and-forget work and for methods that return a CompletableFuture. I use an explicit executor, or a different tool altogether, when I need more control: several steps, joins, timeouts or a bounded queue (question 45).

The primer section 05 ends with a table that compares the tools.

"Can an @Async method call another @Async method?"

Yes, if the call goes through a proxy (another bean). The second method is then submitted as a new task, to the same or another executor, and the first method does not wait for it unless you join the future.

A call inside the same class is a plain method call, so the second method simply runs on the first one's thread, as if it were not annotated.

The risk is a deadlock on a small pool. If an async method submits another task to the same bounded pool and then waits for its result, and every pool thread is doing the same, nobody is left to run the inner tasks. Use separate executors for the outer and inner work, or avoid waiting inside async code.

Keep chains short, and prefer one async entry point that does its steps in order.

Q37. "Which executor runs @Async methods in Spring Boot by default, and how is it sized?"

Reveal answer

Strong answer Boot defines a bean called applicationTaskExecutor, a ThreadPoolTaskExecutor. @Async uses it when you do not name another. I printed its real settings on Boot 4.2:

SettingDefaultProperty
Core pool size8spring.task.execution.pool.core-size
Max pool sizeInteger.MAX_VALUEspring.task.execution.pool.max-size
Queue capacityInteger.MAX_VALUE (unbounded)spring.task.execution.pool.queue-capacity
Keep-alive60 secondsspring.task.execution.pool.keep-alive
Core threads time outtruespring.task.execution.pool.allow-core-thread-timeout
Thread name prefixtask-spring.task.execution.thread-name-prefix

The combination has a famous effect. A ThreadPoolExecutor creates threads beyond the core size only when the queue is full. The queue is unbounded, so it is never full, and the pool never grows past 8 threads. The big max size is never used.

Two consequences: at most 8 tasks run at the same time, and when tasks arrive faster than they finish, the queue grows without limit. Memory rises and the waiting time for each task grows with it, and nothing rejects work.

So for any serious use, set explicit sizes and a bounded queue, or create named executors for different workloads (question 45). If you define your own Executor bean, Boot backs off applicationTaskExecutor (the demo printed [mailExecutor, reportExecutor]).

With spring.threads.virtual.enabled=true the default becomes a virtual-thread executor and the pool settings no longer apply (question 43).

Picture it Boot's default executor printed from a running application, then the same application with virtual threads on.

Make the invisible visible: Print the executor beans and the settings of applicationTaskExecutor, then start one task.

output · Boot 4.2 (B/defaults.out)runs offline
Executor beans: [applicationTaskExecutor]
applicationTaskExecutor is a org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
  corePoolSize         = 8
  maxPoolSize          = 2147483647
  queueCapacity        = 2147483647
  keepAliveSeconds     = 60
  allowCoreThreadTimeOut = true
  threadNamePrefix     = task-
runner finished at 00:45:41
  task 1 started on [task-1]
  task 1 FINISHED

Make the invisible visible: Same application with spring.threads.virtual.enabled=true.

output · Boot 4.2 (B/virtual.out)runs offline
applicationTaskExecutor is a org.springframework.core.task.SimpleAsyncTaskExecutor
  task 2 started on [task-2] virtual=true
  task 1 started on [task-1] virtual=true
  task 1 FINISHED
  task 2 FINISHED

What you see: Core size 8, max and queue both 2,147,483,647, keep-alive 60 seconds, core threads allowed to time out, thread names starting with task-. With virtual threads the executor is a SimpleAsyncTaskExecutor and the task ran on a virtual thread.

Why: The unbounded queue means the pool stays at 8 threads and never rejects. That is safe for memory only while tasks are short. See section 05 and the named-executor idiom.

Land it The default is a pool of 8 threads with an unbounded queue, so I set explicit sizes and a bounded queue, or I use named executors for important work.

Likely follow-ups
"What does it mean that the queue is unbounded, and when does it bite?"

It means a waiting task always has a place in the queue, so the executor never says "no". That sounds friendly and hides overload. If 8 workers need 2 seconds per task and tasks arrive at 10 per second, work comes in at 10 and leaves at 4 per second. The queue grows by 6 tasks per second: after one minute there are 360 waiting tasks, and a new task waits about 90 seconds before it starts.

Hand-worked: 8 workers / 2 s = 4 tasks per second out; 10 in; the difference is 6 per second, 360 per minute; waiting time = 360 / 4 = 90 seconds.

The queue also holds the tasks and their arguments in memory. A long overload can end in an OutOfMemoryError.

A bounded queue turns that silent growth into a visible TaskRejectedException, which you can count, alert on and handle with a rejection policy (question 45).

"How do I size the pool?"

From the kind of work. For CPU-bound tasks, use about the number of cores. For tasks that wait (HTTP calls, SMTP, disk), threads sit idle most of the time, so more threads than cores make sense: the number needed is roughly the arrival rate times the average time per task (Little's law).

Example: 20 emails per second, each taking 2 seconds of waiting, needs about 20 x 2 = 40 threads to keep up. With 8 threads, only 4 emails per second get out.

Then bound the queue to what you can tolerate waiting, and decide what happens beyond it: reject, run in the caller (CallerRunsPolicy, which slows the producer down), or drop.

Check with metrics: Boot publishes executor.active, executor.queued and executor.pool.size for its executors when Micrometer is on. I did not capture them in these demos, so confirm the names on your version.

"Is applicationTaskExecutor also used by Spring MVC or @Scheduled?"

Spring Boot uses it for @Async and for async request handling in Spring MVC (callable and deferred results), so a busy @Async workload can also delay those. That is a good reason to give heavy background work its own executor.

@Scheduled uses a separate scheduler, taskScheduler, with its own settings under spring.task.scheduling.*, and by default a single thread (question 55).

In the demo project, defining my own executor beans removed applicationTaskExecutor from the context, as the printed bean list showed. If something else needed it, that change would be a surprise, so name executors explicitly in @Async("...").

When unsure, list the executor beans at startup (context.getBeansOfType(Executor.class)) and read them.

"How do I see how busy the executor is at run time?"

Through Micrometer metrics if Actuator is present: Boot binds Spring's task executors to the registry, giving meters such as executor.active, executor.queued, executor.pool.size and executor.completed, tagged by the executor name. I did not collect these here, so look them up on your version.

Without metrics you can read the pool directly: ThreadPoolTaskExecutor.getActiveCount(), getPoolSize() and getThreadPoolExecutor().getQueue().size() print the same numbers.

A rising queue with all threads active is the signal that the pool is too small or the downstream is slow.

Alert on queue length and on rejected tasks, not on CPU. An async pool in trouble usually looks idle on CPU while it waits for a slow dependency.

Q38 · Scenario. "After the app finishes its work, it stays alive for 60 seconds. Why?"

Reveal answer

Strong answer The worker threads of the default executor are still alive, and the JVM does not exit while a non-daemon thread lives. Boot's applicationTaskExecutor has allowCoreThreadTimeOut = true and a keep-alive of 60 seconds. After the last task, each idle worker waits up to 60 seconds before it ends, and only when the last one ends can the JVM exit.

It affects short-lived programs: a command-line runner, a batch job, a demo, a test run. A web server stays up anyway, so there it does not show.

The measured numbers: a run with the defaults took 66.98 seconds in total, about 7 seconds of which was start-up. With spring.task.execution.pool.keep-alive=5s it took 9.9 seconds, and with 2s it took 8.43 seconds.

Options:

  • End deliberately: System.exit(SpringApplication.exit(ctx)) closes the context and stops the pool.
  • Shorten the idle time: spring.task.execution.pool.keep-alive=2s.
  • Close the context when the work is done, instead of waiting for the JVM.
  • Make the threads daemon threads, if losing in-flight tasks is acceptable.

Do not "fix" it by killing the process. That throws away tasks that are still running (question 44).

Picture it The same one-task program timed three times: with the defaults, with a 5-second keep-alive and with a 2-second keep-alive.

run · Boot 4.2runs offline
$ java -Xmx256m -jar async-demo.jar --demo=defaults --linger
$ ... --spring.task.execution.pool.keep-alive=5s
$ ... --spring.task.execution.pool.keep-alive=2s

Make the invisible visible: The wall time of each run.

output · Boot 4.2 (B/linger.out)runs offline
$ time java -Xmx256m -jar async-demo.jar --demo=defaults --linger
runner finished at 00:46:08; main returns, JVM stays
JVM wall time: 66.98 s

$ ... --spring.task.execution.pool.keep-alive=5s
JVM wall time: 9.90 s

$ ... --spring.task.execution.pool.keep-alive=2s
JVM wall time: 8.43 s

What you see: The runner finished early, but the process stayed alive: 66.98 s with the defaults, 9.90 s with a 5-second keep-alive and 8.43 s with 2 seconds. The ending time moves with the keep-alive setting.

Why: Idle core threads of the pool time out after the keep-alive, and the JVM waits for non-daemon threads. The setting is in the table of question 37. See section 05 for the measured linger.

Land it The JVM waits for the executor's idle non-daemon threads to time out after 60 seconds, so I close the context explicitly or shorten the keep-alive.

Likely follow-ups
"Is this a problem in a web application?"

No. A web application is supposed to stay alive until it is stopped, so the idle threads do not change when it exits. The 60 seconds matter at shutdown only in the sense that the executor is shut down with the context (question 44 and the demo of await-termination).

It matters for anything that should exit by itself: a scheduled Kubernetes Job, a CLI tool built with Spring Boot, an integration test that starts a context and a JVM-level timeout in CI.

A one-minute delay per run sounds small, but a pipeline with 40 such tests loses 40 minutes. The fix is one property.

In a container, a slow exit can also upset the orchestrator: a Job stays "running" for another minute and a liveness check may restart it.

"Should I make the executor's threads daemon threads?"

Only if you accept that the JVM may exit while tasks are still running. A daemon thread does not keep the JVM alive, so at the end of main the process stops and unfinished tasks are cut off. That removes the linger, and it also removes the safety net.

For work that must finish (sending an invoice, writing an audit row), non-daemon threads plus a proper shutdown are safer: the context waits for running tasks if spring.task.execution.shutdown.await-termination=true is set (question 44).

For best-effort work (a cache warm-up, a metrics push), daemon threads are fine.

Most of the time I leave the threads as they are, shorten the keep-alive for tools, and call SpringApplication.exit at the end of a runner.

"What does SpringApplication.exit do that System.exit does not?"

SpringApplication.exit(ctx) closes the Spring context first, in order: it stops lifecycle beans, shuts down executors, closes connection pools, and publishes the shutdown events. It then returns an exit code (computed from any ExitCodeGenerator beans). You pass that code to System.exit.

Plain System.exit(0) ends the JVM immediately, and Spring only gets its shutdown hook, which runs on a separate thread under time pressure. Context close is still attempted, but the order and the exit code are less controlled.

The demos in this chapter end with System.exit(SpringApplication.exit(ctx)), so they do not linger and the process returns the right code.

For a command-line job that must report failure to a scheduler, the exit code matters: use an exception or an ExitCodeGenerator so that the job ends with a non-zero code.

"How is this different from a thread leak?"

A leak is threads that stay forever and pile up. This linger is bounded: each idle core thread ends after its keep-alive, because allowCoreThreadTimeOut is on. The measured runs ended at 67 seconds, not never.

A real leak looks different: the thread count keeps growing with every call, for example when code creates a new executor per request and never shuts it down. A thread dump shows hundreds of pool-N-thread-1 threads.

To tell them apart, take two thread dumps a minute apart (jcmd <pid> Thread.print) or watch jvm.threads.live. Constant means linger, growing means leak.

The cure for a leak is to create one executor per purpose at start-up as a bean, so Spring owns it and shuts it down.

Q39. "void versus CompletableFuture return types for @Async — what changes for results and errors?"

Reveal answer

Strong answer With void the caller gets nothing back: no result, no way to wait, and no exception. With CompletableFuture<T> the proxy hands the caller a future immediately, and the future is completed later by the worker, with the value or with the failure.

AspectvoidCompletableFuture<T>
Result to the callerNonefuture.get(), join(), or chain with thenApply
Exception from the methodGoes to the AsyncUncaughtExceptionHandler (default: logged at ERROR). The caller never knowsStored in the future: join() throws CompletionException, isCompletedExceptionally() is true
Waiting for completionImpossiblejoin(), allOf(...), orTimeout(...)
Right forFire-and-forget work nobody checksAnything whose outcome somebody needs

Your method returns CompletableFuture.completedFuture(value) or failedFuture(ex). A plain exception thrown from the method also ends up in the future. The caller's future is a different object from the one your method returned: Spring completes it from the task's outcome.

Rules I follow:

  • Use CompletableFuture when anybody cares whether it worked.
  • Always give a void async method an exception handler (question 40).
  • Never call join() on the web thread without a timeout. That makes the async call synchronous again, and a slow worker holds a request thread.
  • Do not wait inside the same bounded pool that runs the tasks.

Picture it One failing void method and one failing CompletableFuture method, both throwing "SMTP 550 mailbox full", and then a future that works.

void

Nothing returns to the caller. Boot logs the failure.

MailService.java · Boot 4.2runs offline
@Async
public void sendFailing(String to) {
    throw new IllegalStateException(
        "SMTP 550 mailbox full for " + to);
}

CompletableFuture

The failure is stored in the future.

MailService.java · Boot 4.2runs offline
@Async
public CompletableFuture<String> sendFuture(
        String to, boolean fail) {
    if (fail) throw new IllegalStateException(...);
    return completedFuture("sent to " + to);
}

The shift: The same failure is a log line the caller cannot see in the first case and a value the caller can ask for in the second.

Make the invisible visible: Call each and read what the caller and the logs show.

output · void (B/types.out)runs offline
-- void method that throws (default handler):
2026-12-02T00:48:06.024+05:30 ERROR 1791031 --- [async-demo] [         task-1] .a.i.SimpleAsyncUncaughtExcepti

java.lang.IllegalStateException: SMTP 550 mailbox full for asha@example.com
output · CompletableFuture (B/types.out)runs offline
-- CompletableFuture method that throws:
  join() threw CompletionException caused by java.lang.IllegalStateException: SMTP 550 mailbox full for asha@e
  isCompletedExceptionally = true
-- CompletableFuture method that works:
  sent to asha@example.com on [task-3]

What you see: The void failure appeared only as an ERROR log from SimpleAsyncUncaughtExceptionHandler with a stack trace on thread task-1. The future version let the caller see CompletionException caused by the same exception on join(), and isCompletedExceptionally = true. The healthy call ran on task-3.

Why: The caller's thread has already moved on when the method fails, so the only way to carry a failure back is through the future. See section 05 for both return types.

Land it I return a CompletableFuture whenever someone needs the outcome, and I give every void async method an exception handler.

Likely follow-ups
"What exactly does join() throw and how do I get the real cause?"

join() throws an unchecked CompletionException that wraps the original exception. get() throws a checked ExecutionException that wraps it too. The real cause is e.getCause().

In the demo the message read "CompletionException caused by java.lang.IllegalStateException: SMTP 550 mailbox full". The wrapper is only a carrier, so handlers should unwrap it before deciding what to do.

A more comfortable style is to avoid join() and use the chaining methods: future.exceptionally(ex -> fallback) or future.handle((value, ex) -> ...). Their ex argument is also wrapped in a CompletionException in some cases, so check ex.getCause().

Add a timeout with orTimeout(2, TimeUnit.SECONDS) so a stuck worker cannot hold the caller forever.

"Can I use @Async with a return type like String and just get the value later?"

No. Spring supports void, Future and its subtypes (such as CompletableFuture). For any other return type the caller would have to receive a value right away, before the worker has computed it. The proxy returns null for such a method, and the real result is thrown away.

That makes a wrong return type a quiet bug: the caller sees null, the method runs on another thread, and nothing complains.

If you want a simple result, return CompletableFuture<String>. If you need many results, return a list of futures and combine them with CompletableFuture.allOf.

In code review I look for @Async on a method with a non-future return type, and I ask for either a future or void.

"How do I run several async calls and wait for all of them?"

Start them all first, then wait once. Calling join() after each start makes them run one after another, which defeats the purpose.

Fan-out · Boot 4.2runs offline
var a = mail.sendFuture("asha@example.com", false);
var b = mail.sendFuture("ravi@example.com", false);
var c = mail.sendFuture("meena@example.com", false);
CompletableFuture.allOf(a, b, c)
        .orTimeout(5, TimeUnit.SECONDS)
        .join();      // total time is the slowest, not the sum

If you need the values, read them from a, b and c after allOf. If one fails, allOf completes exceptionally, but the others are not cancelled and keep running.

Check the pool size: three tasks in parallel need three free threads. With the default pool of 8 and a busy queue, they may wait.

This is a sketch and I did not run this exact fan-out. The single-call versions above were run.

"Does @Async on a method returning CompletableFuture change the exception handler?"

The AsyncUncaughtExceptionHandler is only used for void methods. For a future-returning method, the exception goes into the future and the handler is not called, because the caller can see it there.

This means a future that nobody reads hides its failure. If the caller starts a future and never calls join(), get() or exceptionally, no log line appears at all. That is quieter than the void case, where Boot's default handler at least logs.

So for fire-and-forget work, void with a handler is safer than a future that nobody checks. If you do return a future from such a method, attach whenComplete that logs failures.

I did not run the unread-future case, but it follows from how the handler is chosen. Test it by throwing in a future-returning async method and looking at the console.

Q40 · Scenario. "An exception in a void @Async method disappears. How do you see it?"

Reveal answer

Strong answer It does not disappear completely. Boot's default handler, SimpleAsyncUncaughtExceptionHandler, logs it at ERROR with a stack trace on the worker thread, as the demo showed. But the caller never learns of it, no counter moves and no alert fires. Unless somebody reads that log line, the failure is invisible. That is the real problem.

The fix is to give failures a place to go. Implement AsyncConfigurer and return your own AsyncUncaughtExceptionHandler. It receives the exception, the method and the arguments. Log with context, count the failure in a metric, and alert from the metric.

ExecutorsConfig.java · Boot 4.2runs offline
@Configuration
static class Handler implements AsyncConfigurer {
    @Override
    public AsyncUncaughtExceptionHandler
            getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> log.error(
            "async {} failed for {}", method.getName(),
            Arrays.toString(params), ex);
    }
}

Better options for work that matters:

  • Return a CompletableFuture and attach whenComplete, so failures are handled where the work is started.
  • Catch inside the method, record the failure (a database row, a metric) and retry or alert from there.
  • Use a durable queue, so failed work is kept and retried (question 44).

Whatever you choose, test it: throw on purpose in a test and assert that the handler or the metric saw it.

Picture it The failing method, first with Boot's default handler (the log line with a stack trace) and then with the custom handler.

Default handler

Logs at ERROR with a stack trace. Nobody is told.

excerpt, wrapped to fit · Boot 4.2runs offline
ERROR ... SimpleAsyncUncaught
  ExceptionHandler : Unexpected
  exception occurred invoking
  async method: ... sendFailing

Custom handler

Your code runs with the method and its arguments.

ExecutorsConfig.java · Boot 4.2runs offline
return (ex, method, params) ->
    println("HANDLER caught "
      + ex.getClass().getSimpleName()
      + ": " + ex.getMessage()
      + " in " + method.getName());

The shift: The failure now reaches code you control, which can count it and alert.

Make the invisible visible: The default handler, then the custom one.

output · default (B/types.out)runs offline
-- void method that throws (default handler):
2026-12-02T00:48:06.024+05:30 ERROR 1791031 --- [async-demo] [         task-1] .a.i.SimpleAsyncUncaughtExcepti

java.lang.IllegalStateException: SMTP 550 mailbox full for asha@example.com
output · custom handler (B/handler.out)runs offline
  HANDLER caught IllegalStateException: SMTP 550 mailbox full for asha@example.com  in sendFailing(asha@exampl

What you see: The default output is a long ERROR log with the message "Unexpected exception occurred invoking async method". The custom handler printed one clear line with the exception type, the message, the method name and the argument (asha@example.com).

Why: The proxy calls the handler on the worker thread when the method throws. The handler is the only code that sees the failure. The async exception handler idiom in section 05 has the full version.

Land it A void async failure is only a log line unless I register an AsyncUncaughtExceptionHandler that counts and alerts, or I return a future that someone checks.

Likely follow-ups
"Why did nobody notice the failures for weeks?"

Because the failure is logged at the worker thread with no link to the request, and because nothing counts it. In a busy system with other ERROR lines, an extra stack trace is easy to ignore, and a log alert on "any ERROR" often does not exist.

Another reason is the log level or the log pipeline: if the application filters org.springframework.aop.interceptor or only ships WARN and above from a sampled stream, the line may never reach the search tool.

The custom handler fixes both: it adds context (the arguments, an identifier of the request) and increments a metric such as async.failures tagged with the method name. An alert on that metric rising is the real safety net.

I also add a test that makes the method fail and checks the metric moved, so the handler cannot silently break.

"Does the handler run on the caller's thread?"

No, on the worker thread, right after the method threw. The caller's thread has long moved on.

That has a consequence for what the handler can see. The caller's ThreadLocal values (the user, the MDC, the request id) are not there unless you propagated them (question 41). A log line from the handler without a request id is hard to connect to the request that caused it.

Put what you need into the arguments of the async method (an order id, a correlation id), since the handler receives the argument array. Then the failure carries its own identification.

Keep the handler fast and safe: an exception thrown inside it is itself lost, so wrap risky work in try/catch.

"Should the handler retry the work?"

Rarely. The handler sees the exception and the arguments, so a retry is technically possible, but it runs in a place without limits, delays or knowledge of whether the call is safe to repeat. A handler that blindly retries can resend an email or a payment (question 48).

A better place for a retry is the method itself with @Retryable and a bounded policy (the resilience section), or a queue with redelivery. Both give you counts, delays and a dead-letter at the end.

The handler's job is to observe: log, count, alert, and perhaps write the failed work to a table for a person or a job to look at.

If a failure must never be lost, the handler is the wrong tool. A durable queue (question 44) is the right one.

"What about exceptions in @Scheduled methods or event listeners?"

They have their own handlers. A @Scheduled method that throws is logged by the scheduler's error handler, and the schedule continues. An @EventListener that throws propagates to the publisher when it is synchronous, and it goes to the async handler if the listener is also @Async.

The pattern is the same everywhere: find out which component receives the failure, and make sure it logs with context and counts it. @Async is just the most common place to lose one.

I list the "failure sinks" of a service in the README: the async handler, the scheduler error handler, the message listener error handler and the web @ControllerAdvice. A new developer then knows where an exception can end up.

The scheduling and event questions later in this drill cover the other two.

Q41 · Scenario. "The SecurityContext and the MDC request id are missing inside an @Async method. Fix it."

Reveal answer

Strong answer Both live in a ThreadLocal, and a ThreadLocal belongs to one thread. The caller's thread has the logged-in user (SecurityContextHolder) and the request id (the MDC, Logback's per-thread map). The @Async method runs on task-1, a different thread, whose ThreadLocals are empty. So the user shows as anonymous, and the request id is null.

The fix is to copy the context onto the worker when the task is created, and clear it afterwards. Spring has the hook for it: a TaskDecorator, a function that wraps every task. It runs on the caller's thread (where the context is) when the task is submitted, captures what you want, and returns a wrapped task that sets it on the worker before it runs and clears it after.

  1. Capture: read the MDC map and the authentication on the caller's thread.
  2. Wrap: return a Runnable that sets both on the worker.
  3. Clean: in finally, clear the MDC and the security context, so the next task on that thread does not inherit them.

In Boot 4.2 a TaskDecorator bean is applied to the auto-configured executor automatically (verified here). For your own executors, call setTaskDecorator(...).

For security, Spring Security has wrapper executors that copy the security context. In the Security 7.2 jar used here, DelegatingSecurityContextAsyncTaskExecutor was not available, and DelegatingSecurityContextSchedulingTaskExecutor copied the user but not the MDC. A decorator that copies both is the simplest.

Do the same for any other ThreadLocal you rely on (tenant, locale, trace context).

Picture it The same @Async method called from a thread with the user alice and the request id req-42, three times: broken, with the decorator, and with the security wrapper only.

Broken

No propagation. The worker's ThreadLocals are empty.

excerpt, wrapped to fit · Boot 4.2runs offline
caller [main] user=alice
  requestId=req-42
  async [task-1] user=anonymous
  requestId=null

With a TaskDecorator

The decorator copies the MDC and the user.

ExecutorsConfig.java · Boot 4.2runs offline
@Bean TaskDecorator contextDecorator() {
  return task -> {
    var mdc = MDC.getCopyOfContextMap();
    var auth = SecurityContextHolder
        .getContext().getAuthentication();
    return () -> { /* set, run, clear */ };
  };
}

The shift: The decorator runs on the caller's thread when the task is created, so it can still see the context.

The decorator in full · Boot 4.2runs offline
return task -> {
    Map<String, String> mdc = MDC.getCopyOfContextMap();
    SecurityContext copy = SecurityContextHolder.createEmptyContext();
    copy.setAuthentication(
        SecurityContextHolder.getContext().getAuthentication());
    return () -> {
        try {
            if (mdc != null) MDC.setContextMap(mdc);
            SecurityContextHolder.setContext(copy);
            task.run();
        } finally {
            MDC.clear();
            SecurityContextHolder.clearContext();
        }
    };
};

Make the invisible visible: Run the method broken, with the decorator, and with the Spring Security wrapper only.

output · broken (B/context-broken.out)runs offline
caller [main] user=alice  requestId=req-42
  async  [task-1] user=anonymous  requestId=null
output · with the decorator (B/context-decorator.out)runs offline
caller [main] user=alice  requestId=req-42
  async  [task-1] user=alice  requestId=req-42
output · security wrapper only (B/context-secure.out)runs offline
caller [main] user=alice  requestId=req-42
  async  [secure-1] user=alice  requestId=null

What you see: Broken: the caller saw alice and req-42, the worker saw anonymous and null. With the decorator both arrived. With the security wrapper alone the user arrived (alice) but the request id did not (null).

Why: Each wrapper copies only what it knows about, so the MDC needs its own copy. Always clean up in finally, because pool threads are reused. See the task-decorator idiom in section 05.

Land it ThreadLocals do not cross threads, so I copy the user and the MDC with a TaskDecorator and clear them in a finally block.

Likely follow-ups
"Why must the decorator clear the context afterwards?"

Because pool threads are reused. If the decorator sets the user alice on task-1 and does not clear it, the next task that runs on task-1 starts with alice still set, even if it was submitted by bob or by a background job with no user. That is a security bug: work runs with the wrong identity.

The finally block in the decorator guarantees the clean-up even when the task throws. The demo's decorator clears both the MDC and the security context there.

The same applies to the MDC: stale request ids in log lines of unrelated work are confusing in an incident, because a log search for one request id returns lines from another request's leftover.

A test: run two tasks one after the other on a single-thread executor, the first with a user and the second without, and assert that the second sees no user.

"Is there a simpler way for the security context only?"

Spring Security can propagate it with a wrapper executor, as the third run showed: DelegatingSecurityContextSchedulingTaskExecutor wraps your pool and copies the user to each task. With Security 7.2 on this machine the older DelegatingSecurityContextAsyncTaskExecutor name was not present, so check what your version offers.

Another option is the SecurityContextHolder strategy MODE_INHERITABLETHREADLOCAL, which makes child threads inherit the context. It is not suitable for pools, because pool threads are created once and later tasks would inherit the context of whoever started the thread.

I prefer the decorator because it also handles the MDC and other ThreadLocals in one place. The wrapper is fine if only the user matters.

Whatever you pick, prove it with a test that calls the async method as a known user and asserts what the worker saw.

"What about a @Async method that must run with its own system identity, not the caller's?"

Then do not propagate the user. Run the work as a system principal that you set explicitly inside the async method (or in a decorator for that executor): for example system:mail-sender. An audit row then shows who really acted.

A background job should not inherit a user's permissions just because a user triggered it. The user asked for an email to be sent, but the sending step is the system's act.

A clean design passes the facts in arguments: the order id and the user id as data, and the worker uses the system identity to do the work. The audit line then records "sent by system, on behalf of asha".

If the work needs the user's own permissions (it reads data the user can see), propagate the security context and keep its lifetime short.

"How do I get a trace id into the async work if I use tracing?"

Micrometer Tracing keeps its current span in a ThreadLocal-like context as well, so it is lost on the worker in the same way. The supported fix is a context-propagating wrapper around the executor, and Spring Boot's observation support provides one: with the Micrometer context-propagation library on the classpath, Boot can register a task decorator that carries the observation and trace context to the worker.

I did not run tracing for this answer, so check the Boot documentation for your version for the exact property or bean.

Without it, copy the trace and span ids into the MDC in your own decorator, as the demo does with the request id, so at least the log lines carry them.

Test by logging inside the async method and checking that the line has the same trace id as the request that started it.

Q42. "How do @Async and @Transactional interact?"

Reveal answer

Strong answer They do not share anything. The async interceptor is outermost, so the call moves to a worker thread first, and the transaction (if the method has one) starts on the worker. A transaction belongs to a thread, so the caller's transaction does not follow the call.

Three consequences:

  1. The worker has its own transaction. The caller's open transaction and the worker's are different, with different connections.:
  2. The worker may run before the caller commits. It then cannot see the caller's new rows. In the demo the worker started inside the caller's open transaction and its read of the new order returned "sees order? false".:
  3. Entities do not travel. A JPA entity loaded in the caller's session is detached on the worker, and touching a lazy collection fails with LazyInitializationException.:

The rules that follow:

  • Pass identifiers, not entities. The worker loads what it needs in its own transaction.
  • Start async work after the caller commits: publish an event and listen with @TransactionalEventListener(phase = AFTER_COMMIT) plus @Async, so the worker only starts once the data is visible (see section 07).
  • Do not expect a rollback in the caller to undo what the worker does. Once the worker has committed, it stays committed.
  • Put @Transactional on the async method itself, so the worker has a transaction, and not on the caller expecting it to cover the worker.

Order check: the NotificationService chain printed the async interceptor first and the transaction interceptor second, which is why the transaction belongs to the worker.

Picture it Three experiments with H2: an entity passed to an async transactional method, an id passed instead, and a worker started inside the caller's open transaction.

Entity

The entity travels to another thread and its session is gone.

MailService.java · Boot 4.2runs offline
@Async @Transactional
Future<Integer> countLinesOfEntity(
        OrderEntity order) {
    return done(order.getLines().size());
}

Id

The worker loads the order in its own transaction.

MailService.java · Boot 4.2runs offline
@Async @Transactional
Future<Integer> countLinesById(long id) {
    return done(orders.findById(id)
        .orElseThrow().getLines().size());
}

The shift: Passing the id means the worker owns its data and its transaction.

Make the invisible visible: Run the three experiments.

output · Boot 4.2 (B/tx.out)runs offline
-- pass the ENTITY to an @Async @Transactional method:
  org.hibernate.LazyInitializationException: Cannot lazily initialize collection of role 'com.quickbite.async.
-- pass the ID:
  lines = 2
-- worker started INSIDE the caller's open transaction, before commit:
  caller [main] tx active=true
  worker [task-3] tx active=true tx name=com.quickbite.async.MailService.txInfo sees order 2? false

Make the invisible visible: And the caller's own transaction with an async audit call, from the AOP section.

output · Boot 4.2 (A/asynctx.out)runs offline
   caller on thread main, transaction active = true
   caller's own transaction is still open, and it does not own the audit work
   record(A-100) on thread task-1, transaction active = true, name = com.quickbite.aop.asynctx.AuditService.re

What you see: The entity version failed with a LazyInitializationException whose message says "Cannot lazily initialize collection ... (no session)". The id version returned 2 lines. The worker had transaction active = true on task-3, with its own transaction name, and it did not see the order the caller had not yet committed. The audit demo shows main with one transaction and task-1 with another.

Why: Threads do not share transactions, so the two units of work are independent. See section 05 and, for the commit timing, the after-commit event idiom.

Land it I pass ids and not entities to async methods, and I start the async work after the caller commits, because the worker's transaction is separate.

Likely follow-ups
"How do I make the async work start only after the commit?"

Publish an application event inside the transaction and handle it with @TransactionalEventListener in the AFTER_COMMIT phase. The listener runs only if the transaction commits, and not at all if it rolls back. Mark the listener @Async as well, and the work then runs on a worker after the commit.

AfterCommit.java (idea) · Boot 4.2runs offline
@Transactional
public void placeOrder(Order o) {
    orders.save(o);
    events.publishEvent(new OrderPlaced(o.getId()));
}

@Async
@TransactionalEventListener(phase = AFTER_COMMIT)
void sendEmail(OrderPlaced e) { mail.send(e.orderId()); }

This gives both guarantees: no email for a rolled-back order, and a worker that can see the committed data. I did not run this exact class in this answer. The scheduling section of the primer runs the rollback versus commit case.

Remember what it does not give: if the process dies right after the commit, the email is lost, because the event is only in memory (question 44).

"Why did the entity version fail with LazyInitializationException?"

JPA loads the order's lines lazily, on first access, and it needs an open Hibernate session to do it. The caller loaded the entity in its own session. When the entity reaches the worker, that session is closed or belongs to another thread, so touching order.getLines() has nothing to load from.

The message says it plainly: "Cannot lazily initialize collection of role ... (no session)". The demo printed exactly that for the entity version.

The fix is the one in the answer: pass the id, and let the worker load what it needs in its own transaction. Or pass a small immutable object (a record with the fields the worker needs), loaded and filled by the caller.

Do not "fix" it with FetchType.EAGER everywhere or with open-session-in-view on the worker. That hides the design problem and loads more data than needed.

"Can the caller wait for the worker's transaction to finish?"

Only by waiting on the future: return CompletableFuture and call join() after the worker completes. Then the worker's transaction has already committed or rolled back when join() returns. But the caller has made the call synchronous again, and it holds its own transaction open while it waits, which can pin a database connection for a long time.

If you want results back, think about what you are really building. If the caller needs the worker's outcome inside its own transaction, the work probably belongs in the same transaction and thread, with no @Async.

If the caller only needs "it was done" later, return the future, leave the transaction, and then wait or chain.

A rule I use: never wait on a future while a database transaction is open.

"What about @Transactional on the caller and a rollback after the async method was started?"

The async work is not undone. Once the worker has been submitted and has started, it runs independently. If the caller's transaction rolls back afterwards, the worker's own commit stays.

That is how an email can go out for an order that was rolled back, the incident in question 58. The cure is the same: start the async work only after the commit, with the after-commit listener.

If the worker must also be undone on a rollback, it cannot be separate. Make it part of the transaction, or add a compensating step that cancels the effect if the order is rolled back.

When you review code that calls an @Async method inside a @Transactional method, ask "what if the transaction rolls back after this line?". The answer tells you whether it is safe.

Q43. "What changes when spring.threads.virtual.enabled=true?"

Reveal answer

Strong answer Boot swaps its default pool for a virtual-thread executor. A virtual thread is a very cheap thread managed by the JVM. When it blocks (a database call, an HTTP call), the JVM parks it and reuses the carrier thread for something else, so you can have thousands or millions of them without running out of memory.

What I measured on Boot 4.2:

  • applicationTaskExecutor became a SimpleAsyncTaskExecutor, which starts a new virtual thread per task and keeps no pool and no queue.
  • The task ran on a thread with isVirtual() = true, still named with the prefix, task-1, task-2.
  • The pool settings (core-size, max-size, queue-capacity, keep-alive) no longer apply to it.
  • Boot also runs Tomcat request handling and scheduled tasks on virtual threads when the property is on (check the reference for the exact list on your version).

What does not change: your code still blocks, and ThreadLocals still work per thread (but remember they are per virtual thread, and creating millions of them with large ThreadLocal data costs memory). Propagation of user and MDC to the worker is still needed (question 41).

What you lose: the pool was also a limit. With no pool and no queue, nothing stops a burst of 100,000 tasks from running at once and hitting your database or a downstream API all together. You need explicit limits: a semaphore, a connection pool that blocks, or @ConcurrencyLimit (see section 06).

Also watch for pinning: a virtual thread inside a synchronized block or a native call can hold its carrier thread. The JDK has reduced this in recent releases, but measure if you rely on it. E21 covers virtual threads in depth.

Picture it The same application started with and without the property, then a limit applied to 50 concurrent virtual-thread callers.

Make the invisible visible: Start with the default (platform threads) and with spring.threads.virtual.enabled=true.

output · property off (B/virtual-off.out)runs offline
applicationTaskExecutor is a org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
  task 1 started on [task-1] virtual=false
  task 2 started on [task-2] virtual=false
  task 1 FINISHED
  task 2 FINISHED
output · property on (B/virtual.out)runs offline
applicationTaskExecutor is a org.springframework.core.task.SimpleAsyncTaskExecutor
  task 2 started on [task-2] virtual=true
  task 1 started on [task-1] virtual=true
  task 1 FINISHED
  task 2 FINISHED

Make the invisible visible: Now 50 callers on virtual threads, a method that takes 100 ms, first without a limit and then with @ConcurrencyLimit(10).

output · Boot 4.2 (F/limit.out)runs offline
unlimited  50 calls of 100 ms: max in flight = 50, wall = 109 ms
limited    50 calls of 100 ms: max in flight = 10, wall = 509 ms

What you see: With the property off the executor was a ThreadPoolExecutor-based ThreadPoolTaskExecutor and virtual=false. With it on the executor was a SimpleAsyncTaskExecutor and virtual=true. Without a limit, all 50 calls ran at once (max in flight 50, 109 ms). With @ConcurrencyLimit(10) only 10 ran at a time (max in flight 10) and the total grew to 509 ms: five rounds of 100 ms.

Why: Virtual threads remove the cost of waiting, not the cost of the work behind the wait. The pool used to protect your database. Now a limit has to do it. See the concurrency-limit idiom and section 05.

Land it Virtual threads make blocking cheap but remove the pool's built-in limit, so I add an explicit concurrency limit in front of anything fragile.

Likely follow-ups
"Do I still need executors if virtual threads are on?"

Less often, but yes for two jobs: naming and isolation and limits. A virtual thread is cheap, but a downstream service is not. If email sending and report generation share one unlimited pool of virtual threads, a burst of reports can slow emails or overload the database.

Keep a separate executor or a separate concurrency limit per kind of work, so one cannot starve the other. With virtual threads this is often a Semaphore or @ConcurrencyLimit, not a sized pool.

A common pattern is Executors.newVirtualThreadPerTaskExecutor() for tasks plus a per-resource limit. The primer's concurrency section shows the limit.

You also still want a clean shutdown. A SimpleAsyncTaskExecutor can wait for running tasks if you configure the shutdown properties (question 44).

"Can virtual threads make a CPU-heavy task faster?"

No. A virtual thread helps when tasks spend their time waiting. A CPU-bound task needs a processor, and there are only as many processors as cores (12 on the course machine). Running 10,000 CPU-bound virtual threads gives you the same throughput as 12 platform threads, plus a little scheduling overhead.

For CPU work, use a fixed pool sized to the cores, or a parallel stream or fork-join pool. For waiting work (HTTP, database, SMTP), virtual threads let one machine keep far more calls in flight.

I did not benchmark CPU-bound work here, because the point follows from how threads and cores work.

The test I give a team: "does this task mostly wait?" If yes, virtual threads help. If it mostly computes, they do not.

"What is thread pinning and should I worry?"

Pinning means a virtual thread cannot be unmounted from its carrier thread while it is blocked, because it is inside a synchronized block or a native frame. The carrier stays stuck, and with enough pinned threads the scheduler runs out of carriers.

JDK 24 made synchronized stop pinning in most cases, and the course machine runs Java 25, so the classic problem is much smaller. Native calls and some Object.wait cases can still pin.

You can detect it with -Djdk.tracePinnedThreads=full on older JDKs, or with the JFR event for pinned virtual threads. I did not capture pinning here, since nothing in the demo blocked inside a lock.

My advice: on Java 25 do not worry in advance, measure under load, and replace long synchronized sections that wrap blocking calls with ReentrantLock when you see a stall.

"Does @Async change in any other way with virtual threads on?"

The thread names. Boot keeps the prefix, so you still see task-1, but each task has its own new virtual thread, so numbers keep growing and are not reused, unlike a pool's task-1 to task-8. The demo printed task-2 before task-1 in one run, which shows there is no queue order to rely on.

Anything that assumed a small fixed number of threads changes: a metric named after pool size, a ThreadLocal cache that expected thread reuse, a test that waited for "a free worker". With a new thread per task, a ThreadLocal cache gets no reuse.

Shutdown also differs, since no pool exists: wait for running tasks through the executor's termination setting.

Test your own code with the property on in a staging environment before turning it on in production.

Q44 · Scenario. "Async email sending loses emails on every deploy. Why, and what should you use instead?"

Reveal answer

Strong answer @Async keeps its waiting work in the memory of one JVM. The queue is a Java object. When the process stops, work that is queued and not yet running is lost, and work that is running may be cut off. A deploy replaces pods, so every deploy throws away whatever was waiting. A crash or an OOM kill does the same without any warning.

It is the design, not a bug. @Async is "run this on another thread", with no promise that it will finish.

Two separate remedies:

  1. Drain gracefully on a normal stop. spring.task.execution.shutdown.await-termination=true with await-termination-period=30s makes the context wait for running and queued tasks before it closes. Give the pod a termination grace period at least that long.:
  2. Use something durable for anything that must happen: write the work to a database table (the outbox pattern) or a message broker (Kafka, RabbitMQ), and let a worker send from there, with retries. After a crash the pending rows are still there.

The first remedy handles planned stops only. A kill -9, a node loss or an OOM kill skips it. So for an email that must be sent (an order confirmation, an invoice) the durable route is the answer.

What @Async is fine for: best-effort work you can afford to lose or that is repeated anyway, such as a cache warm-up, a metrics push or a "recently viewed" update.

Stack choice: @Async for best effort; a CompletableFuture with your own executor for work that is part of the request; a broker or outbox for must-happen work; Spring Batch or a scheduler for bulk or timed work. E7's outbox idiom and E17 cover the durable options.

Picture it Three runs. First: six emails queued with @Async on one worker, and the process killed after 2.5 seconds. Second and third: the same six emails written to an outbox table first, the process killed, then restarted.

In memory

@Async queue. Nothing survives the process.

MailService.java · Boot 4.2runs offline
@Async("singleExecutor")
public void sendQueued(int n) {
    send(n);          // waits in a Java queue
}

Outbox

A row in a table is written first, then sent.

// illustrative · outbox sketchillustration
outbox.save(new Mail(n, "PENDING"));
// a poller later: send, then
// row.setStatus("SENT")

The shift: The queue moved from memory to the database, so a restart finds the unfinished work.

Make the invisible visible: Kill the process in the middle of each run.

output · @Async only (B/lost.out)runs offline
$ run 1: @Async on a single worker
6 emails queued; the process is killed at t=2.5 s
  email #1 sent
  email #2 sent
*** kill -9 ***
output · outbox table (B/outbox.out)runs offline
$ run 1: write to the outbox table, send from it
6 emails written to the outbox table as PENDING
  email #1 sent, row marked SENT
  email #2 sent, row marked SENT
*** kill -9 ***

$ run 2: restart the process
restart: pending rows = 4
  email #3 sent, row marked SENT
  email #4 sent, row marked SENT
  email #5 sent, row marked SENT
  email #6 sent, row marked SENT
outbox now: SENT=6 PENDING=0

Make the invisible visible: And a graceful stop: three tasks running when the context closes.

output · shutdown settings (B/shutdown.out)runs offline
$ run A: defaults
runner done; closing the context now
  task 1 FINISHED
  task 3 FINISHED
  task 2 FINISHED
total wall 7.54 s

$ run B: --spring.lifecycle.timeout-per-shutdown-phase=1s
runner done; closing the context now
  task 3 INTERRUPTED
  task 1 INTERRUPTED
  task 2 INTERRUPTED
total wall 5.77 s

$ run C: B plus await-termination=true, period=10s
runner done; closing the context now
  task 3 FINISHED
  task 2 FINISHED
  task 1 FINISHED
total wall 9.83 s

What you see: With @Async only, emails 1 and 2 were sent and the kill took emails 3 to 6 with it: no trace, no retry. With the outbox, the same kill left 4 rows PENDING, and after the restart emails 3 to 6 were sent and the table showed SENT=6 PENDING=0. In the shutdown run, a short timeout interrupted the tasks (INTERRUPTED), and await-termination=true with a 10-second period let them finish.

Why: A memory queue dies with its process. A table survives. Graceful shutdown helps with planned stops only. See the async-not-durable idiom in section 05.

Land it I use @Async only for work I can afford to lose, and a durable outbox or broker for anything that must happen, plus a graceful shutdown for the normal stop.

Likely follow-ups
"Does a graceful shutdown solve the problem?"

It solves the planned stop. With await-termination=true and a long enough period, a normal SIGTERM makes Spring finish the running and queued tasks before the JVM exits. The demo shows it: with a short phase timeout the tasks were interrupted, and with the await settings they all finished.

It does not help when the process is killed without warning: a node failure, an OOM kill, a kill -9, or a deploy whose grace period is shorter than the work. The lost.out demo used exactly such a kill.

So graceful shutdown is a good habit, but it is not durability. I still set it on every service, because it removes the most common loss, and I set the Kubernetes terminationGracePeriodSeconds longer than the await period.

For must-happen work I still add the outbox, since that covers the unplanned case too.

"What is the outbox pattern, in a few lines?"

In the same database transaction that saves the order, you also insert a row into an outbox table describing the work: "send confirmation email for order A-100", status PENDING. The commit makes both visible together, so an order exists if and only if its email task exists.

A separate poller (a @Scheduled job or a worker) reads pending rows, performs the work, and marks each SENT. If it crashes midway, the rows are still PENDING and the next run picks them up. The send can happen twice (if the crash came after sending and before marking), so make the receiver idempotent or use an idempotency key (question 48).

The demo is the small version: 6 rows written, the process killed after 2 were sent, and after the restart the 4 pending were sent.

For high volume, the poller can publish the rows to Kafka or RabbitMQ instead of sending directly. E7 has the full outbox idiom.

"Why not just retry the failed emails at start-up with @Async?"

Because at start-up you no longer know which emails were lost. The queue in memory is gone, and without a record of what was waiting, there is nothing to retry from.

To retry you must have stored the intention somewhere before the crash, and a table or a broker is exactly that. Then "retry at start-up" is just "process the pending rows", which the outbox poller does anyway.

A log line is not a record you can replay reliably, since it may not show which emails were sent.

So the order is: store first, send second. That is the opposite of @Async, which sends first and keeps nothing.

"Is it ever fine to keep @Async for email?"

Yes for emails where a loss is acceptable: a "welcome" email that the user can request again, a marketing digest, a newsletter. If missing one means a user asks support, and the cost is small, the simplicity is worth it.

For an order confirmation or invoice, a loss means a customer thinks the order failed, or a legal document is missing. I would use the outbox.

A middle option is @Async with a recovery sweep: a scheduled job looks for orders without a "confirmation sent" flag older than five minutes and sends them again. It is cheap, and it needs a flag in the order row and an idempotent send.

Choose by asking: "what happens to the business if this task disappears?" The answer chooses the tool.

Q45. "How do you name and isolate executors for different kinds of work?"

Reveal answer

Strong answer Declare one executor bean per kind of work, give each its own thread-name prefix, size and queue, and select it by name: @Async("mailExecutor"). This is the bulkhead idea from ships: a leak in one compartment does not sink the others. If report generation is slow or stuck, it fills only the report pool, and emails still go out.

Each executor needs four decisions:

DecisionWhyExample
Name and thread prefixThread dumps and logs show which pool a thread belongs tomail-, report-
SizeMatch the work: waiting tasks need more threads than coresmail: 2 core, 2 max
Queue capacityA bounded queue turns overload into a visible signalmail: 3 waiting
Rejection policyWhat happens when pool and queue are fullAbort (throw) or CallerRunsPolicy (the caller does it, which slows the producer)

The default policy is abort: TaskRejectedException goes to the caller. For work you may drop or retry, that is right. For work that must not be dropped, CallerRunsPolicy slows the caller down instead of losing the task, which acts as natural back-pressure. A third choice is a policy that writes the task to a durable store.

Remember two Spring Boot details. Defining your own Executor bean makes Boot back off its applicationTaskExecutor (the demo printed [mailExecutor, reportExecutor]), so name the executor in every @Async, or you may end up with an unexpected executor for un-named calls. And Spring shuts down executor beans with the context.

Add metrics for each pool (active, queued, rejected) so you can see which compartment is full.

Picture it Two executors: mailExecutor (2 threads, 3 waiting, abort on overflow) and reportExecutor (1 thread, 1 waiting, caller runs on overflow). Seven mail tasks and four report tasks are submitted quickly.

ExecutorsConfig.java · Boot 4.2runs offline
@Bean ThreadPoolTaskExecutor mailExecutor() {   // 2 threads + 3 waiting
    return pool("mail-", 2, 2, 3);
}
@Bean ThreadPoolTaskExecutor reportExecutor() { // 1 thread + 1 waiting
    ThreadPoolTaskExecutor ex = pool("report-", 1, 1, 1);
    ex.setRejectedExecutionHandler(
        new ThreadPoolExecutor.CallerRunsPolicy());
    return ex;
}
// use:  @Async("mailExecutor")   @Async("reportExecutor")

Make the invisible visible: Submit the tasks and read the output.

output · Boot 4.2 (B/reject.out)runs offline
Executor beans: [mailExecutor, reportExecutor]
  mail #1 running on [mail-1]
submitted #1
submitted #2
submitted #3
submitted #4
submitted #5
  mail #2 running on [mail-2]
submit #6 FAILED: TaskRejectedException: ExecutorService in active state did not accept task: org.springframew
submit #7 FAILED: TaskRejectedException: ExecutorService in active state did not accept task: org.springframew
-- reportExecutor (CallerRunsPolicy): caller thread = [main]
  report #1 running on [report-1]
  report #3 running on [main]
  report #2 running on [report-1]
  mail #3 running on [mail-1]
  mail #4 running on [mail-2]
  report #4 running on [report-1]
  mail #5 running on [mail-1]

What you see: The bean list shows only the two named executors. Mail tasks ran on mail-1 and mail-2, reports on report-1. Mail tasks 1 to 5 were accepted (2 running and 3 waiting), and tasks 6 and 7 were rejected with TaskRejectedException. In the report run, task 3 ran on main, the caller thread, because of CallerRunsPolicy.

Why: The bounded queue made overload visible, and the policy decided what to do about it: reject for mail, slow the caller for reports. Reports and mail never took each other's threads. See the named-executor idiom in section 05.

Land it I give each kind of work its own named executor with a bounded queue and a deliberate rejection policy, so one slow workload cannot starve another.

Likely follow-ups
"Which rejection policy should I choose?"

Choose by what the work is worth. Abort (the default) throws TaskRejectedException to the caller. Use it when the caller can decide: show an error, retry later, or drop. The demo's tasks 6 and 7 show it.

CallerRuns runs the task on the submitting thread. The producer is slowed down while it does the work, so it cannot flood the pool: natural back-pressure. Risk: the caller may be a request thread, and the slow work now delays the response, as in the report demo where task 3 ran on main.

Discard and DiscardOldest drop silently, which is fine only for work with no consequence, such as a refresh of a display value.

For must-happen work none of these is good enough: write it to a durable store and process it from there (question 44).

"What happens to @Async calls with no name if I define only custom executors?"

Spring looks for an executor in this order: the name in the annotation, a bean of type TaskExecutor named taskExecutor, a single TaskExecutor bean, and then falls back to a simple executor that starts a new thread for every call. If you define two custom executors and neither is the unique TaskExecutor, an un-named @Async may use that fallback, with no pool and no limit.

The demo printed the executor beans as [mailExecutor, reportExecutor], with no applicationTaskExecutor, which is what Boot's back-off does.

Avoid the surprise in two ways: always name the executor in @Async("..."), or implement AsyncConfigurer and return the default executor from getAsyncExecutor().

A startup check can help: a test that fails if any @Async method has no explicit executor name.

"How do I choose the number of threads for each executor?"

From the arrival rate and the time per task: threads needed is roughly tasks per second times seconds per task. Emails at 5 per second, each taking 2 seconds on the SMTP server, need about 10 threads.

Then cap it by what the downstream can take. If the SMTP provider allows 4 parallel connections, 10 threads only produce errors, so the cap is 4 and the queue holds the rest.

Choose the queue size from how long a task may wait: 4 tasks per second out, and you accept waiting 10 seconds, so a queue of about 40.

Check the numbers with the metrics (active, queued, rejected) after the first week, and change them from data.

"Do named executors survive a graceful shutdown?"

Spring manages executor beans that implement its lifecycle (ThreadPoolTaskExecutor does), and closes them with the context. By default it waits for tasks that are running. To wait for the queue too and to set a limit, use the executor's waitForTasksToCompleteOnShutdown and awaitTerminationSeconds, or for Boot's own executor the spring.task.execution.shutdown.* properties.

The measured shutdown demo (question 44) used the auto-configured executor: with the await properties the tasks finished, and with a short phase timeout they were interrupted. For your own beans, set the same two things on the bean.

Make sure the orchestrator gives the pod enough time: the termination grace period should be longer than the longest await period, or the process is killed before the wait ends.

Test it: start tasks, send SIGTERM and see which tasks finish.

Drill · Retry, limits and circuit breakers

These questions test whether you pick the right resilience tool and read its numbers correctly. The first five are here, and the circuit breaker questions follow. Every count comes from a real run on Boot 4.2.

Q46. "Spring Framework 7 @Retryable, Spring Retry or Resilience4j — which do you pick?"

Reveal answer

Strong answer I pick by what the call needs. For a simple "try again a few times with a delay", I use Spring Framework 7's @Retryable. It is built into the core, so there is no extra dependency, and it has one important property: its advice always runs outside @Transactional and @Cacheable, so each attempt gets a fresh transaction and a fresh cache lookup (question 14).

OptionPick it whenCost or catch
Spring Framework 7 @Retryable + @EnableResilientMethodsPlain retries with delay, multiplier, jitter, includes and excludes, in a Boot 4 / Framework 7 serviceOnly retry, no circuit breaker, no rate limiter. Counts retries, not attempts
Spring Retry (the older library)Existing code on Boot 3 or earlier, or you need its @Recover and listener featuresAn extra dependency. Counts attempts. Check the project page for its maintenance status
Resilience4jYou need a circuit breaker, rate limiter, bulkhead or time limiter, with metrics, not only retriesMore configuration and concepts. A separate library with its own annotations
Retries in the platform (service mesh, gateway)Same retry policy for every service without code changesCoarse: it does not know which calls are safe to repeat

They are not exclusive. A typical design: timeouts on every call, Framework 7 @Retryable for transient errors, and a Resilience4j circuit breaker around the remote dependency, so that when it is truly down you stop calling it and fail fast.

The ordering matters when they combine. Framework 7's retry sits outermost on its bean. A Resilience4j breaker on the same method sits inside it, so each retry attempt passes through the breaker and counts toward its failure rate, which is usually what you want. Print the advisor chain to confirm (question 17).

Whichever you use: retry only what is safe to repeat (question 48), keep the count small, and add jitter (question 49). The primer's resilience section has the full table and the demos.

Picture it The same retry rule written for the older library and for Framework 7, then the real runs of both on Boot 4.2 against a gateway that always fails.

Spring Retry

@EnableRetry, counts attempts: maxAttempts.

Gateway.java · Spring Retryruns offline
@Retryable(maxAttempts = 3,
    backoff = @Backoff(delay = 100))
public void charge() { ... }

Framework 7

@EnableResilientMethods, counts retries: maxRetries.

Gateway.java · Boot 4.2runs offline
@Retryable(maxRetries = 2,
           delay = 100)
public void charge() { ... }

The shift: Both give three calls here, but the number you write is different, and the imports and the enabling annotation are different too.

Make the invisible visible: Run the old library with maxAttempts = 3, then Framework 7 with maxRetries = 2.

output · Spring Retry 2.0.13 on Boot 4.2 (F/oldretry.out)runs offline
   call 1
   call 2
   call 3
   -> java.lang.IllegalStateException: 503 (total calls: 3)
output · Framework 7, maxRetries = 2 (F/retry.out)runs offline
   retries=2 call 1 at  2583 ms
   retries=2 call 2 at  2684 ms
   retries=2 call 3 at  2785 ms
   -> IllegalStateException: 503  (total calls: 3)

Make the invisible visible: And the circuit breaker, from the resilience section.

output · Resilience4j (C/breaker.out)runs offline
--- gateway is DOWN ---
  call 1 at   26 ms (pay o-1)
pay #1 -> QUEUED (503 Service Unavailable)
  call 2 at   39 ms (pay o-2)
pay #2 -> QUEUED (503 Service Unavailable)
  call 3 at   41 ms (pay o-3)
pay #3 -> QUEUED (503 Service Unavailable)
  call 4 at   46 ms (pay o-4)
  >>> state State transition from CLOSED to OPEN at 55 ms
pay #4 -> QUEUED (503 Service Unavailable)
pay #5 -> QUEUED (breaker open, call skipped)
pay #6 -> QUEUED (breaker open, call skipped)

What you see: Both retry rules produced exactly three calls and then rethrew the original IllegalStateException. The Resilience4j run shows something retry cannot do: after four failures the breaker went from CLOSED to OPEN, and the next calls were skipped ("breaker open, call skipped") with no gateway call at all.

Why: Retry answers "try again". A breaker answers "stop trying for a while". A gateway outage needs both. See the idempotent-retry idiom and the circuit-fallback idiom.

Land it For plain retries I use Framework 7's @Retryable, and I add a Resilience4j breaker when a dependency can be down for a while and I need to stop calling it.

Likely follow-ups
"Can I run Spring Retry and Framework 7 @Retryable together?"

They use different annotations in different packages, so both can exist in one project, and I ran both on Boot 4.2 here. But two retry mechanisms on one method would multiply the attempts: 3 outer times 3 inner is 9 calls. I never put both on the same method.

During a migration, convert one class at a time: replace @EnableRetry and the annotation, translate maxAttempts to maxRetries (subtract one, question 47), and check each converted method with a call counter.

The importing is the trap. org.springframework.retry.annotation.Retryable and org.springframework.resilience.annotation.Retryable share a simple name, and an IDE can pick the wrong one without a warning.

Search the project for both imports in code review during the migration.

"Where does a Resilience4j circuit breaker sit relative to @Retryable?"

Inside it. With Framework 7, the retry advisor is outermost on its bean, and a Resilience4j aspect behaves like any other aspect, so it sits below the retry. Each retry attempt therefore goes through the breaker: failures count toward the breaker's failure rate, and when the breaker is open the attempt fails at once without calling the gateway.

That is usually the right shape. Retries handle brief glitches, and the breaker stops the retries from hammering a service that is really down.

One side effect: when the breaker is open, a retry policy that retries on any exception will also retry the "call not permitted" exception, and burn its delays on a call that cannot succeed. Exclude that exception type (CallNotPermittedException) from the retry.

I did not run this exact combination. The separate runs above show each behaviour.

"Is Spring Retry deprecated?"

I do not state a status I have not checked. What is clear is that Spring Framework 7 brought core resilience features (@Retryable, @ConcurrencyLimit, RetryTemplate) into the framework itself, which covers the common use of the older library. Look at the Spring Retry project page and its release notes for its current maintenance state before you start a new project on it.

The demo shows it still works with Boot 4.2: a plain @Retryable(maxAttempts = 3) produced three calls. That tells me it runs, not that it is the right choice for new code.

For new Boot 4 code I would start with the framework version, since it has no extra dependency and puts retry outside the transaction by rule.

For existing code, there is no hurry. Migrate when you touch the class, and keep the call counter test.

"Why not rely on the service mesh or the gateway for retries?"

A mesh or a gateway can retry for every service without code changes, which is a quick win for read requests. But it does not know which calls are safe to repeat. A retry of a POST /payments by the mesh is a retry of a charge, and the mesh will not add an idempotency key for you.

It also multiplies. If the mesh retries 3 times and your code retries 3 times, one failure becomes up to 9 calls to the dependency, a retry storm that can finish off an already struggling service.

My rule is to decide on one place that retries each call. For safe reads, the mesh may do it. For writes, the code does it, with an idempotency key. And everywhere there are timeouts.

Write the choice in the service's README so nobody adds a second layer by accident.

Q47. "maxRetries in Spring Framework 7 versus maxAttempts in Spring Retry — why does the difference matter?"

Reveal answer

Strong answer They count different things. maxAttempts (Spring Retry) is the total number of calls, the first one included. maxRetries (Framework 7) is the number of retries after the first call. So the same intent, "three calls in total", is maxAttempts = 3 and maxRetries = 2.

The demo proves it on Boot 4.2 with a gateway that always fails:

AnnotationWritten valueCalls made
Spring Retry @RetryablemaxAttempts = 33
Framework 7 @RetryablemaxRetries = 23
Framework 7 @RetryablemaxRetries = 34
Framework 7 @Retryable, all defaults3 retries, 1 s delay4

Why it matters: a developer converts the annotation and keeps the number: maxAttempts = 3 becomes maxRetries = 3. The method is now called 4 times instead of 3, one third more load on a dependency that is already failing, and for a non-idempotent call one more chance to double-charge (question 48).

Worked example with a 2-second timeout and a 1-second delay: three calls take 3 x 2 + 2 x 1 = 8 seconds at worst. Four calls take 4 x 2 + 3 x 1 = 11 seconds. A caller with a 10-second budget now times out.

The defaults are easy to forget. Framework 7's defaults of 3 retries and a 1-second delay mean a failing call is made 4 times over 3 seconds: the measured calls were at 15, 1,021, 2,022 and 3,022 ms.

When migrating, write the number of calls you want, then convert it: retries = calls - 1.

Picture it Spring Retry's maxAttempts = 3, Framework 7's maxRetries = 3 and maxRetries = 2, each against a gateway that always answers 503, with a counter of calls.

Gateway.java (excerpts) · Boot 4.2runs offline
// Spring Retry
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 100))

// Framework 7
@Retryable(maxRetries = 3, delay = 100)
@Retryable(maxRetries = 2, delay = 100)

Make the invisible visible: Spring Retry first, then the two Framework 7 variants.

output · Spring Retry, maxAttempts = 3 (F/oldretry.out)runs offline
   call 1
   call 2
   call 3
   -> java.lang.IllegalStateException: 503 (total calls: 3)
output · Framework 7, maxRetries = 3 then 2 (F/retry.out)runs offline
   retries=3 call 1 at  2273 ms
   retries=3 call 2 at  2377 ms
   retries=3 call 3 at  2479 ms
   retries=3 call 4 at  2579 ms
   -> IllegalStateException: 503  (total calls: 4)
   retries=2 call 1 at  2583 ms
   retries=2 call 2 at  2684 ms
   retries=2 call 3 at  2785 ms
   -> IllegalStateException: 503  (total calls: 3)

What you see: Spring Retry with maxAttempts = 3 made 3 calls and ended with IllegalStateException: 503 (total calls: 3). Framework 7 with maxRetries = 3 made 4 calls (about 100 ms apart), and with maxRetries = 2 it made 3 calls. Both rethrow the original exception when they give up.

Why: One number includes the first call and the other does not. The fix when migrating is arithmetic: retries = attempts - 1. See section 06 for the full retry demo with defaults, backoff and includes.

Land it maxAttempts counts the first call and maxRetries does not, so when I migrate I convert three attempts into two retries and check the call counter.

Likely follow-ups
"How can I make sure a migration did not change the call count?"

With a call counter test per retried method. Make the fake dependency count its calls and fail every time, call the method, catch the exception and assert the count equals the number you intend.

RetryCountTest.java (idea) · Boot 4.2runs offline
@Test void chargeIsCalledThreeTimesAtMost() {
    gateway.alwaysFail();
    assertThrows(IllegalStateException.class,
                 () -> service.charge("A-100"));
    assertThat(gateway.calls()).isEqualTo(3);
}

Use a very small delay in tests (delay = 1 or a test property) so the test runs fast. I did not run this test class, but the same counter was used in the demos above.

Write the expected number as a comment next to the annotation: "3 calls in total". A reader then sees the intent, whatever the library counts.

"What are the other differences besides the count?"

Framework 7 adds jitter, maxDelay and multiplier as plain attributes, and includes and excludes for exception types, with the retry advice always outside @Transactional and @Cacheable. After the last failed call it rethrows the original exception, as the demo printed.

Spring Retry has @Recover methods for a fallback after the last attempt, listeners, and a RetryTemplate with many policies. Framework 7 also has a programmatic RetryTemplate, with a smaller API.

The package names, the enabling annotation and the version of the dependency are different. And the order with @Transactional was a configuration matter in Spring Retry and is a fixed rule in Framework 7.

Read the reference for the version you use for the details. I only claim what the demos above showed.

"The defaults retry three times with a one-second delay. Is that a good default for a payment call?"

Usually not as it stands. Three retries with a fixed one-second delay mean four calls within three seconds, with no growth in the delay and no jitter. If a gateway is overloaded, a hundred callers all retrying at the same fixed rhythm hit it again at the same moments.

For a payment call I would write the policy down: a short delay that grows (delay, multiplier), a maxDelay, some jitter, a small maxRetries, includes only for the transient exceptions (I/O errors, 503), excludes for anything the server says is wrong with the request, and an idempotency key.

The measured defaults are in the resilience demo: calls at 15, 1,021, 2,022 and 3,022 ms.

Above all, a payment call needs a timeout first. Without one, a retry policy waits as long as the worst call, times four.

"Does maxRetries = 0 disable retrying?"

It would mean "no retries after the first call", which is a single call, the same as no annotation. I did not run it, so check that your version accepts zero, and prefer to remove the annotation if you do not want retries.

A more useful switch is a property: put the number in configuration (maxRetriesString = "${gateway.retries:2}" is the form the annotation offers for placeholders, check the reference) so operations can lower it during an incident without a deploy.

Turning retries down is a common incident move: when a dependency is failing, retries make it worse, and a lower setting reduces the load right away.

If you cannot change it at run time, your breaker or a feature flag has to do the job.

Q48 · Scenario. "Retrying a payment call charged a customer twice. What went wrong?"

Reveal answer

Strong answer The payment call was not idempotent, and the retry could not tell the difference between "the charge failed" and "the charge worked but I did not hear back". An operation is idempotent when doing it twice has the same effect as doing it once. A charge is not, unless you make it so.

The usual sequence: the client sends the charge, the gateway takes the money, and the reply is lost (a read timeout, a dropped connection, a 503 from a proxy in between). The client sees an error, the retry policy sees a transient error, and it sends the charge again. The gateway has no reason to think it is the same charge, so it takes the money a second time.

The fix has two parts:

  1. Send an idempotency key with every charge, made from something stable for the business operation (an order id, not a random value per attempt). The gateway stores the key with the first result. A second request with the same key returns the stored result and charges nothing.:
  2. Retry only what is safe: errors where the request never reached the server (connection refused) are safe. A read timeout is ambiguous, so it is safe only with the key.

Add the surrounding habits: a timeout on the call, a small retry count, a record of the key and the result in your own database, and a reconciliation job that compares your records with the gateway's.

The hidden-retry bug from the AOP section is the same problem in disguise: an aspect that called proceed() twice also charged twice (question 7). Any retry, wherever it lives, needs the key.

E20 has the server-side idiom, the idempotency key, and the primer links it from the idempotent-retry idiom.

Picture it A fake gateway that counts charges. The same retry runs once without a key and once with one. The first attempt succeeds at the gateway but its reply is lost, so the client retries.

No key

The retry sends a plain charge again.

PaymentClient.java · Boot 4.2runs offline
gateway.charge(orderId, cents);
// reply lost -> retry:
gateway.charge(orderId, cents);

With a key

Both calls carry the same key.

PaymentClient.java · Boot 4.2runs offline
String key = "key-" + orderId;
gateway.charge(orderId, cents, key);
// reply lost -> retry, same key:
gateway.charge(orderId, cents, key);

The shift: The key tells the gateway "this is the same charge", so the second call is an echo and not a second charge.

Make the invisible visible: Run both versions and count the money taken.

output · Boot 4.2 (C/idempotent.out)runs offline
--- retry WITHOUT an idempotency key ---
  call 1: charged order o-1001 (total charges so far = 1)
  call 2: charged order o-1001 (total charges so far = 2)
charge -> receipt-2
money taken: 2 time(s)
--- retry WITH an idempotency key ---
  call 1: charged order o-1001 (total charges so far = 1)
  call 2: key key-o-1001 seen before, returning the old result
charge -> receipt-1
money taken: 1 time(s)

What you see: Without the key: two calls, "money taken: 2 time(s)". With the key: the second call printed "key key-o-1001 seen before, returning the old result", and "money taken: 1 time(s)".

Why: The key turns a repeat into a lookup. The gateway, not the client, decides that the second request is a duplicate, because only the gateway knows whether the first one worked. See section 06 for the full demo.

Land it A retry cannot tell a failed charge from a lost reply, so I send an idempotency key made from the order and retry only with it.

Likely follow-ups
"Which failures are safe to retry on a payment call without a key?"

Only those where I know the request never reached the gateway: a connection that was refused, a DNS failure, a TLS handshake error before any bytes were sent. Nothing could have been charged.

A read timeout or a dropped connection after the request was sent is ambiguous: the charge may or may not have happened. An HTTP 5xx from a proxy is ambiguous too, because the proxy may have forwarded the request. A 4xx from the gateway ("invalid card") means the request was received and rejected, and retrying will not help.

In Framework 7 terms: put includes on the exception types for "request not sent" and keep the ambiguous ones out, unless the key is present.

In practice I send the key on every charge, because it removes the need to classify errors, and then retrying on the ambiguous ones is safe.

"How should the idempotency key be built?"

From the business operation, not from the attempt. For a charge, the order id plus the purpose is a good key: charge-o-1001. Every retry of that order's charge sends the same key. A random UUID generated inside the retried method is wrong: each attempt gets a new key and the protection is gone.

Generate the key before the first attempt and keep it with the order (a column), so a retry after a crash, or by another pod, reuses it.

Keys should not be reused for a different amount: gateways usually reject the same key with different parameters, which is a good safety check.

Keep keys long enough to cover your longest retry window, since a gateway forgets them after some time (check your provider's retention).

"What do I do if the gateway offers no idempotency key?"

Then the key lives on your side. Before charging, write an intent row (order id, amount, status PENDING). Call the gateway. On an ambiguous failure, do not retry the charge: query the gateway for a payment with your reference (most gateways let you look up by merchant reference) and act on what it says.

That turns "retry" into "check, then decide", which is safe for any gateway. A reconciliation job that lists PENDING rows older than a few minutes and checks each with the gateway catches the rest.

It is more code than a key, but it is the honest design when the provider gives you nothing else.

In both designs, the money record in your database is the source of truth, and the gateway is a partner that you reconcile against.

"How can I test that a retry does not charge twice?"

Use a fake gateway that succeeds but loses the reply on the first call: it records the charge and then throws a timeout exception. The client retries. Assert that the fake recorded exactly one charge.

That is the shape of the demo above, and it fails clearly if the key is missing or different between attempts: money taken: 2 time(s).

Also test the key stability: call the service twice for the same order and assert the same key was sent; and for a different order, a different key.

Keep this test next to the payment code. It is the single most valuable test in a payment service, because the bug it prevents costs real money.

Q49. "Exponential backoff and jitter — why do you need both?"

Reveal answer

Strong answer They solve two different problems.

Exponential backoff makes each wait longer than the last: for example 200 ms, 400 ms, 800 ms. A failing dependency often needs time to recover, so spacing retries out gives it room, and the total load from retries falls as they go on. A fixed delay keeps hitting it at the same rate.

Jitter adds a random amount to each wait. Without it, clients that failed at the same moment retry at the same moment, again and again, in synchronised waves. This is a thundering herd, and it can knock a recovering service down again.

Hand-worked: 100 clients all fail at time 0. With a fixed 1-second delay, all 100 retry at 1.0 s, again at 2.0 s, again at 3.0 s: three spikes of 100 requests. With exponential backoff alone they are still synchronised, only at 0.2, 0.6 and 1.4 s. With jitter the retries spread over each interval, and the peak falls to a fraction of 100.

Settings in Framework 7: delay, multiplier, maxDelay (a cap, so the wait does not grow forever) and jitter. Keep the total budget in mind. Delays of 200, 400 and 800 ms add up to 1.4 seconds of pure waiting, on top of the call times.

Add a limit on the number of retries and a timeout on every call. Backoff and jitter spread the retries, and the count stops them.

Picture it A retry with a delay of 100 ms and a multiplier of 2, against a gateway that always fails. Without jitter, then with a jitter of 40 ms.

Backoff only

Delays grow: 100, 200, 400, 800 ms.

Gateway.java · Boot 4.2runs offline
@Retryable(delay = 100,
           multiplier = 2,
           maxRetries = 4)

Backoff plus jitter

The same, with a random spread added.

Gateway.java · Boot 4.2runs offline
@Retryable(delay = 100,
           multiplier = 2,
           jitter = 40,
           maxRetries = 4)

The shift: The delays are still growing, but each one now has a random part, so two clients no longer retry in step.

Make the invisible visible: Call times for both (milliseconds since the start of the demo).

output · Boot 4.2 (F/retry.out)runs offline
   backoff   call 1 at  2786 ms
   backoff   call 2 at  2887 ms
   backoff   call 3 at  3088 ms
   backoff   call 4 at  3489 ms
   backoff   call 5 at  4289 ms
   -> IllegalStateException: 503  (total calls: 5)
   jitter    call 1 at  4291 ms
   jitter    call 2 at  4417 ms
   jitter    call 3 at  4539 ms
   jitter    call 4 at  4886 ms
   jitter    call 5 at  5973 ms
   -> IllegalStateException: 503  (total calls: 5)

Make the invisible visible: And four more runs from the resilience section with a similar delay, multiplier and jitter.

output · Boot 4.2 (C/jitter.out)runs offline
run 1
  call 1 at   21 ms (backoff)
  call 2 at  255 ms (backoff)
  call 3 at  596 ms (backoff)
  call 4 at 1473 ms (backoff)
backoff() -> OK
run 2
  call 1 at    0 ms (backoff)
  call 2 at  209 ms (backoff)
  call 3 at  693 ms (backoff)
  call 4 at 1642 ms (backoff)
backoff() -> OK

What you see: Without jitter the gaps were 101, 201, 401 and 800 ms: exactly doubling. With jitter they were about 126, 122, 347 and 1,087 ms, and in the four runs of the other demo the fourth call came at 1,473, 1,642, 1,191 and 1,351 ms. Every run was different, and none was a multiple of the base delay.

Why: Backoff spreads retries over time, and jitter spreads them across clients. The measured jitter was larger for longer delays. I do not claim the exact formula, so check the reference for your version. See section 06 and Fig. 22.9.

Land it Backoff gives the dependency time to recover, jitter stops clients from retrying in lockstep, and a retry count and timeout keep the total bounded.

Likely follow-ups
"Is jitter really needed if I have only one client?"

For one client it does little. The herd effect comes from many clients with the same schedule. A single process retrying on its own is already alone.

In practice you never have one client. A service runs on several pods, each pod handles many requests, and when the gateway fails, hundreds of calls fail within the same second and all start the same retry schedule. That is the herd, and jitter breaks it up.

The cost of jitter is tiny: one random number per wait. I turn it on by default.

The only time I skip it is in a test that needs exact timing, where I set a fixed delay on purpose.

"How long should the total retry window be?"

Shorter than the time a caller is willing to wait, and much shorter than the time the dependency needs to recover from a real outage. Retries are for glitches that last a second or two. If the dependency is down for minutes, retries only add load.

Compute the worst case: for the policy in the demo (4 retries, delays of 100, 200, 400, 800 ms) the waiting alone is 1.5 seconds. Add up to 5 call times. With a 2-second timeout per call the worst case is 5 x 2 + 1.5 = 11.5 seconds.

If your caller (a web request) has a 5-second budget, that policy is too generous. Cut the retries or the timeout.

For long outages use a circuit breaker so you stop calling at all (question 51 and the next questions), and a queue or an outbox for work that must be done eventually.

"What is a retry budget?"

A cap on retries as a share of all calls, instead of per call. For example "retries may be at most 10% of the traffic to this dependency". If the dependency is failing, per-call retry counts multiply the load by up to four times, while a budget limits the total extra load to a fixed percentage.

Spring Framework 7's @Retryable has a per-call count and not a shared budget, so I did not run one. Service meshes and some client libraries (gRPC clients, for example) offer retry budgets.

A circuit breaker gives a similar protection: when too many calls fail, it stops calling, so the retries stop with it.

If you do not have a budget, keep the per-call count small and watch the ratio of retried calls to first calls in the metrics.

"Why is maxDelay useful?"

Because exponential growth gets out of hand. With a multiplier of 2 starting at 200 ms, the sixth wait is 6.4 seconds and the tenth is over 100 seconds. A maxDelay of, say, 2 seconds caps each wait, so a long retry sequence settles at a steady slow rate instead of waiting for minutes.

The demo's resilience run used maxDelay 1,000 ms with a delay of 200 ms, multiplier 2 and jitter 50, and the waits stayed under a second.

With the cap, think about the total as well. Many retries at the cap still add up, so keep the count small.

Choose the cap from the point where waiting longer no longer helps the dependency: a few seconds is usually enough.

Q50. "What does @ConcurrencyLimit do, and when is it better than a thread pool or a bulkhead?"

Reveal answer

Strong answer @ConcurrencyLimit(10) is a Spring Framework 7 annotation (enabled with @EnableResilientMethods) that allows at most 10 callers inside the method at the same time. The eleventh caller waits until one of the first ten leaves. It is a semaphore with a proxy around it.

The demo: 50 callers on virtual threads, each call takes 100 ms. Without the limit all 50 ran at once (max in flight 50, 109 ms). With @ConcurrencyLimit(10) the maximum in flight was 10, and the total was 509 ms. The check by hand: 50 calls in groups of 10 is 5 rounds of 100 ms, 500 ms.

Where it fits against the alternatives:

OptionPick it whenCost or catch
@ConcurrencyLimitYou want to cap parallel calls to a fragile dependency, on the caller's own threads (especially virtual threads)Callers block while they wait. No wait timeout or metrics of its own. Check your version for a reject policy
Thread pool / named executorThe work can leave the caller (async), and you want a queue and a rejection policyA thread hand-off: ThreadLocals and transactions do not follow (question 41)
Resilience4j @BulkheadYou need a wait timeout, rejection instead of blocking, and metricsAnother library and more configuration
Connection pool sizeThe scarce resource is a database connectionLimits only that resource

Its best case is virtual threads. With virtual threads there is no pool to bound parallelism (question 43), so a limit on the method that calls the fragile service restores the protection, without moving the work to another thread. The caller's security context, MDC and transaction stay where they are.

Pick it for a simple cap. Pick a bulkhead when you need the cap to fail fast instead of waiting.

Picture it The experiment from question 43, now read as a resilience question: a method that takes 100 ms, 50 virtual-thread callers, with and without the limit. Max in flight is measured with a counter.

LimitDemo.java · Boot 4.2runs offline
@EnableResilientMethods
@Configuration
public class LimitDemo {
    @Service
    public static class Gateway {
        public void unlimited() { work(); }

        @ConcurrencyLimit(10)
        public void limited() { work(); }
    }
}

Make the invisible visible: Fifty callers each way.

output · Boot 4.2 (F/limit.out)runs offline
unlimited  50 calls of 100 ms: max in flight = 50, wall = 109 ms
limited    50 calls of 100 ms: max in flight = 10, wall = 509 ms

Make the invisible visible: And the same check from the resilience section.

output · Boot 4.2 (C/limit.out)runs offline
unlimited 50 callers: max in flight = 50, total 124 ms
limited   50 callers: max in flight = 10, total 519 ms

What you see: Unlimited: max in flight 50, 109 ms. Limited: max in flight 10, 509 ms. The other run agrees (50 versus 10, 124 versus 519 ms). The limit costs time for the callers who wait, and protects the dependency from more than 10 at once.

Why: The limit does not make the work faster. It decides how many callers are inside at the same moment. See the concurrency-limit idiom and section 06.

Land it ConcurrencyLimit caps parallel calls to a method on the caller's own threads, which is ideal with virtual threads, and I pick a bulkhead when I need a timeout or a fast failure.

Likely follow-ups
"What happens to the callers that are waiting for a slot?"

They block on the caller's thread until a slot is free. In the demo, 40 of the 50 callers waited, and the last one finished at 509 ms. With virtual threads, waiting is cheap, so thousands of waiting callers cost little memory.

With platform threads, waiting callers hold real threads. If many wait for a slow dependency, the web server's thread pool can fill up with them, and then everything is slow, including requests that do not need the dependency.

The wait has no timeout in the basic form, so a stuck call holds a slot forever and every other caller queues behind it. Put a timeout on the underlying call (a client timeout), so slots are always released.

If you need "wait at most 200 ms, then fail", use a bulkhead with maxWaitDuration, or check whether your Spring version has a reject policy on the annotation.

"Why is a limit on a method not the same as a limit on a thread pool?"

A pool limits how many tasks run at the same time among the tasks submitted to it. It needs the work to be handed over as tasks, and it adds a queue. A method limit looks at who is inside a particular method at the moment, whatever thread they come from.

That makes the method limit more precise for protecting one dependency. Ten different pools could call the same fragile method, and only a limit on the method or a shared semaphore bounds the total.

It also keeps the call on the caller's thread, so you do not lose the security context or the transaction, which a pool hand-off would.

The pool is still the right tool when you want to move the work off the request thread and queue it. The two are often used together.

"Is a connection pool already a concurrency limit?"

For the database, yes: HikariCP with a maximum of 10 connections lets at most 10 queries run at once, and other callers wait for a connection up to the connection timeout. That is a built-in limit, and it is why a stampede of 200 callers shows up as waiting for connections (question 25).

It does not protect other resources: an HTTP gateway, an SMTP server, a CPU-heavy library. For those you need a limit of your own, and @ConcurrencyLimit is the shortest one.

Keep the two consistent. A method limit of 50 in front of a pool of 10 connections just moves the queue from the pool to the method.

Set the limit from what the dependency can take, not from what your pool can hold.

"How do I choose the number?"

From the dependency's capacity. If the gateway handles 20 requests per second and each call takes 100 ms, then about 20 x 0.1 = 2 calls are in flight on average, and a limit of 5 to 10 leaves headroom for bursts without allowing a flood. Use Little's law: concurrency equals arrival rate times time per call.

Check it with the contract: some partners state a limit on parallel connections, and that number is your ceiling.

Then watch the effect: if callers wait a lot (the time in the method exceeds the call time), the limit is too low for the traffic, or the dependency is too slow. Both are signals to act on, not to hide.

Change it with data from a load test, and keep it in configuration where possible, so you can lower it during an incident.

Drill · Circuit breakers and resilience design

The last three questions of the resilience group move from single settings to whole designs: a breaker's states and tuning, and a complete protection plan for one flaky payment gateway. Section 06 has the demos behind them.

Q51. "Explain the circuit breaker's three states and its key settings."

Reveal answer

The real test Whether you can say that the breaker is about refusing calls to protect threads, not about retrying, and name the settings that decide when it trips and when it recovers.

Strong answer A circuit breaker is a small state machine wrapped around a remote call. Its job is to stop you from hammering a dependency that is already failing. Think of the fuse box at home: when too much current flows, the fuse trips, and nothing flows until someone resets it. The breaker does the same for calls, and it resets itself by testing carefully.

It has three states. CLOSED is normal: every call goes through, and the breaker quietly records whether each call succeeded, failed or was slow. OPEN means "stop calling": the breaker rejects every call at once, without touching the network, and throws a CallNotPermittedException that your fallback can catch. HALF_OPEN is the test: after a wait, the breaker lets a few probe calls through. If enough of them succeed it goes back to CLOSED. If they fail it goes back to OPEN for another wait.

The settings you must know in Resilience4j (see section 06) are these:

  • slidingWindowType and slidingWindowSize: what counts as "recent". COUNT_BASED looks at the last N calls. TIME_BASED looks at the last N seconds.
  • minimumNumberOfCalls: how many calls must be in the window before the failure rate is judged at all. Without it, 1 failure out of 1 call is "100 %" and trips the breaker.
  • failureRateThreshold: the percentage of failed calls that trips it (default 50).
  • slowCallDurationThreshold and slowCallRateThreshold: a call slower than the threshold counts as slow, and too many slow calls trip the breaker even when none fail.
  • waitDurationInOpenState: how long OPEN lasts before the breaker tries HALF_OPEN.
  • permittedNumberOfCallsInHalfOpenState: how many probe calls are allowed.
  • recordExceptions and ignoreExceptions: which exceptions count as failures. A "card declined" is the customer's problem, not an outage.

The point to say out loud: a breaker does not retry and does not fix anything. It limits damage and gives the dependency room to recover. Retries try again; a breaker decides whether to try at all.

Picture it

The setup: The payment breaker from the #resilience demo has a window of 6 calls, needs at least 4 calls before it judges, trips at 50 % failures, waits 1 s in OPEN and allows 2 probe calls. A fake gateway is down for the first seven orders, then recovers.

application.yml · Boot 4.2runs offline
resilience4j:
  circuitbreaker:
    instances:
      payment:
        sliding-window-type: COUNT_BASED
        sliding-window-size: 6
        minimum-number-of-calls: 4
        failure-rate-threshold: 50
        wait-duration-in-open-state: 1s
        permitted-number-of-calls-in-half-open-state: 2

Make the invisible visible: Print every call and every state change, in order.

run --demo=breaker · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
--- gateway is DOWN ---
  call 1 at   26 ms (pay o-1)
pay #1 -> QUEUED (503 Service Unavailable)
  call 2 at   39 ms (pay o-2)
pay #2 -> QUEUED (503 Service Unavailable)
  call 3 at   41 ms (pay o-3)
pay #3 -> QUEUED (503 Service Unavailable)
  call 4 at   46 ms (pay o-4)
  >>> state State transition from CLOSED to OPEN at 55 ms
pay #4 -> QUEUED (503 Service Unavailable)
pay #5 -> QUEUED (breaker open, call skipped)
pay #6 -> QUEUED (breaker open, call skipped)
pay #7 -> QUEUED (breaker open, call skipped)
--- gateway recovers; waiting 1.2 s (open wait is 1 s) ---
  >>> state State transition from OPEN to HALF_OPEN at 1268 ms
  call 5 at 1269 ms (pay o-8)
pay #8 -> OK
  call 6 at 1271 ms (pay o-9)
  >>> state State transition from HALF_OPEN to CLOSED at 1272 ms
pay #9 -> OK
  call 7 at 1273 ms (pay o-10)
pay #10 -> OK

What you see: Four failed calls fill the minimum, the failure rate is 100 %, and the breaker goes CLOSED to OPEN at 55 ms. Orders 5 to 7 are answered with no call at all ("breaker open, call skipped"). After the 1 s wait, the first call after 1,268 ms flips it to HALF_OPEN, two probes succeed, and it closes at 1,272 ms.

Why: OPEN does not time out on its own thread. By default the move to HALF_OPEN happens when the next call arrives after the wait, which is why the transition is stamped at the moment of order 8. automaticTransitionFromOpenToHalfOpenEnabled(true) moves it on a timer instead.

No breaker

Every call pays the full timeout while the gateway is down.

Checkout.java · Boot 4.2runs offline
for (Order o : orders) {
    try { gateway.charge(o); }
    catch (IOException e) {
        queue.add(o);   // after 500 ms
    }
}

With a breaker

After the trip, calls are refused in microseconds.

Checkout.java · Boot 4.2runs offline
@CircuitBreaker(name = "payment",
    fallbackMethod = "queue")
String charge(Order o) {
    return gateway.charge(o);
}
String queue(Order o, Throwable t) {
    return "QUEUED";
}

The shift: A breaker turns "wait for every timeout" into "fail at once, then probe".

StateCallsLeaves it when
CLOSEDAll pass; outcomes recordedFailure or slow-call rate crosses its threshold after the minimum calls
OPENAll rejected, no networkwaitDurationInOpenState has passed
HALF_OPENOnly the permitted probes passProbes succeed (to CLOSED) or fail (back to OPEN)

Land it I describe a breaker as a fuse with a self-test: closed passes calls, open refuses them, half-open lets a few probes decide.

Likely follow-ups
"What is the difference between a count-based and a time-based window?"

A count-based window keeps the outcome of the last N calls, whatever the clock says. With slidingWindowSize=6 the breaker always judges the six most recent calls. A time-based window keeps every call from the last N seconds and groups them in one-second buckets.

Pick count-based for a steady call rate, like the payment gateway, because the judgement is always about the same amount of evidence. Pick time-based when traffic swings. At 3 a.m. a count-based window of 100 calls may stretch over an hour of old data, so an outage ten minutes ago still counts. A time-based window of 60 seconds forgets it.

The catch with time-based windows is the opposite one: a quiet minute may hold only two calls. That is why minimumNumberOfCalls exists. With a minimum of 20, two failures in a quiet minute change nothing.

In the demo above I used count-based (6 calls, minimum 4) because I wanted the trip to be easy to read in a 12-line log. In production I would start with time-based, 30 to 60 seconds, a minimum of 20 calls, and check the numbers against real traffic.

"Why does the breaker count slow calls, not only failures?"

Because a slow dependency hurts you as much as a dead one, and often more. A dead gateway returns 503 in 20 ms; you fail fast and move on. A gateway that answers in 8 seconds holds a thread for 8 seconds on every call. With 200 request threads and 30 calls a second, all 200 threads are stuck within seven seconds, and your whole service stops, including endpoints that never touch the gateway.

slowCallDurationThreshold=2s marks any call over two seconds as slow. slowCallRateThreshold=60 trips the breaker when 60 % of the calls in the window were slow, even if every one eventually returned 200. The breaker then protects your threads from the slowness.

This only works together with a timeout. The breaker measures how long a call took, but it cannot cancel it. The HTTP client timeout (see the next questions and Q53) cuts the call, and the breaker reads the result as a failure or a slow call.

My rule: set the client timeout to a bit above the 99th percentile of normal latency, and set the slow-call threshold a bit below the timeout.

"Does a rejected call count as a failure in the window?"

No. A call that the breaker rejects while OPEN never reached the dependency, so it is not recorded as a failure. It is counted separately as a notPermittedCall, and you can see that number in the Actuator output.

That is by design. If rejected calls counted, the failure rate would stay at 100 % forever and the breaker could never close. In HALF_OPEN the breaker starts a fresh, small window made only of the probe calls and judges those.

Here is the Actuator view from the same demo, taken while the breaker was open:

GET /actuator/circuitbreakers · Boot 4.2 (C/ folder)runs offline
{"circuitBreakers":{"payment":{"bufferedCalls":4,"failedCalls":4,
 "failureRate":"100.0%","failureRateThreshold":"50.0%",
 "notPermittedCalls":1,"state":"OPEN"}}}

Four buffered calls, four failures, and one notPermittedCall. The overall /actuator/health status of the app showed UNKNOWN in the same run, with the breaker reported as CIRCUIT_OPEN and HTTP 200. An open breaker does not mark the application down by default, and that is usually what you want: you keep serving everything that does not need payments.

"Where do you put the fallback, and what should it do?"

The fallback is a method with the same signature plus a Throwable parameter, named in fallbackMethod. Resilience4j calls it when the protected call fails or the breaker is open. You can add overloads for specific exception types, and the most specific one wins.

What it should do depends on the business, and you need to decide that before coding. For payments, a sensible fallback is "accept the order, mark the payment as pending, and charge later from a queue". For menu prices, "serve the last cached value". For recommendations, "return an empty list". Returning fake success is the one thing a fallback must never do for money.

Keep the fallback cheap and independent. If the fallback calls another remote service, it needs its own breaker. A fallback that throws makes the caller see that exception, so it should not.

Also remember the fallback hides the failure from the caller. Log it and count it (a metric tagged with the breaker name), or you will learn about a week-long outage from a customer. The idiom is Circuit breaker with a fallback.

Q52 · Scenario. "A circuit breaker opened during a 30-second blip and stayed open for 5 minutes. Tune it."

Reveal answer

Strong answer Start by reading the story: the gateway was broken for 30 seconds, but the service refused payments for 5 minutes. Four and a half minutes of refusal were self-inflicted. The most likely cause is waitDurationInOpenState=300s: the breaker did exactly what it was told. Someone copied a number from a blog post, or set "5 minutes" thinking of a big outage.

The fix is in four parts.

  1. Shorten the open wait: set waitDurationInOpenState to 10 to 20 seconds. The wait is the price of a wrong trip, so it should be about as long as a typical short blip, not a long outage.
  2. Probe cheaply: keep permittedNumberOfCallsInHalfOpenState small (3 to 5) and add maxWaitDurationInHalfOpenState so a half-open breaker that gets no traffic does not sit there forever.
  3. Do not trip on tiny samples: raise minimumNumberOfCalls (20 on a time-based window) so that three failures in a quiet minute cannot open it.
  4. Trip on the right failures: use recordExceptions for timeouts and 5xx, and ignoreExceptions for 4xx and business errors. A burst of "card declined" must not open the breaker.

Then prove the tuning with a test that you can run in seconds, not by waiting for production. In the demo below I scaled time down 50 times: the 30-second blip became 600 ms, and the 5-minute wait became 6 seconds (A), against a 20-second wait that became 400 ms (B). A call arrives every 50 ms.

One more design question: should the breaker ever stay open for minutes? Yes, but only through a different mechanism. If the gateway is truly down for an hour, the breaker with a 20-second wait will probe every 20 seconds, fail, and re-open. That costs three probe calls per 20 seconds, which is nothing. A short wait is cheap and safe, because HALF_OPEN protects you.

Picture it

The setup: A programmatic Resilience4j breaker (window of 10 calls, minimum 5, trip at 50 %). The fake gateway is down from 0 to 600 ms (the scaled 30-second blip). One payment attempt every 50 ms. Three configurations differ only in the open wait.

BreakerTune.java (excerpt) · Boot 4.2runs offline
CircuitBreakerConfig.custom()
    .slidingWindowSize(10).minimumNumberOfCalls(5)
    .failureRateThreshold(50)
    .waitDurationInOpenState(Duration.ofSeconds(6)) // A
    // .waitDurationInOpenState(Duration.ofMillis(400)) // B
    // + .automaticTransitionFromOpenToHalfOpenEnabled(true) // C
    .permittedNumberOfCallsInHalfOpenState(3).build();

Make the invisible visible: Run the three scenarios and compare when the first good payment goes through.

run --demo=breaker-tune · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
--- A: waitDurationInOpenState = 6 s (the '5 minutes' setting, scaled)
    220 ms  State transition from CLOSED to OPEN
   6264 ms  State transition from OPEN to HALF_OPEN
  gateway back at 600 ms, first successful payment at 6262 ms, calls refused after recovery: 111

--- B: waitDurationInOpenState = 400 ms (the '20 seconds' setting, scaled)
    202 ms  State transition from CLOSED to OPEN
    609 ms  State transition from OPEN to HALF_OPEN
  gateway back at 600 ms, first successful payment at 609 ms, calls refused after recovery: 0

--- C: B plus automatic open to half-open (no call needed to trigger it)
    205 ms  State transition from CLOSED to OPEN
    606 ms  State transition from OPEN to HALF_OPEN
  gateway back at 600 ms, first successful payment at 610 ms, calls refused after recovery: 0
// scaled 50x: 600 ms here = 30 s in production

What you see: All three open at about 200 ms, because five calls in the window were failures. The gateway comes back at 600 ms. Configuration A is still open: its first good payment is at 6,262 ms, and 111 payment attempts were refused after the gateway was already healthy. Configurations B and C move to HALF_OPEN at 609 and 606 ms and pay at once.

Why: In A the breaker is blind during the whole wait. It cannot know the gateway is back, because it is not calling it. The wait is the only thing between the recovery and the first probe. Scaling back up: a 5-minute wait means about 5,500 refused attempts at 20 per second, for a 30-second problem.

Over-cautious

A long wait that outlives the problem.

application.yml · Boot 4.2runs offline
wait-duration-in-open-state: 300s
minimum-number-of-calls: 2
failure-rate-threshold: 50
record-exceptions: []

Tuned

Short wait, enough evidence, only real failures.

application.yml · Boot 4.2runs offline
wait-duration-in-open-state: 20s
minimum-number-of-calls: 20
failure-rate-threshold: 50
ignore-exceptions:
  - com.quickbite.CardDeclined

The shift: Keep the wait near the length of a short blip and let probes, not minutes, decide recovery.

Land it I tune a breaker by shortening the open wait to blip length, raising the minimum sample, filtering which exceptions count, and proving it with a time-scaled test.

Likely follow-ups
"How do you choose the number for waitDurationInOpenState?"

Look at your own incident history. If gateway blips usually last 10 to 40 seconds, a wait of 15 to 20 seconds means that one wrong trip costs you at most one extra half-open cycle. If the dependency is a nightly partner batch that is down for an hour, 60 seconds is fine.

The wait trades two costs. A short wait means more probe calls against a dependency that is still sick: with permittedNumberOfCallsInHalfOpenState=3 and a 15 s wait that is 12 probe calls a minute, which no gateway will notice. A long wait means longer refusal after recovery, which the customer sees as lost sales.

Add a business view: how much does one refused payment cost, against how much does one extra probe cost? Probes cost microseconds; refused payments cost money. So bias short.

Never leave the default unexamined. Resilience4j's default is 60 seconds, which suits few real services. Write the number down in the config with a comment that says why.

"Should the breaker be automatic (automaticTransitionFromOpenToHalfOpenEnabled)?"

Without it, the move from OPEN to HALF_OPEN happens when a call arrives after the wait has passed. With it, a background thread does the move on a timer. In the demo above both B and C paid at about 610 ms, because calls arrive every 50 ms in this test and the difference is invisible.

It matters when traffic is low. Imagine one payment every two minutes and a 20-second wait. Without the automatic move the state shows OPEN on the dashboard for minutes after the wait ended, because no call has come to flip it. Dashboards and health indicators then tell a false story.

The cost is one scheduled thread per such breaker (Resilience4j uses a shared scheduler), which is small. I enable it for breakers that I expose in health or alerts and leave it off for chatty, high-traffic ones where the first call flips it within milliseconds anyway.

"The breaker never opens even though the gateway is failing. What do you check?"

Work through the usual causes in order.

  1. Minimum calls: minimumNumberOfCalls may be higher than the traffic. A window of 100 with a minimum of 50 does nothing during a quiet hour.
  2. Exception filters: your failures may be in ignoreExceptions, or an exception thrown by your own wrapper is not in recordExceptions, so the breaker sees success.
  3. Fallback placement: if a try/catch inside the protected method swallows the error and returns a default, the breaker sees a successful call. The failure must leave the method.
  4. Proxy: the annotation sits on a method called from the same class (self-invocation, see section 02), so no advice runs. Check the bean class for $$SpringCGLIB$$.
  5. Aspect order: if retry wraps the breaker, each retry is a separate recorded call; if the breaker wraps retry, only the final result is recorded. Know which one you have.

I check with /actuator/circuitbreakers first: if bufferedCalls stays at 0, the advice is not running at all, and the cause is in step 4. If it grows but the rate stays low, the cause is in step 2.

"How do you test breaker tuning without waiting minutes?"

Scale time down, as the demo did: create the breaker programmatically with the same ratios (a wait of 400 ms instead of 20 s) and drive it with a fake dependency that fails during a scripted window. The code is about 30 lines and runs in 8 seconds.

For the real annotation, load a test profile with short durations (wait-duration-in-open-state: 300ms) and a fake gateway bean, then assert on transitions through the event publisher: breaker.getEventPublisher().onStateTransition(...) collects the changes, and the test checks the order CLOSED, OPEN, HALF_OPEN, CLOSED.

Add one more test for the unhappy path: a gateway that stays down. The assertion is that the breaker goes back to OPEN after the probes and that the fallback is called each time.

Finally, a load test in a staging environment with a real outage simulated (stop the gateway stub for 30 seconds) is worth doing once. It catches the parts a unit test cannot: connection pool exhaustion and timeouts that are longer than you thought.

Q53 · Design. "Design resilience for calls to a flaky payment gateway: timeouts, retries, breaker, fallback and idempotency."

Reveal answer

The real test Whether you start from the failure modes and the idempotency key, not from the annotation names, and can say what the customer sees at each layer.

Strong answer I design this as layers, from the inside out, and each layer answers a different question. The order matters, so I write it down before any code.

  1. Timeout (inside): how long will I wait for one call? A hard limit, set a little above the normal 99th percentile, say 2 seconds for a 300 ms gateway. Without it nothing below works: retries and breakers cannot react to a call that never returns.
  2. Idempotency key (on the request): can I safely send this again? One key per order, sent as an Idempotency-Key header, and the gateway returns the first result for a repeated key. See E20 idempotency keys.
  3. Retry (around the timeout): is the failure probably temporary? Retry only transient errors (timeouts, 502, 503), at most 2 or 3 times, with exponential backoff and jitter (Q49). Never retry 4xx.
  4. Circuit breaker (around the retries): has this dependency been failing for a while? If so, stop calling it. Count the final result of the retried call as one outcome.
  5. Concurrency limit or bulkhead (outermost): how many calls may be waiting at once? A cap of, say, 30 stops a slow gateway from using all request threads.
  6. Fallback (outermost): what does the customer get when all of this fails? For payments: accept the order as PAYMENT_PENDING and put it on a durable queue, never a fake "paid".

Then the pieces around the code: metrics for every layer (retries, breaker state, queue depth), an alert on "breaker open for over 5 minutes", a reconciliation job that compares our records with the gateway's settlement report, and a runbook.

The honest limit: this design makes failures rare and safe, not impossible. The reconciliation job is the safety net for the case where the timeout hid a charge that we never recorded.

Picture it

The setup: A fake gateway with four behaviours: healthy, two 503s then healthy, "takes the money but answers after 400 ms" (our timeout is 200 ms) and down. The client has a 200 ms timeout, up to 3 attempts with backoff plus jitter, a breaker (window 6, minimum 4) and a fallback that queues the order. Idempotency keys are switchable.

Gateway.java (excerpt) · Java 25, Resilience4j 2.4runs offline
for (int attempt = 1; attempt <= 3; attempt++) {
    try {
        String r = cb.executeCheckedSupplier(
            () -> callWithTimeout(order, key));
        return "PAID " + r + " (attempt " + attempt + ")";
    } catch (CallNotPermittedException e) {
        return "FALLBACK queued (breaker open, no call made)";
    } catch (Throwable e) {
        sleep(delay + jitter());
        delay *= 2;
    }
}
return "FALLBACK queued (retries exhausted)";

Make the invisible visible: Run the six scenarios in order.

run --demo=gateway · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
1. healthy gateway
   -> PAID receipt-1 (attempt 1)   charges=1
2. two 503s, then fine
    attempt 1 failed: 503
    attempt 2 failed: 503
   -> PAID receipt-1 (attempt 3)   charges=1
3. money taken but answer arrives after our 200 ms timeout, WITHOUT a key
    attempt 1 failed: timeout after 200 ms
    attempt 2 failed: timeout after 200 ms
    attempt 3 failed: timeout after 200 ms
   -> FALLBACK queued (retries exhausted)   charges=3
3b. the same, WITH an idempotency key
    attempt 1 failed: timeout after 200 ms
    attempt 2 failed: timeout after 200 ms
   -> PAID receipt-1 (replayed) (attempt 3)   charges=1
4. gateway down: five orders in a row
    attempt 1 failed: 503
    attempt 2 failed: 503
    attempt 3 failed: 503
   o-4 -> FALLBACK queued (retries exhausted)  [371 ms, breaker CLOSED]
    attempt 1 failed: 503
   o-5 -> FALLBACK queued (breaker open, no call made)  [68 ms, breaker OPEN]
   o-6 -> FALLBACK queued (breaker open, no call made)  [0 ms, breaker OPEN]
   o-7 -> FALLBACK queued (breaker open, no call made)  [0 ms, breaker OPEN]
   o-8 -> FALLBACK queued (breaker open, no call made)  [0 ms, breaker OPEN]

What you see: Scenario 2: two failures, success on attempt 3, one charge. Scenario 3 without a key: three timeouts, three real charges, and the order still ends in the queue, so the customer was charged three times and told "pending". With a key (3b) the third attempt returns the first receipt, marked replayed, one charge. Scenario 4: the first order burns 371 ms on three attempts, the second opens the breaker, and orders 6 to 8 are queued in 0 ms.

Why: A timeout is not a failure of the payment; it is a failure to learn the answer. Only a stable key lets the gateway turn "I do not know" into "ask again and I will tell you what happened". Retrying without a key trades one risk (a lost payment) for a worse one (a duplicate charge).

Retry only

A loop that retries every error three times.

Pay.java · Java 25runs offline
for (int i = 0; i < 3; i++) {
    try { return gw.charge(o); }
    catch (Exception e) { sleep(50); }
}
throw new PaymentFailed(o);

Layered

Key, timeout, backoff, breaker and fallback.

Pay.java · Java 25runs offline
@CircuitBreaker(name = "pay",
    fallbackMethod = "queue")
@Retryable(maxRetries = 2, delay = 100,
    multiplier = 2, jitter = 20,
    includes = IOException.class)
String charge(Order o) {
    return gw.charge(o, "key-" + o.id());
}

The shift: Resilience is a stack of small decisions, each answering one question, not a single retry loop.

Land it I answer a flaky gateway with a timeout, an idempotency key, bounded retries with jitter, a breaker around the retries and a queue as the fallback.

Likely follow-ups
"Which layer wraps which, and why does the order matter?"

The usual order, from outside to inside, is: fallback, concurrency limit, circuit breaker, retry, timeout, call. Resilience4j's own documented default aspect order is retry outermost (Retry, then CircuitBreaker, then RateLimiter, TimeLimiter, Bulkhead), so check your version if you rely on it. Both orders can work; the difference is what the breaker counts. One catch on Boot 4.2: when both annotations sit on the same bean, the Framework 7 @Retryable advice is outermost, so to put the breaker around the retries you put the breaker on a separate calling bean.

If the breaker wraps the retry, one retried call (three attempts, then failure) is one failed outcome in the window. The breaker reacts to "the whole operation failed", which is slower to trip but ignores brief blips that retry already fixed.

If retry wraps the breaker, each attempt is a separate outcome. A blip that retry fixes still leaves failures in the window, so the breaker trips earlier, and during OPEN the retries hit CallNotPermittedException three times in a row, wasting time unless you exclude that exception from retry.

Spring Framework 7's @Retryable is always the outermost advice by its own rule (see section 03). In the demo I put the breaker inside the loop to see each outcome; choose deliberately, and test it.

"What do you do about the charge that timed out and never got recorded?"

That is the hole every design has. Our client gave up after 200 ms, but the gateway may have charged the card at 190 ms. The idempotency key lets a retry find out; it does not help if we never retry, for example after all attempts fail.

So the fallback must keep the key. The queued order carries key-o-3, and the worker that processes the queue sends the same key. The gateway then replays the first result if the money was taken and does a fresh charge if not.

On top of that, run a reconciliation job every night: fetch the gateway's settlement list, match it to our orders by key, and report the mismatches (charged by the gateway, not paid with us, or the opposite). A small number of manual refunds is normal and cheap.

Never answer a timeout with "payment failed, try again" to the customer without using the same key. That is how duplicate charges reach the customer's bank statement.

"How do you size the timeout, the retry count and the concurrency limit together?"

Start from the user's patience and work backwards. The checkout page may wait 6 seconds in total. With a 2-second timeout and 2 retries (three attempts) plus backoff of about 100 ms and 200 ms, the worst case is 6.3 seconds. That is already too long, so cut the timeout to 1.5 s or the retries to 1.

Then the limit. By Little's law, the number of calls in flight equals the arrival rate times the time each takes. At 40 payments a second and 300 ms normal latency that is 12 in flight. A cap of 30 gives headroom for a bad day. If the gateway slows to 2 seconds, the cap is reached after under a second, and further calls are rejected quickly instead of piling up on all 200 request threads.

Each retry multiplies the load on a struggling gateway by up to three. With a 2 % normal error rate that is fine; during an outage the breaker is what stops the multiplication. So the retry count is safe only together with the breaker, and the numbers must be reviewed as one set.

"How would you test this design before production?"

In three layers. First unit tests with a fake gateway that you can script: fail twice then succeed, hang forever, take the money and then time out. These are the scenarios from the demo, and each one asserts both the result and the count of charges. The charge counter is the assertion that matters.

Second, a component test with a real HTTP stub (WireMock or a MockWebServer) with delays and 503 responses, to exercise the real RestClient timeouts, not only the Java code. A spring.http.clients.read-timeout setting that is silently ignored is a classic find.

Third, a game day in staging: block the gateway stub for 60 seconds under load and watch the dashboards. You should see retries rise, the breaker open within seconds, the queue grow, and then drain after recovery with no duplicate charges in the reconciliation report.

Write down what you saw. Next quarter's team will not remember, and the numbers (time to trip, time to recover) are what you tune against.

Drill · Scheduling, events, security and validation

These twelve questions cover the annotations that look harmless on a single line and misbehave in a fleet: timers, events, method security, validation, metrics, laziness and profiles. The last one asks you to review a service that carries five of them.

Q54. "fixedRate versus fixedDelay versus cron — and what happens when a run takes longer than the interval?"

Reveal answer

The real test Whether you can say what each mode measures from, and predict the schedule of a run that overruns, rather than reciting the attribute names.

Strong answer All three tell Spring when to call a method, and they differ in what they measure from. fixedRate measures from the start of one run to the start of the next: "every 1 second, on the clock". fixedDelay measures from the end of one run to the start of the next: "1 second of rest after each run". cron uses calendar times: "at 02:00 every night", with a zone so that the pod's time zone does not matter.

The interesting part is a run that is longer than the interval. With the default scheduler there is one thread, so a method never overlaps itself, and the three modes handle the overrun differently:

  • fixedRate=1000 with a 1.5 s task: the next run is already due when the first ends, so it starts at once. Runs go back to back and the schedule falls behind and never catches up.
  • fixedDelay=1000 with a 1.5 s task: each run is followed by a full second of rest, so the cycle is 2.5 s. It cannot pile up, by construction.
  • cron every 2 seconds with a 3 s task: the tick that came while the job was running is skipped. The next run waits for the next tick after the end.

My rule: use fixedDelay for polling and cleanup, where "do not overlap and do not pile up" is the right behaviour. Use cron for business times (nightly invoices, a morning report). Use fixedRate only when the rate itself matters (sampling a gauge each second) and the work is clearly shorter than the interval. This is fixedDelay for polling.

Two more facts to know. initialDelay postpones only the first run. And with virtual threads (spring.threads.virtual.enabled=true) the picture changes for fixedRate: runs can overlap themselves, as the demo shows, while fixedDelay still waits for the previous run to end.

Picture it

The setup: One task sleeps 1.5 s and prints its start and end. The same task is scheduled three ways: fixedRate=1000, fixedDelay=1000 and cron="*/2 * * * * *" (the cron run sleeps 3 s). One app run per mode; the timestamps are milliseconds since the first start.

SchedDemos.java (excerpt) · Boot 4.2runs offline
@Scheduled(fixedRate = 1000)
void rate() { slow("invoices", 1500); }

@Scheduled(fixedDelay = 1000, initialDelay = 500)
void delay() { slow("invoices", 1500); }

@Scheduled(cron = "*/2 * * * * *", zone = "Asia/Kolkata")
void cron() { slow("invoices", 3000); }

Make the invisible visible: Look at the start and end times of three runs in each mode.

run --demo=rate · fixedDelay · cron · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
# fixedRate = 1000, task takes 1500
    0 ms [scheduling-1] start invoices
 1501 ms [scheduling-1]   end invoices (took 1500)
 1504 ms [scheduling-1] start invoices
 3004 ms [scheduling-1]   end invoices (took 1500)
 3005 ms [scheduling-1] start invoices

# fixedDelay = 1000, task takes 1500
    0 ms [scheduling-1] start invoices
 1502 ms [scheduling-1]   end invoices (took 1500)
 2510 ms [scheduling-1] start invoices
 4011 ms [scheduling-1]   end invoices (took 1500)
 5013 ms [scheduling-1] start invoices

# cron every 2 s, task takes 3000
    0 ms [scheduling-1] start invoices
 3003 ms [scheduling-1]   end invoices (took 3000)
 3992 ms [scheduling-1] start invoices
 6993 ms [scheduling-1]   end invoices (took 3000)
 7990 ms [scheduling-1] start invoices

What you see: fixedRate: the second run starts 3 ms after the first ends, and every later start is back to back, never on the 1 s grid. fixedDelay: the second run starts at 2,510 ms, about 1 s after the first ended at 1,502. cron: the run started at 0 ends at 3,003; the tick at 2 s was missed, and the next run starts at about 3,992 ms (the 4 s tick, a few milliseconds early in this measurement).

Why: Spring's scheduler keeps one thread. A due task waits for the thread, and the three modes compute "next due" from different anchors: the scheduled time (fixedRate), the end time (fixedDelay) or the calendar (cron).

fixedRate

Starts are planned from the previous start.

Rate.java · Boot 4.2runs offline
// 1 s grid, task takes 1.5 s
@Scheduled(fixedRate = 1000)
void run() { slow(1500); }
// runs: 0.0-1.5, 1.5-3.0,
//       3.0-4.5  (back to back)

fixedDelay

Starts are planned from the previous end.

Delay.java · Boot 4.2runs offline
// 1 s rest after each run
@Scheduled(fixedDelay = 1000)
void run() { slow(1500); }
// runs: 0.0-1.5, 2.5-4.0,
//       5.0-6.5  (never piles up)

The shift: Rate follows the clock and can run flat out; delay follows the work and always rests.

Land it I pick fixedDelay for polling, cron for business times, and fixedRate only when the work is clearly shorter than the interval.

Likely follow-ups
"Does Spring skip or queue a fixedRate run that is late?"

It does not skip it; it runs it late. A fixedRate task is rescheduled for "previous scheduled start plus 1 second", so once the first run overruns, every following run is already overdue and starts the moment the thread is free. In the demo the starts were at 0, 1,504, 3,005 and 4,507 ms, 1.5 s apart, which is the task's own length, not the 1 s you asked for.

Nothing is dropped, and nothing queues up more than one run: the scheduler holds only the next due time. So a task that is permanently slower than its rate runs continuously and uses a thread constantly. That is the surprise: a 90-second run of a fixedRate=60000 job means it never rests.

If you need "never run late runs, just wait for the next slot", use cron, which skips past ticks. If you need "always rest", use fixedDelay.

"How do you run a job at 02:00 in a given time zone?"

Use a cron expression with a zone: @Scheduled(cron = "0 0 2 * * *", zone = "Asia/Kolkata"). Spring's cron has six fields, with seconds first: second, minute, hour, day of month, month, day of week. A five-field Unix cron line will not parse.

Without zone the job uses the JVM's default zone, which in a container is usually UTC, and changes if somebody sets TZ. A job meant for 02:00 India time then runs at 07:30 India time, or twice a year at the wrong hour around daylight saving changes elsewhere. Always write the zone.

Externalise the expression: cron = "${quickbite.invoice.cron:0 0 2 * * *}" lets operations change the time with a property, and a value of - disables the job. Remember that in a multi-pod deployment every pod fires at 02:00, so the job still needs a lock (Q56).

"What is initialDelay for, and does it apply to cron?"

initialDelay postpones the first run of fixedRate and fixedDelay tasks by a number of milliseconds (or a duration string). It is useful so that a cache-warming or polling task does not compete with application start-up: initialDelay = 30000 means "wait half a minute after the context starts".

It does not apply to cron, whose first run is simply the next matching time. If the app starts at 01:59:59 a 0 0 2 * * * job runs one second later, before your warm-up has finished. If that matters, guard the job with a readiness flag or schedule programmatically with TaskScheduler after ApplicationReadyEvent (see section 08 for what runs when).

Also remember that the delay is counted from when the scheduler starts, not from when the task method was first reachable.

"What changes when spring.threads.virtual.enabled=true?"

The scheduler stops being a single platform thread and starts each run on a new virtual thread. The measured effect (see the #scheduling demos) is that two different jobs no longer block each other, and a fixedRate job that overruns now starts the next run on time, in parallel with the running one. Overlapping runs appear: with a 1.5 s task and a 1 s rate the output shows runs on scheduling-2, scheduling-3, scheduling-4, overlapping.

fixedDelay and cron do not overlap themselves, because the next run is computed after the previous one completes. Only fixedRate can overlap.

So switching to virtual threads is not a free upgrade for a scheduled job that assumed single-threaded behaviour. Review every fixedRate method: if overlap would corrupt data, change it to fixedDelay, or guard it with a lock (AtomicBoolean for one JVM, ShedLock across pods).

Q55 · Scenario. "Two @Scheduled jobs block each other. Why?"

Reveal answer

Strong answer The cause is the default scheduler. Spring's @EnableScheduling registers a ThreadPoolTaskScheduler with a pool size of one. Every @Scheduled method in the whole application, from every bean, shares that single thread. A job that runs for 3 seconds holds the thread for 3 seconds, and everything else waits: a heartbeat scheduled every second does not fire, and then fires late or in a burst.

This was exactly the incident: a slow report with fixedRate=60s ran for 90 seconds and the other job, which looked unrelated, stopped on time. Nothing in the logs is wrong. The scheduler did what a one-thread scheduler does.

There are three fixes, and they suit different situations.

  1. Give the scheduler more threads: spring.task.scheduling.pool.size=2 (or 5). Simple and predictable. The size is a limit you must choose; two slow jobs plus a heartbeat need at least 3 to be safe.
  2. Use virtual threads: spring.threads.virtual.enabled=true. Each run gets its own virtual thread, so nothing blocks anything. The catch (Q54): fixedRate jobs can now overlap themselves.
  3. Make the slow job fast or move it away: split the work, hand it to a bounded executor with @Async, or run it as a batch job in a separate process. A scheduler thread should start work, not do hours of it.

Measure rather than guess. In the demo below a heartbeat every second and a 3 s report run together. With one thread the heartbeat is silent for 3 seconds at a time; with a pool of 2 it beats every second; with virtual threads both run freely.

Mind one more trap. If the slow job uses @Async to escape the scheduler, the scheduler thread returns at once, and the next tick starts another copy while the first is still running, so you need your own overlap guard.

Picture it

The setup: Two jobs, both fixedRate=1000: heartbeat() prints a line, slowReport() sleeps 3 s. Three runs differ only in scheduler settings.

application.properties · Boot 4.2runs offline
# run 1: nothing set (one scheduler thread)
# run 2:
spring.task.scheduling.pool.size=2
# run 3:
spring.threads.virtual.enabled=true

Make the invisible visible: Compare the heartbeat lines in the three runs.

run --demo=twojobs · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
# one thread
    0 ms [scheduling-1] heartbeat
    5 ms [scheduling-1] slowReport start (virtual=false)
 3006 ms [scheduling-1] slowReport end
 3011 ms [scheduling-1] heartbeat
 3016 ms [scheduling-1] slowReport start (virtual=false)
 6018 ms [scheduling-1] slowReport end
 6020 ms [scheduling-1] heartbeat
 6022 ms [scheduling-1] slowReport start (virtual=false)

# pool.size=2
    0 ms [scheduling-2] slowReport start (virtual=false)
    1 ms [scheduling-1] heartbeat
  976 ms [scheduling-1] heartbeat
 1975 ms [scheduling-1] heartbeat
 2975 ms [scheduling-1] heartbeat
 3001 ms [scheduling-2] slowReport end
 3002 ms [scheduling-2] slowReport start (virtual=false)
 3975 ms [scheduling-1] heartbeat

# virtual threads
    0 ms [scheduling-2] heartbeat
    0 ms [scheduling-3] slowReport start (virtual=true)
  967 ms [scheduling-4] heartbeat
  974 ms [scheduling-5] slowReport start (virtual=true)
 1965 ms [scheduling-6] heartbeat
 1974 ms [scheduling-7] slowReport start (virtual=true)
 2971 ms [scheduling-8] heartbeat
 2974 ms [scheduling-9] slowReport start (virtual=true)

What you see: One thread: the heartbeat prints at 0 ms, then not again until 3,011 ms, after the report ended. Pool of 2: the heartbeat prints at 0, 976, 1,975 and 2,975 ms while the report runs on scheduling-2. Virtual threads: every run has a new thread name, and the report starts again at 974 ms while the first run is still going (overlap).

Why: With one thread, "due" does not mean "running": a task waits in the scheduler's queue behind the long one. A second thread removes the queue; virtual threads remove the pool size altogether.

One thread (default)

A slow job starves the heartbeat.

application.propertiesruns offline
# nothing configured
# scheduling-1 runs everything:
#  report 0 - 3000 ms
#  heartbeat waits until 3011 ms

Pool of two

The heartbeat keeps its own slot.

application.propertiesruns offline
spring.task.scheduling.pool.size=2
# scheduling-1: heartbeat
# scheduling-2: report
#  heartbeat every ~1000 ms

The shift: Size the scheduler for the slowest job plus the jobs that must stay punctual.

Land it I give the scheduler enough threads for its slowest job, and I keep scheduled methods short by moving long work into a bounded executor or a separate job.

Likely follow-ups
"How big should spring.task.scheduling.pool.size be?"

Count the jobs that can run at the same moment in the worst case, add one for safety, and stay small. With a nightly invoice job (1 hour), a heartbeat and a cleanup, the worst case is three at once, so 4. A pool of 50 is rarely needed and hides design problems.

Remember that a bigger pool does not make a single job faster; it only stops jobs from blocking each other. If one job needs parallel work inside itself, give it its own executor.

Also check that the pool thread name prefix is helpful: spring.task.scheduling.thread-name-prefix=qb-sched- makes thread dumps readable. And set spring.task.scheduling.shutdown.await-termination=true so a deploy waits for a running job instead of cutting it off.

"How do you find out which job is blocking the others?"

Take a thread dump (jcmd <pid> Thread.print) while the symptom is happening and look for the thread named scheduling-1. Its stack shows the exact method that is running. If that thread is in Thread.sleep, in a socket read or waiting on a lock, you have found the slow job and the reason.

Add a log line at the start and end of each scheduled method, with the thread name, as the demo does. A log with a start but no end for 90 seconds is as clear as a dump.

Better, add a metric. Spring Boot records tasks.scheduled.execution through Micrometer for each @Scheduled method; its max and total time per method show which job is long. Alert when a job's duration exceeds its interval, because that is the moment it starts to disturb the others.

"Can I use @Async on a @Scheduled method to escape the single thread?"

You can, and it works, but think about what you give up. The scheduler thread calls the proxy, the proxy hands the real work to an executor and returns at once. The scheduler is free, but it also no longer knows whether the previous run finished, so fixedDelay loses its meaning: the delay now counts from "submitted", not from "finished".

If the job takes longer than its interval, copies pile up in the executor queue. With the default executor that queue is unbounded, which risks memory trouble and many parallel copies of the same job.

So if you do this, add an explicit guard: an AtomicBoolean running, or tryLock on a ReentrantLock, and skip the run if the previous one is still active. Use a named, bounded executor (named executor idiom) so a rejection is visible. Often the better move is a bigger scheduler pool and no @Async at all.

"What does the scheduler do when a task throws an exception?"

For a repeating task, Spring catches the exception, logs it at ERROR level through the scheduler's error handler, and schedules the next run as usual. The job does not die. That is helpful, because one bad night does not stop the invoice job forever.

It is also dangerous: a job that fails every night shows up only as a log line. Add an error handler or catch in the method and count failures with a metric, then alert on "no successful run in 25 hours". A dead-man's-switch alert catches both exceptions and a job that stopped for another reason (pod stuck, scheduler blocked).

For one-shot tasks scheduled with TaskScheduler.schedule(...), an exception ends that task, and the same error handler logs it.

Q56 · Scenario. "A nightly job runs on all six pods. Fix it."

Reveal answer

Strong answer The cause is simple: @Scheduled is an in-process timer. Every pod starts its own copy of the application, so every pod has its own scheduler and fires at 02:00. Six pods, six invoice runs, six invoices per customer. Spring does not know the other pods exist.

The fix is to make exactly one pod run each tick, and the usual tool is ShedLock (see section 07 and the idiom). Before each run, the pod tries to take a named lock stored in a table that all pods share. The pod that wins runs; the others find the lock taken and skip.

The steps are small:

  1. Add the dependencies: shedlock-spring and a provider such as shedlock-provider-jdbc-template, and create the shedlock table (name, lock_until, locked_at, locked_by).
  2. Turn it on: @EnableSchedulerLock(defaultLockAtMostFor = "PT30M") on a configuration class, and declare a LockProvider bean.
  3. Annotate the job: @SchedulerLock(name = "nightlyInvoice", ...).

The two durations are the point. lockAtMostFor is a safety valve: if the pod that holds the lock crashes, the lock expires after this time so another pod can run next night. Set it longer than the longest normal run. lockAtLeastFor keeps the lock for a minimum time even if the job finishes instantly, so that pods whose clocks differ by a few seconds cannot run it again right after.

Know the limits. ShedLock is a lock, not a scheduler: it gives "at most once per tick", not "at least once". If the winning pod dies half-way, the work is not retried until the next tick. Make the job idempotent, so a rerun is safe. Alternatives: a Kubernetes CronJob (one fresh pod per run, nothing to lock), Quartz in cluster mode, or a leader election.

Picture it

The setup: Two Spring contexts in one JVM, pod-A and pod-B, share one H2 file database. Both have the same job every 3 seconds. One copy of the job is plain @Scheduled (UNSAFE) and one has @SchedulerLock (SAFE). The run covers four ticks.

ShedLockDemo.java (excerpt) · Boot 4.2, ShedLock 7.12runs offline
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")

@Scheduled(cron = "*/3 * * * * *")
void unsafe() { log("UNSAFE invoices generated"); }

@Scheduled(cron = "*/3 * * * * *")
@SchedulerLock(name = "nightlyInvoice",
    lockAtMostFor = "PT10S", lockAtLeastFor = "PT2S")
void safe() { log("SAFE invoices generated"); }

Make the invisible visible: Count how many pods ran each version of the job at every tick.

run --demo=shedlock · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
00:42:33  pod-A SAFE   invoices generated
00:42:33  pod-A UNSAFE invoices generated
00:42:33  pod-B UNSAFE invoices generated
00:42:36  pod-B SAFE   invoices generated
00:42:36  pod-A UNSAFE invoices generated
00:42:36  pod-B UNSAFE invoices generated
00:42:39  pod-B UNSAFE invoices generated
00:42:39  pod-A SAFE   invoices generated
00:42:39  pod-A UNSAFE invoices generated
00:42:42  pod-A UNSAFE invoices generated
00:42:42  pod-B UNSAFE invoices generated
00:42:42  pod-B SAFE   invoices generated

What you see: At each of the four ticks both pods ran the UNSAFE job (8 runs in total, one per pod per tick), while the SAFE job ran exactly once per tick (4 runs): pod-A at the first tick, pod-B at the second, pod-A and pod-B after that. It does not matter which pod wins; it matters that only one does.

Why: The lock row is the shared fact. lockAtLeastFor kept the lock for 2 s, so the pod that finished first could not run again a moment later, and the other pod found the row held.

Plain @Scheduled

Every pod fires its own timer.

InvoiceJob.java · Boot 4.2runs offline
@Scheduled(cron = "0 0 2 * * *")
void nightly() {
    invoices.generateAll();
}
// 6 pods -> 6 runs

With ShedLock

One pod wins the named lock; the rest skip.

InvoiceJob.java · Boot 4.2runs offline
@Scheduled(cron = "0 0 2 * * *")
@SchedulerLock(name = "nightlyInvoice",
  lockAtMostFor = "PT30M",
  lockAtLeastFor = "PT1M")
void nightly() { invoices.generateAll(); }

The shift: A per-pod timer plus a shared lock gives one run per tick across the fleet.

Land it I put a ShedLock named lock on the job, set lockAtMostFor above the longest run, and make the job idempotent because a lock is at-most-once, not guaranteed.

Likely follow-ups
"What happens if the pod holding the lock dies half-way through the job?"

The lock row stays in the table with a lock_until time. Other pods see the lock held and skip the tick, until lock_until passes. That time is lockAtMostFor after the lock was taken, so after a crash the job is blocked for at most that long.

This is why lockAtMostFor should be a little longer than the longest honest run, not 24 hours. Set it to 10 minutes for a 4-minute job and a crash costs you the rest of that tick only. Set it too low (1 minute for a 4-minute job) and the lock expires while the job is still running, a second pod takes it, and you have two runs at once.

The half-finished work is not rolled back. Design the job so that a rerun is safe: process invoices with a status column (PENDING to DONE) and select only pending ones, or key every invoice by customer and month with a unique constraint.

"How does a Kubernetes CronJob compare with ShedLock?"

A CronJob creates a new pod for each run, runs one container and ends. Nothing is duplicated because there is one job object, and concurrencyPolicy: Forbid stops an overlapping run. Resources are used only while the job runs, and failures are visible as failed pods with their own logs and retry (backoffLimit).

The cost is that the job becomes a separate deployable: its own image or command, its own configuration and secrets, and a cold start (a Spring Boot start of several seconds). It cannot reach the in-memory state of the running service.

ShedLock keeps the job inside the service, with its beans, caches and connection pool, and needs only a table. Use it for small and frequent jobs. Use a CronJob for heavy batch work, jobs that need different resources, or teams that want ops-level visibility. See E10 for CronJob details.

"Which lock providers does ShedLock support, and which should I pick?"

ShedLock has providers for JDBC (through JdbcTemplate), MongoDB, Redis, ZooKeeper, DynamoDB, Hazelcast, Consul and others. Pick the store you already run and trust: if the service has a relational database, use the JDBC provider and one extra table. That adds no new infrastructure and the lock is as durable as your data.

Redis is attractive for speed, but if Redis is flushed or fails over, locks can be lost, so two pods may briefly run. For an idempotent job that is acceptable; for a money job I prefer the database.

Whatever the store, the clocks matter a little: ShedLock's JDBC provider can use the database time (usingDbTime()) so that pods with skewed clocks agree. I turn that on for JDBC. Also keep the lock table small and indexed by name; it only ever holds one row per job.

"How do you test that only one instance runs the job?"

Start two application contexts in one test, point both at the same test database and run the scheduled method on both at the same time, as the demo does. Collect the names of the instances that executed the job and assert the count is exactly one per tick. You can also call the proxied method directly from two threads with a barrier and assert one execution.

Do not rely on timing alone. Make the job record locked_by or an instance id in a list, and wait with Awaitility until the tick has happened rather than sleeping.

Test the failure path as well: run the job on pod A with a lockAtMostFor of 1 s, make it "crash" by never releasing, and assert that pod B can run after 1 s but not before. This test is what proves your lockAtMostFor value is sensible.

Q57. "@EventListener versus @TransactionalEventListener — when does each fire?"

Reveal answer

Strong answer Spring has a small in-process event bus. A service calls ApplicationEventPublisher.publishEvent(...), and every listener method for that event type is called. The two annotations differ in when the listener runs relative to the publisher's transaction.

A plain @EventListener is synchronous and immediate. When publishEvent is called, Spring calls the listener on the same thread, right then, inside the same transaction. When the listener returns, publishEvent returns. If the listener throws, the exception travels back to the publisher and, in a transaction, usually rolls it back. It also fires when there is no transaction at all.

A @TransactionalEventListener waits. Spring registers it as a callback on the current transaction and calls it at a chosen phase: AFTER_COMMIT (the default), AFTER_ROLLBACK, AFTER_COMPLETION (either), or BEFORE_COMMIT. With the default, the listener runs only if the transaction commits, and never if it rolls back.

That makes AFTER_COMMIT the right place for side effects that must not escape a failed transaction: sending the confirmation email, publishing to Kafka, clearing a cache. It is the after-commit event idiom.

Three traps go with it. First, if there is no transaction, a @TransactionalEventListener does not fire at all, unless you set fallbackExecution = true. Second, at AFTER_COMMIT the transaction has committed but its resources are still bound to the thread, so database writes in the listener are not part of any transaction: to write you need @Transactional(propagation = REQUIRES_NEW). Third, an exception in an after-commit listener cannot undo the commit and is only logged.

Picture it

The setup: OrderService.place() is @Transactional: it inserts a row, publishes OrderPlaced, and then optionally fails with "payment declined". Three listeners are registered: a plain @EventListener, a @TransactionalEventListener (AFTER_COMMIT) and one with AFTER_ROLLBACK. Three scenarios: commit, rollback, no transaction.

Events.java (excerpt) · Boot 4.2runs offline
@EventListener
void onPlaced(OrderPlaced e) { /* same tx, same thread */ }

@TransactionalEventListener   // AFTER_COMMIT
void afterCommit(OrderPlaced e) { /* email */ }

@TransactionalEventListener(phase = AFTER_ROLLBACK)
void afterRollback(OrderPlaced e) { /* clean up */ }

@TransactionalEventListener(fallbackExecution = true)
void anyway(OrderPlaced e) { /* even without a tx */ }

Make the invisible visible: Run the three scenarios and watch which listeners fire.

run --demo=events · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
--- 1. commit ---
  [service] row inserted, publishing OrderPlaced(o-1)
  [@EventListener] on main, tx active = true -> SENDING EMAIL for o-1
  [service] publishEvent returned
  [fallbackExecution=true] ran for o-1 (tx active = true)
  [AFTER_COMMIT]   -> SENDING EMAIL for o-1
  JPA write without a new transaction FAILED: No EntityManager with actual transaction available for cu...
  orders=1 jdbc-audit=[emailed o-1, emailed-new-tx o-1] jpa-audit=[jpa-new-tx o-1]
--- 2. rollback ---
  [service] row inserted, publishing OrderPlaced(o-2)
  [@EventListener] on main, tx active = true -> SENDING EMAIL for o-2
  [service] publishEvent returned
  [AFTER_ROLLBACK] -> cleaning up for o-2
  caught: payment declined
  orders=0 jdbc-audit=[] jpa-audit=[]
--- 3. no transaction at all ---
  [fallbackExecution=true] ran for o-3 (tx active = false)
  [@EventListener] on main, tx active = false -> SENDING EMAIL for o-3

What you see: In the commit case the plain listener fires inside the transaction ("tx active = true") before publishEvent returns, and the AFTER_COMMIT listener fires afterwards. In the rollback case the plain listener already "sent the email" for o-2, but the AFTER_COMMIT listener never ran and AFTER_ROLLBACK did. With no transaction only the plain listener and the fallbackExecution one run.

Why: A plain listener is a method call dressed as an event; it cannot know how the transaction ends. The transactional one is a synchronization callback, registered with TransactionSynchronizationManager, so Spring runs it only at the phase you named.

@EventListener

Fires at once, even if the order is later rolled back.

Mail.java · Boot 4.2runs offline
@EventListener
void onPlaced(OrderPlaced e) {
    mail.send(e.orderId());
}
// order rolled back later:
// customer already has the mail

@TransactionalEventListener

Fires only after the commit succeeded.

Mail.java · Boot 4.2runs offline
@TransactionalEventListener
void onPlaced(OrderPlaced e) {
    mail.send(e.orderId());
}
// rollback: listener never runs

The shift: Use the plain listener for in-transaction bookkeeping and the transactional one for anything outside the database.

Land it I use a plain listener for work that belongs to the transaction and AFTER_COMMIT for emails, messages and cache changes that must not outlive a rollback.

Likely follow-ups
"Why did a database write inside my AFTER_COMMIT listener not happen?"

Because at that moment there is no usable transaction. The commit is done, but the transaction's connection is still bound to the thread in a finished state, so Spring Data and JPA see a write with no active transaction and refuse it. In the measured run the error was "No EntityManager with actual transaction available for current thread" (a TransactionRequiredException), and because it happened in an after-commit callback it was only logged. The order was fine, the audit row was missing, and nobody was told.

The fix is to start a fresh transaction for the listener's work: put @Transactional(propagation = Propagation.REQUIRES_NEW) on the listener or on a service method it calls. The run above shows jpa-audit=[jpa-new-tx o-1] after that change.

Plain JDBC with autocommit may appear to work, because JdbcTemplate can run a statement without a transaction. Do not rely on it; use REQUIRES_NEW everywhere an after-commit listener writes.

"What are the four phases, and when would you use each?"

BEFORE_COMMIT runs just before the commit, still inside the transaction. Use it for last-moment checks or to write an audit row that must commit together with the data. AFTER_COMMIT (default) runs once the data is safely stored: emails, messages, cache eviction, calls to other systems. AFTER_ROLLBACK runs if the transaction rolled back: clean up temporary files, release a reserved slot, write a failure metric. AFTER_COMPLETION runs in both cases, like a finally block, for releasing resources.

You choose a phase by asking what must be true when the listener runs. If the answer is "the order must exist in the database", that is AFTER_COMMIT. If it is "the order must not exist", that is AFTER_ROLLBACK.

The next-level caveat: AFTER_COMMIT is not a delivery guarantee. If the JVM dies between the commit and the listener, the email is never sent. For must-happen messages use the outbox pattern (E7) or Spring Modulith's event publication registry, which stores the event in the same transaction and replays it.

"Can a listener change the result of the transaction that published the event?"

A plain @EventListener can, because it runs inside the same transaction on the same thread. If it throws a runtime exception the publisher's transaction is marked for rollback, and the listener can also write to the same database inside the same unit of work. That makes it a handy place for in-transaction side effects like updating a summary row, and a dangerous one for slow or flaky work: a slow listener lengthens the transaction, and a failing mail server rolls back an order.

A BEFORE_COMMIT listener can also still fail the transaction. After the commit phase, nothing can change the outcome.

My rule: anything that touches only your own database may use a plain listener or BEFORE_COMMIT. Anything that talks to another system goes to AFTER_COMMIT, behind a try/catch, and ideally an outbox.

"Do events have to be classes of my own, or can I publish any object?"

Since Spring 4.2 you can publish any object; it does not need to extend ApplicationEvent. A Java record is a fine event: record OrderPlaced(long orderId, String customer) {}. Listener methods are matched by the type of their parameter, including superclass and interface matches.

Keep events small and immutable, and carry ids and values, not JPA entities. An entity passed to an AFTER_COMMIT or async listener may be detached or lazily loaded after the session closed, and reading a lazy field fails (the lazy-loading failure in section 05 is the same problem).

A listener can also return an object, and Spring publishes that return value as a new event, so one listener can trigger the next step. I use that sparingly, because a chain of events is hard to read. Name events in the past tense (OrderPlaced) because they describe something that has already happened.

Q58 · Scenario. "An "order placed" email went out for an order that rolled back. Fix it."

Reveal answer

Strong answer The cause is almost always the same: the email is sent from a plain @EventListener (or directly from the service method), and that code runs inside the transaction, before the commit. The order is inserted, the email is sent, and then something later in the same transaction fails, for example the payment step. The database rolls the row back, but an email cannot be taken back.

Reproduce it first. Publish the event, then throw an exception, and watch the listener fire anyway. In the measured run (below) order o-2 rolled back with "payment declined", yet the plain listener had already printed "SENDING EMAIL for o-2".

The fix has two parts.

  1. Move the side effect to @TransactionalEventListener at AFTER_COMMIT (the default phase). The listener is called only after the commit succeeded, so a rollback sends nothing. This is the after-commit idiom.:
  2. Keep the event small (the order id and the customer, not the entity), because the listener may run after the session closed.:

Then close the three holes that come with it:

  • A write in the listener needs @Transactional(propagation = REQUIRES_NEW) (Q57).
  • A listener on a thread without a transaction does not fire unless fallbackExecution = true. Decide on purpose whether you want that.
  • The email can still be lost if the JVM dies between the commit and the listener, and the mail server can be down. If the email truly must go out, store a row in an outbox table in the same transaction and let a worker send it (E7 outbox).

Finally, add a test: place an order that fails after publishing, and assert that the mail sender was never called. It takes ten lines and prevents the bug from coming back.

Picture it

The setup: place(boolean fail) inserts an order row and publishes OrderPlaced. With fail=true it throws "payment declined" afterwards. The app has the broken listener (plain @EventListener, sends the email) and the fixed one (@TransactionalEventListener, AFTER_COMMIT).

OrderService.java (excerpt) · Boot 4.2runs offline
@Transactional
public void place(String id, boolean fail) {
    jdbc.update("insert into orders(id) values (?)", id);
    publisher.publishEvent(new OrderPlaced(id));
    if (fail) throw new IllegalStateException("payment declined");
}

Make the invisible visible: Run a good order and a failing one, and look at which listener fired.

run --demo=events · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
--- 1. commit ---
  [service] row inserted, publishing OrderPlaced(o-1)
  [@EventListener] on main, tx active = true -> SENDING EMAIL for o-1
  [service] publishEvent returned
  [fallbackExecution=true] ran for o-1 (tx active = true)
  [AFTER_COMMIT]   -> SENDING EMAIL for o-1
  JPA write without a new transaction FAILED: No EntityManager with actual transaction available for cu...
  orders=1 jdbc-audit=[emailed o-1, emailed-new-tx o-1] jpa-audit=[jpa-new-tx o-1]
--- 2. rollback ---
  [service] row inserted, publishing OrderPlaced(o-2)
  [@EventListener] on main, tx active = true -> SENDING EMAIL for o-2
  [service] publishEvent returned
  [AFTER_ROLLBACK] -> cleaning up for o-2
  caught: payment declined
  orders=0 jdbc-audit=[] jpa-audit=[]
--- 3. no transaction at all ---

What you see: Order o-1 commits: the plain listener and the AFTER_COMMIT listener both fire. Order o-2 rolls back: the plain listener has already sent the email, AFTER_COMMIT never runs, AFTER_ROLLBACK runs, and the final row count is orders=0. The customer got a mail for an order that does not exist.

Why: The plain listener ran before the outcome was known. Only a callback tied to the transaction's end can wait for the outcome.

Email inside the transaction

The mail leaves before the commit is certain.

MailListener.java · Boot 4.2runs offline
@EventListener
void on(OrderPlaced e) {
    mail.send(e.id());   // too early
}

Email after the commit

The mail leaves only if the order is stored.

MailListener.java · Boot 4.2runs offline
@TransactionalEventListener
void on(OrderPlaced e) {
    mail.send(e.id());   // after commit
}

The shift: Tie irreversible side effects to the commit, not to the call.

Land it I move irreversible side effects to an AFTER_COMMIT listener, and to an outbox if they must never be lost.

Likely follow-ups
"Is AFTER_COMMIT enough, or do I still need an outbox?"

It is enough for "nice to have" side effects, such as a welcome email where a rare loss is acceptable. It is not enough when the message must be delivered.

The gap sits between the commit and the listener. If the pod is killed or the JVM crashes in that moment, the order is stored and the email is never sent, and nothing remembers that it was owed. A listener exception after the commit is also just logged.

The outbox closes the gap. In the same transaction as the order, insert a row into an outbox table ("send email for order 1042"). A small worker reads pending rows, sends them and marks them done. If the worker crashes, the row is still there. The price is a worker, a table and at-least-once delivery, which means the receiver must tolerate duplicates.

Spring Modulith's event publication registry gives a ready version of this for application events, storing each event in the same transaction and republishing the incomplete ones at start-up (see section 10).

"How do you test that no email is sent on rollback?"

Write an integration test with @SpringBootTest and a @MockitoBean for the mail sender (in Boot 4, @MockBean is gone and @MockitoBean replaces it). Call the service method with fail=true, catch the expected exception, and then verify mail had no interactions with verifyNoInteractions(mail).

Add the positive test as well: with fail=false verify exactly one send("o-1"). A test that only checks the negative would also pass if the listener were never registered.

One detail: the test method itself must not be @Transactional. A transactional test rolls back at the end and, by default, AFTER_COMMIT listeners never fire inside it, so the positive test would fail for the wrong reason. Let the service create its own transaction and clean up the table afterwards.

"What if the listener is @Async? Is AFTER_COMMIT still respected?"

Yes, in this order: the transaction commits, Spring calls the listener's callback on the committing thread, and the @Async proxy then hands the real work to an executor thread. So the email is still sent only after the commit, and it no longer holds up the caller.

What you lose is the thread: the worker thread has no transaction, no SecurityContext and no MDC unless you copy them (the task-decorator idiom), and an exception there goes to the async exception handler, not to the caller.

Two practical rules. Use @Async @TransactionalEventListener only for side effects that are safe to lose or retry. And pass only ids and plain values in the event, because the original transaction's session is gone when the listener runs.

"A teammate says "I will just call the mail sender after save() in the service". What is wrong with that?"

The call inside a @Transactional method happens before the commit, exactly like the plain listener. The commit takes place when the method returns, after the email call. If anything fails at commit time (a constraint violation, a deadlock, a flush error), the data is lost but the email is sent.

It also hides the dependency: the order service now knows about email, and every new reaction (SMS, analytics, loyalty points) means editing it. Events keep the service small: it states what happened, and the listeners decide what to do.

If the team wants the simplest possible safe version, they can move the call out of the transaction: let the controller or a thin facade call orderService.place() (transactional) and, after it returns normally, call the mail sender. That works too, and has the same "lost on crash" gap. Events add structure, not extra safety; the outbox adds safety.

Q59. "Are application events synchronous? How do you make a listener async, and what do you lose?"

Reveal answer

Strong answer Yes. By default publishEvent calls every matching listener one after another, on the publisher's own thread, and returns only when they have all finished. There is no queue and no background thread. That is why a slow listener slows the publisher, and why an exception in a listener travels back to the code that published the event.

Synchronous delivery has real advantages. The listener runs inside the publisher's transaction (for a plain @EventListener), it sees the same SecurityContext and MDC, and failures are visible at once. The price is coupling in time: the publisher waits.

There are two ways to make delivery asynchronous.

  1. Per listener: add @Async next to @EventListener. That one listener runs on an executor thread. The publisher returns at once. This needs @EnableAsync, like any @Async method (see section 05).
  2. For all listeners: give the ApplicationEventMulticaster an executor with setTaskExecutor(...). Every listener then runs on that executor. It is a blunt tool, because it also changes framework events and the order of listeners.

What you lose when you go async:

  • The transaction: the listener is no longer in the publisher's transaction and cannot roll it back.
  • The security context and the MDC, unless a TaskDecorator copies them.
  • Error propagation: the publisher never sees the exception; it ends up in the async exception handler, as for any void @Async method.
  • Ordering and timing: listeners may run after the publisher has returned, so a test or a caller cannot assume the work is done.
  • Durability: the event lives only in memory. A restart loses queued events (async is not durable).

So make a listener async when it is slow, optional and safe to lose, and keep it synchronous when it must succeed with the caller.

Picture it

The setup: One listener is marked @Async @EventListener. The service prints its own thread, publishes the event, and prints when publishEvent returns.

EventsDemo.java (excerpt) · Boot 4.2runs offline
@Async
@EventListener
void onPlaced(OrderPlaced e) {
    log("[@Async @EventListener] on " + thread() + " for " + e.id());
}

void publish() {
    log("caller thread: " + thread());
    publisher.publishEvent(new OrderPlaced("o-9"));
    log("publishEvent returned to the caller");
}

Make the invisible visible: Run it and compare the thread names.

run --demo=events-async · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
  caller thread: main
  publishEvent returned to the caller
  [@Async @EventListener] on task-1 for o-9

What you see: The caller runs on main, publishEvent returns, and the listener runs on task-1, Boot's default executor thread. The ordering is typical for async: the caller's line is guaranteed first, and the listener line comes whenever the executor gets to it.

Why: @Async wraps the listener in a proxy that only submits a task. The same proxy rules apply as for any @Async method, so the executor, its queue size and its thread name come from section 05.

Synchronous (default)

The publisher waits, and shares thread and transaction.

Listener.java · Boot 4.2runs offline
@EventListener
void on(OrderPlaced e) {
    slowAudit(e);   // caller waits
}
// thread: main, tx: yes

Asynchronous

The publisher returns; the listener has its own thread.

Listener.java · Boot 4.2runs offline
@Async
@EventListener
void on(OrderPlaced e) {
    slowAudit(e);   // caller moves on
}
// thread: task-1, tx: no

The shift: Async trades the caller's thread, transaction and error path for speed.

Land it Events are synchronous by default; I make a listener async only when its work is slow, optional and safe to lose.

Likely follow-ups
"Does the order of listeners matter, and can I control it?"

With synchronous delivery, listeners run one after another, and you can set the order with @Order on the listener method. The lower number runs first. Without @Order, the order is not a contract: it follows registration and may change when you add a bean.

If a listener depends on another having run first, that is a design smell: the two steps are really one process. Put them in one listener or in one service method, and keep events for independent reactions.

With asynchronous listeners there is no order at all. Two @Async listeners for the same event run on different threads and either may finish first. Never write code that assumes otherwise.

"What happens to an exception thrown by an async listener?"

The caller never sees it. For a void async method the proxy catches the exception on the executor thread and passes it to the AsyncUncaughtExceptionHandler. In Spring Boot the default handler (SimpleAsyncUncaughtExceptionHandler) logs it at ERROR level and does nothing more.

That means a failing audit listener is visible only as a log line, and the event is gone. To handle it, register your own handler through an AsyncConfigurer (the exception-handler idiom) that increments a metric and sends an alert. For events that must not be lost, wrap the work in a retry or store it in an outbox.

Another way is to catch exceptions inside the listener and record them yourself, so that the failure is a first-class business event.

"Is it better to publish an event or just call another service?"

Use a direct call when the caller needs the answer or needs the work to succeed or fail together with its own step. Use an event when the caller does not care who reacts and the reactions are independent.

An event removes a compile-time dependency (the order service need not know about the loyalty service) and makes adding a reaction cheap. It costs readability: from the publisher you cannot see who listens, so debugging means searching for the event type. Spring Modulith can draw the listener graph for you.

Events are also not a message broker. They stay inside one JVM, one process, with no persistence and no retries. If a second service must react, you need Kafka or RabbitMQ (E17).

"Can I publish an event from a listener, and could I create an infinite loop?"

Yes you can, and yes you can loop. A listener for A that publishes B, with a listener for B that publishes A, recurses until the stack overflows (synchronous) or fills the executor queue (async).

Guard against it by design: keep the event graph one-way (placed, paid, shipped), never let two listeners publish each other's events, and put a condition on listeners (@EventListener(condition = "#e.amount > 0")) when they react to their own side effects.

Spring helps in one place: an @EventListener method that returns a non-null value publishes that value as a new event, which is convenient but makes chains easy to miss. In code review I look at what every listener returns and publishes.

Q60. "How does @PreAuthorize work, and what are its silent failure modes?"

Reveal answer

Strong answer @PreAuthorize is method security, and like @Transactional and @Cacheable it is advice on a proxy. When the annotated bean is created, Spring Security's method-security infrastructure wraps it in a proxy. On each call from outside, an interceptor evaluates the expression (it is SpEL) against the current Authentication and the method arguments. If it is true, the call goes on; if not, an AccessDeniedException is thrown before your method runs. With no login at all you get an AuthenticationCredentialsNotFoundException.

What turns it on is @EnableMethodSecurity on a configuration class. That is the first silent failure: without it, the annotation is just text.

The silent failures, all measured in the demo below, are these:

  1. Not enabled: no @EnableMethodSecurity, no proxy, and a normal user calls the admin method successfully. No warning is printed.
  2. Self-invocation: a method that calls this.refund() skips the proxy, so the check is skipped (the same trap as in section 02).
  3. Role and authority mismatch: hasRole('ADMIN') looks for the authority ROLE_ADMIN. A user whose authority is just ADMIN is denied. Use hasAuthority('ADMIN') for that, or add the prefix when you create the authorities.
  4. Other proxy limits: private, final and static methods and objects built with new are not proxied, so they are not protected.
  5. Thread boundaries: an @Async method runs on a thread with no SecurityContext, so a check fails there, or you pass the user in by hand (decorator idiom).
  6. Layer: the annotation guards the method, not the HTTP route. If the controller is open and the service is protected, fine; if the check sits only on a method that the controller never calls, nothing is protected.

Two good habits: write a test that calls each protected method as the wrong user and expects AccessDeniedException (Spring Security's @WithMockUser makes this a short test), and keep the final defence in the URL rules too (requestMatchers("/admin/**")). Link: E4's security questions.

Picture it

The setup: A RefundService has refund (hasRole('ADMIN')), history (hasRole('ADMIN') or #customer == authentication.name), viaAuthority (hasAuthority('ADMIN')) and bulk, which calls this.refund. It is run in a context without and a context with @EnableMethodSecurity.

PreAuth.java (excerpt) · Boot 4.2, Spring Security 7.2runs offline
@PreAuthorize("hasRole('ADMIN')")
public String refund(long order) { return "refunded " + order; }

@PreAuthorize("hasRole('ADMIN') or #customer == authentication.name")
public String history(String customer) { ... }

@PreAuthorize("hasAuthority('ADMIN')")
public String viaAuthority(long order) { ... }

public String bulk(long order) { return refund(order); }

Make the invisible visible: Call each method as bob (ROLE_USER), amy (ROLE_ADMIN), kim (authority ADMIN) and as nobody.

run --demo=preauth · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
--- 1. @PreAuthorize present, but no @EnableMethodSecurity
  bean class: RefundService
  bob (ROLE_USER) refund(1)                    -> refunded 1
--- 2. with @EnableMethodSecurity
  bean class: PreAuth$RefundService$$SpringCGLIB$$0
  bob refund(1)                                -> DENIED (Access Denied)
  bob history("bob")                           -> history of bob
  bob history("amy")                           -> DENIED (Access Denied)
  bob bulk(1)  (calls this.refund)             -> refunded 1
  amy (ROLE_ADMIN) refund(1)                   -> refunded 1
  kim (authority 'ADMIN') refund(1)            -> DENIED (Access Denied)
  kim (authority 'ADMIN') viaAuthority(1)      -> ok 1
  nobody logged in, refund(1)                  -> 401-style failure: AuthenticationCredentialsNotFoun...

What you see: Without @EnableMethodSecurity the bean is a plain RefundService, and bob refunds. With it the bean is a CGLIB proxy and bob is denied. bulk runs refund for bob anyway. kim has the authority ADMIN and is denied hasRole('ADMIN') but allowed hasAuthority('ADMIN'). With no user at all the exception is a different one, AuthenticationCredentialsNotFoundException.

Why: Everything the interceptor can see is the call that crosses the proxy and the Authentication stored for this thread. A direct this call, a missing proxy or an empty context changes the result.

Silently open

The check never runs.

Bulk.java · Boot 4.2runs offline
// no @EnableMethodSecurity anywhere
@PreAuthorize("hasRole('ADMIN')")
String refund(long id) { ... }
// bob (ROLE_USER) -> refunded 1

Enabled and called through the proxy

The check runs on every outside call.

Config.java · Boot 4.2runs offline
@Configuration
@EnableMethodSecurity
class SecurityConfig { }
// bob (ROLE_USER) -> DENIED
// amy (ROLE_ADMIN) -> refunded 1

The shift: A security annotation protects nothing until method security is enabled and the call goes through the proxy.

Land it I never trust a @PreAuthorize I have not tested as the wrong user, and I check that method security is enabled and that nothing calls the method with this.

Likely follow-ups
"What is the difference between @PreAuthorize, @PostAuthorize, @Secured and @RolesAllowed?"

@PreAuthorize checks a SpEL expression before the call and can use arguments (#customer) and the authentication. @PostAuthorize checks after the call and can use the return value (returnObject.owner == authentication.name), which fits "load, then decide if the caller may see it". Both are enabled by @EnableMethodSecurity.

@Secured and the standard @RolesAllowed take a plain list of roles, no expressions. They are simpler and portable but less capable, and @EnableMethodSecurity needs securedEnabled or jsr250Enabled set to use them.

I use @PreAuthorize for almost everything, because rules like "admin or the owner" are very common and cannot be written with a role list. There are also @PreFilter and @PostFilter for filtering collections; they work on the whole collection in memory, so on big lists a database query with the user's id is the better design.

"How do you test method security?"

With spring-security-test, annotate a test with @WithMockUser(username = "bob", roles = "USER") and call the service. Expect AccessDeniedException for the denied cases and the normal result for the allowed ones. Use @WithMockUser(roles = "ADMIN") for the admin case, and a test with no annotation for the anonymous one.

The test must load the real security configuration and call the service through the Spring proxy. A plain unit test that does new RefundService() tests nothing, as the first case in the demo shows. @SpringBootTest or a slice that imports the security configuration is right.

The same set of tests I run in CI covers the silent cases: one test per protected method as the wrong user. In the #scheduling demos, six method-security tests passed this way. Add a test that asserts the bean is proxied (AopUtils.isAopProxy(bean)) if you want a cheap alarm for "someone removed @EnableMethodSecurity".

"Why does hasRole('ADMIN') fail for a user whose authority is ADMIN?"

Spring Security stores roles as authorities with the prefix ROLE_. hasRole('ADMIN') is shorthand for hasAuthority('ROLE_ADMIN'); it adds the prefix for you. A token from your identity provider with the claim ADMIN becomes the authority ADMIN, not ROLE_ADMIN, so hasRole('ADMIN') is false and the admin gets "Access Denied".

In the demo, kim has the authority ADMIN: refund (hasRole) denies, and viaAuthority (hasAuthority) allows.

Fix it in one place: map the claims when you build the authorities (a JwtAuthenticationConverter with setAuthorityPrefix("ROLE_"), or GrantedAuthorityDefaults to change the prefix globally) and then use one style across the code base. Mixed styles in one project are how admins get locked out after a token change.

"Is method security enough, or do I also need URL rules?"

Use both; they guard different things. URL rules (authorizeHttpRequests) protect HTTP paths and run in the filter chain before any controller, so a new endpoint with no rule is still behind "authenticated" if you end the chain with anyRequest().authenticated().

Method security protects the code, whoever calls it: a controller, a scheduled job, another service, a message listener. If the same service is reached from a Kafka consumer, URL rules do nothing there, but @PreAuthorize on the service still asks for an Authentication (and you must provide one for system users).

Treat URL rules as the coarse gate ("only logged-in users reach /api") and method security as the fine rule ("only the owner may read this order"). Deleting either one leaves a hole.

Q61. "Method validation with @Validated: what does it add beyond @Valid on a controller?"

Reveal answer

Strong answer Bean Validation (Jakarta Validation, with Hibernate Validator behind it) checks constraint annotations such as @NotBlank and @Positive. A controller can use @Valid on a request body, and Spring MVC runs the check while binding the request. That covers requests that arrive over HTTP.

@Validated on a class turns validation on for the method calls themselves. Spring wraps the bean in a proxy that validates the arguments (and, with constraints on the return type, the result) of every call from outside. A violation throws jakarta.validation.ConstraintViolationException before the method body runs.

What it adds is protection for everything that does not come through a controller: a Kafka listener, a scheduled job, another service, a test. The rule is in the service, so there is one place that says "the discount code must not be blank and the percent must be positive". It is the validated-service idiom.

Things to know:

  • It is a proxy, so the usual limits apply: no effect on self-calls, private, final or static methods (section 02).
  • On a class with @Validated, constraints placed on method parameters are checked; @Valid on a parameter cascades into its fields.
  • A ConstraintViolationException is not a 400 by default. In a controller you map it with an @ExceptionHandler. (Controller methods get built-in method validation in Spring Framework 6.1 and later: a violation there raises HandlerMethodValidationException, which Spring MVC turns into a 400 on its own.)
  • In an interface-based design, put the constraints on the interface method and follow the rule that overriding methods must not add constraints.

The measured demo shows both sides: the @Validated service rejected a blank code and a negative percent with two violations, while an identical class without @Validated accepted them and printed "--5%".

Picture it

The setup: Two identical classes. DiscountService has @Validated on the class; UncheckedDiscountService has the same constraints on its parameters but no @Validated. A test calls both with (" ", -5).

Validation.java · Boot 4.2runs offline
@Service @Validated
class DiscountService {
    public String apply(@NotBlank String code, @Positive int percent) {
        return code + " -" + percent + "%";
    }
}

@Service
class UncheckedDiscountService {   // same signature, no @Validated
    public String apply(@NotBlank String code, @Positive int percent) {
        return code + " -" + percent + "%";
    }
}

Make the invisible visible: Run the two calls and print the exception.

mvn test -Dtest=ValidationTest · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
[INFO] Running com.quickbite.ValidationTest
CVE: jakarta.validation.ConstraintViolationException
  apply.code -> must not be blank
  apply.percent -> must be greater than 0
  proxy class: DiscountService$$SpringCGLIB$$0
unchecked.apply(" ", -5) ->   --5%
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.142 s -- in com.quickbite.Va...

What you see: The validated service throws ConstraintViolationException with two violations, apply.code -> must not be blank and apply.percent -> must be greater than 0. Its bean class is DiscountService$$SpringCGLIB$$0. The unchecked one happily returns " --5%".

Why: The constraint annotations are only metadata. The proxy that @Validated adds is what reads them on each call. Remove the class annotation and the constraints are silently ignored.

Controller only

Only HTTP requests are checked.

Controller.java · Boot 4.2runs offline
@PostMapping("/discount")
String apply(@Valid @RequestBody Req r) {
    return svc.apply(r.code(), r.percent());
}
// a job calling svc.apply(" ", -5)? ok

Service validated

Every caller is checked, HTTP or not.

DiscountService.java · Boot 4.2runs offline
@Service @Validated
class DiscountService {
  String apply(@NotBlank String code,
               @Positive int percent) {
      return code + " -" + percent + "%";
  }
}

The shift: Put the rule next to the code that depends on it, so that every entry point is covered.

Land it I validate at the controller for the HTTP shape and with @Validated on the service for the rules that every caller must respect.

Likely follow-ups
"How do I turn a ConstraintViolationException into a 400 response?"

Add an @ExceptionHandler(ConstraintViolationException.class) in a @RestControllerAdvice and return a ProblemDetail with status 400. Build the body from e.getConstraintViolations(): each violation has a property path (apply.code) and a message. List them as a map or an array so a client can show errors next to fields.

A violation inside a service call can mean two different things. If the argument came straight from the request, a 400 is right. If a bug in your own code produced the bad argument, it is a 500 and you want the stack trace. When the same service is used by both HTTP and internal callers, I keep the service rule as the safety net and validate the request earlier (with @Valid) so a client error never reaches it.

Do not expose the property path unchanged to clients: apply.code leaks a method name. Map it to the request field name.

"What is the difference between @Valid and @Validated?"

@Valid is the standard Jakarta annotation. It marks what to cascade into: a parameter, a field or a collection element whose own constraints must be checked. @Validated is Spring's annotation. On a class it switches on method validation through a proxy, and it also allows validation groups (for example one set of rules for create and another for update).

So they are used together: @Validated on the service class (switch on), and @Valid on a parameter object (cascade into its fields). On a controller parameter, either works for body validation, and @Valid is the usual choice.

A common bug is a service with constraints and no @Validated: the code looks protected, and nothing is checked, as the unchecked class in the demo shows.

"Can I validate return values and use custom constraints?"

Yes. Put a constraint on the method itself, for example @NotNull @Valid Order find(long id), and the proxy validates the returned object after the call. A violation throws the same exception, and it means the service broke its own promise, which is a 500-class error.

Custom constraints are an annotation plus a ConstraintValidator: @ValidPromoCode and a PromoCodeValidator class that implements ConstraintValidator. The validator can be a Spring bean, so it can look up the database, but keep that for cheap checks. A constraint that makes a remote call on every validation is a hidden performance problem and runs again in every layer that validates.

For cross-field rules (end date after start date) put a class-level constraint on the request record, not a method-level one.

"How is validation affected by the proxy limits you learned in the AOP section?"

Exactly the same way. A call from another method of the same class (this.apply(...)) bypasses the proxy, so nothing is validated. A private or final method cannot be intercepted by a CGLIB proxy, and final classes cannot be proxied at all (in Spring Boot a final class with @Validated fails or silently loses the proxy depending on the setup, so check the startup log).

The remedies are the ones from the self-invocation fix: call through another bean, or move the validated method to its own class. As a safety net, add a unit test that asserts the class is proxied and that an invalid call throws, as ValidationTest did.

If you cannot accept any silent hole, validate explicitly at the top of the method with Validator.validate(...) and throw yourself. It is more code and it does not depend on a proxy.

Q62. "@Observed versus @Timed versus a custom aspect for metrics."

Reveal answer

Strong answer All three put a timer around a method, and they differ in what they give you and what you must set up. The surprising part, which I measured in the #scheduling section, is that two of them do nothing out of the box.

@Timed (from Micrometer) records a timer: count, total time and max time, tagged with class, method and exception. It is not active by default. Micrometer's TimedAspect must be declared as a bean, for example a TimedAspect bean built from the MeterRegistry. Without that bean the annotation is only text and the meter never appears. (Spring MVC controllers and a few framework points have their own timing and do not need this.)

@Observed (Micrometer Observation) is the newer, larger idea. One observation can produce a metric, a trace span and a log context from one instrumentation point. It needs the observation aspect, and in Boot 4.2 you switch it on with management.observations.annotations.enabled=true. In the measured run, without that property @Observed recorded nothing, and no error was shown.

A custom aspect (section 02) gives you full control: any pointcut (all services at once), your own tags, your own naming, your own rules (only record slow calls). The price is that you write and maintain it, including the proxy limits.

How I choose: use @Observed when the service already has tracing and you want metrics and spans together. Use @Timed for a quick latency timer on one method with the least setup. Use a custom aspect when you want a rule applied to many methods without annotating each one, or special logic. Always keep cardinality in mind: tags must have a small, fixed set of values (method, source). A tag such as orderId creates a new time series per order and can crash your metrics backend.

Verify, do not assume: after adding any of the three, curl /actuator/metrics/<name> and check that the count rises.

Picture it

The setup: PriceService has @Timed("menu.price") on price() and @Observed(name = "menu.load") on load(). The first run has neither the TimedAspect bean nor the observation property; the second run adds both. Each method is called three times, then the meters are read, and /actuator/metrics/menu.price is fetched with a real HTTP call.

Metrics.java · Boot 4.2runs offline
@Bean TimedAspect timedAspect(MeterRegistry registry) {
    return new TimedAspect(registry);
}

@Observed(name = "menu.load", lowCardinalityKeyValues = {"source", "db"})
public int load() { ... }

@Timed(value = "menu.price", description = "time to price an item")
public int price(String item) { ... }

Make the invisible visible: Compare the two runs; then read the metric through Actuator.

run --demo=metrics · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
# without management.observations.annotations.enabled
menu.load: NO METER
menu.price: count=3 tags=[tag(class=com.quickbite.PriceService), tag(exception=none), tag(method=price)]
menu.* meters: [menu.price]

# with it
menu.load: count=3 tags=[tag(class=com.quickbite.PriceService), tag(error=none), tag(method=load), ta...
menu.price: count=3 tags=[tag(class=com.quickbite.PriceService), tag(exception=none), tag(method=price)]
menu.* meters: [menu.load, menu.price]
GET /actuator/metrics/menu.price -> 200 (count 3.0, total 0.0319 s, max 0.0107 s)

What you see: Without the property menu.load has "NO METER" while menu.price already exists, because the TimedAspect bean was declared. With the property @Observed appears too, with tags class, method, source and error. The Actuator JSON for menu.price shows COUNT 3, TOTAL_TIME and MAX.

Why: @Timed and @Observed are only annotations. The real work is done by an aspect bean that must exist, so a missing switch means a method that looks measured and is not.

@Timed

One timer, one bean to declare.

Metrics.java · Boot 4.2runs offline
@Bean TimedAspect timedAspect(
        MeterRegistry r) {
    return new TimedAspect(r);
}
@Timed("menu.price")
int price(String item) { ... }

@Observed

Metric plus trace from one annotation, one property.

application.propertiesruns offline
management.observations
  .annotations.enabled=true
# then in code:
# @Observed(name = "menu.load")
# int load() { ... }

The shift: Both need a switch; choose by whether you also want traces.

Land it I check the meter in Actuator after adding any metrics annotation, because without its aspect the annotation silently records nothing.

Likely follow-ups
"What is metric cardinality and why does it matter for tags?"

Cardinality is the number of different tag value combinations. Every combination is a separate time series that the metrics backend stores and indexes. A tag such as method (maybe 40 values) is fine. A tag such as customerId or orderId has one value per customer or order, millions in the end. Prometheus-style backends slow down or run out of memory, and the monthly bill grows.

Rule of thumb: tags describe a kind of thing (endpoint, status class, source), never an instance (user, order, URL with ids). For per-order detail use a log line or a trace attribute, which are made for high cardinality.

@Observed splits this clearly: lowCardinalityKeyValues become metric tags, and highCardinalityKeyValues go only into traces. That is one more reason to prefer it when you have tracing.

"Can I time every service method without annotating each one?"

Yes, with a custom aspect and a pointcut such as @Around("within(@org.springframework.stereotype.Service *)"). The aspect starts a Timer.Sample, calls proceed(), and stops the sample with tags built from the join point (class and method names). This is the 12-line aspect from section 02, with a registry call in place of a print.

Boot also gives you some timing for free: HTTP server requests (http.server.requests), JDBC connection pool (hikaricp.*), and @Scheduled methods (tasks.scheduled.execution). Check what exists before adding your own.

The risk of a broad pointcut is overhead and clutter. Timing a getter that takes 20 nanoseconds costs more than it measures. Restrict the pointcut to the service layer, and skip trivial methods with !execution(* get*(..)) or a marker annotation.

"How do @Observed and tracing relate to the trace id in my logs?"

One observation can feed several "handlers": a metrics handler creates the timer, a tracing handler creates a span, and a logging handler can put the trace and span ids into the MDC. When tracing is on, a method annotated with @Observed becomes a span, a child of the current request's span, so you see it in the trace view with its own duration.

The ids then appear in log lines written while the span is open (see section 09 and Q76). That is how you jump from a slow trace to its exact logs.

Without a tracing dependency, @Observed still produces the metric and nothing more. Adding the OpenTelemetry starter later upgrades the same annotation to a span without changing code.

"Why would the metric exist but have no data for some methods?"

Three common reasons. First, self-invocation: the annotated method is called from another method of the same class, so the proxy is bypassed and nothing is recorded (the self-invocation fix). Second, the bean is not a Spring bean (created with new), so no proxy exists. Third, the meter is created lazily on the first call, so an endpoint that was never called simply has no meter yet. A dashboard that queries menu.price before any call finds nothing.

In the demo, untouched() has no annotation and has no meter at all. If a meter is expected and missing, check the order: is the aspect bean present, is the property set, is the call crossing a proxy, and has it been called at least once?

Q63. "What does @Lazy actually do, on a bean and on an injection point?"

Reveal answer

Strong answer By default Spring creates every singleton bean when the application context starts. This is called eager initialisation, and it is a feature: a wrong configuration or a missing dependency stops the application at start-up instead of failing in production on the first request. @Lazy changes the moment of creation, and the two places you can put it do two different things.

@Lazy on a bean (on the class or the @Bean method) means "do not create this bean at start-up; create it the first time somebody asks for it". The first caller pays the creation cost, and any failure in creating it appears then, not at start-up.

@Lazy on an injection point (a constructor parameter or a field) means "do not hand me the real bean; hand me a small proxy that will fetch the real one on first use". The proxy lets the bean that receives it be created without the dependency being ready. It is one way to break a cycle (the cycle idiom).

The measured demo shows the part that surprises people: @Lazy on an injection point alone does not make the target bean lazy. The target is still an ordinary singleton, so Spring still creates it at start-up like any other. Only the reference held by the consumer is lazy. To defer the bean itself you need @Lazy on the bean, or global lazy initialisation with spring.main.lazy-initialization=true.

Use it for: a rarely used bean with a heavy start (a report engine, a large model), a cycle you cannot redesign yet, and fast start-up in tests or serverless. Avoid global lazy mode in production: it moves startup errors to the first user request, hides slow beans until traffic arrives, and makes the first request slow.

Picture it

The setup: SlowClient takes 100 ms to build. Dashboard receives it through a @Lazy constructor parameter. ReportEngine is marked @Lazy itself. ChatClient is both a @Lazy bean and a @Lazy injection point. EagerCache is a normal bean. A runner prints "context is ready" and then uses each.

LazyProfile.java (excerpt) · Boot 4.2runs offline
@Component @Lazy
class ReportEngine { ... }               // lazy BEAN

@Component
class Dashboard {
    Dashboard(@Lazy SlowClient client,   // lazy INJECTION POINT
              @Lazy ChatClient chat) { ... }
}

Make the invisible visible: Run it twice: normally, and with spring.main.lazy-initialization=true.

run --demo=lazy · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
# normal
  creating Dashboard, client is SlowClient$$SpringCGLIB$$0
  creating EagerCache (eager, the default)
  creating SlowClient (heavy)
  context is ready
  Dashboard.show() -> called
  creating ChatClient (@Lazy bean AND @Lazy injection point)
  Dashboard.chat.hello() -> hi
  creating ReportEngine (@Lazy bean)
  ReportEngine.run() -> report built

# spring.main.lazy-initialization=true
  creating Dashboard, client is SlowClient$$SpringCGLIB$$0
  context is ready
  creating SlowClient (heavy)
  Dashboard.show() -> called
  creating ChatClient (@Lazy bean AND @Lazy injection point)
  Dashboard.chat.hello() -> hi
  creating ReportEngine (@Lazy bean)
  ReportEngine.run() -> report built

What you see: Normal run: Dashboard is created holding a proxy (SlowClient$$SpringCGLIB$$0), but "creating SlowClient (heavy)" still prints before "context is ready", and so does EagerCache. ReportEngine and ChatClient, both @Lazy beans, are created only when first used. With global lazy mode even SlowClient waits until show() is called.

Why: A lazy injection point only changes what the consumer holds. The singleton registry still instantiates every non-lazy bean at refresh, because nothing told it otherwise.

Lazy injection point only

The target is still created at start-up.

Dashboard.java · Boot 4.2runs offline
Dashboard(@Lazy SlowClient c) {
    this.client = c;   // a proxy
}
// SlowClient: created before
// "context is ready"

Lazy bean

The target waits for its first use.

SlowClient.java · Boot 4.2runs offline
@Component @Lazy
class SlowClient {
    SlowClient() { /* 100 ms */ }
}
// created on the first call,
// after "context is ready"

The shift: To delay a bean, mark the bean; to delay a reference, mark the injection point.

Land it @Lazy on an injection point delays the reference, not the bean; to defer the bean itself I mark the bean or use global lazy mode in non-production.

Likely follow-ups
"Why not turn on spring.main.lazy-initialization=true everywhere?"

It makes start-up faster, but at the wrong price for production. Configuration errors that would stop the app at start (a missing property, a bean that cannot be built, a database that is unreachable) now appear on the first request that needs the bean. A deployment looks healthy, passes the readiness check, and then fails for the first customer.

It also moves the cost of heavy beans onto the first user: a 3-second connection set-up lands on someone's checkout.

Where it helps is development and tests, where you start the app often and touch few beans, and serverless or CLI tools where start-up time is the main cost. If you use it in production anyway, add a warm-up step that touches the critical beans on ApplicationReadyEvent and exclude important beans with @Lazy(false).

"How does @Lazy on an injection point help with a circular dependency?"

With a cycle A needs B and B needs A, Spring cannot build either first. If A takes a @Lazy B, Spring injects a proxy of B into A without building B. A is created, then B is created normally with the real A, and later when A calls the proxy, the proxy resolves the real B.

It works, but it hides the cycle instead of removing it. The honest fix is to break the design (extract the shared part, use an event, see the cycle idiom). The measured --demo=cycle run in section 08 lists the fixes in order of preference and puts @Lazy after redesign and events.

A @Lazy proxy also needs the dependency type to be proxiable: an interface, or a non-final class.

"Does @Lazy work on @Configuration classes or @Bean methods?"

On a @Bean method it makes that one bean lazy. On a @Configuration class it makes every @Bean in that class lazy, and it is inherited by component scanning of the configuration. @Lazy(false) on an individual bean overrides it, which is how you keep health-critical beans eager inside a lazy class.

Beans that other components depend on eagerly are created anyway, even if marked lazy: if a non-lazy bean injects a lazy bean through a normal injection point, Spring must create the lazy one to satisfy it. Lazy only helps when the consumer is lazy too, or injects through @Lazy, ObjectProvider or Provider.

ObjectProvider<T> is the explicit alternative: engine.getObject() or getIfAvailable() in the demo's runner. It makes the lazy lookup visible in the code, with no proxy.

"How does @Lazy interact with @Transactional or @Async proxies?"

They stack. A @Lazy injection point proxy forwards each call to the real bean, and if the real bean is itself a proxy (transactional, async, cacheable), the call passes through those advisors as usual. The lazy proxy does not hide advice.

One catch is class-based proxying of the target: the lazy proxy for a class needs CGLIB, so the class must not be final. And getClass() on the injected object shows ...$$SpringCGLIB$$0, which can confuse equality checks and instanceof code.

Also remember that a lazy bean's lifecycle callbacks (@PostConstruct) run on first use, on that caller's thread, perhaps inside a transaction or a request.

Q64. "@Profile versus @ConditionalOnProperty — when do you use each?"

Reveal answer

Strong answer Both switch a bean (or a configuration) on or off from outside the code, and they differ in the question they ask. @Profile("dev") asks "is this environment active?". A profile is a named group, chosen by spring.profiles.active. @ConditionalOnProperty(name = "feature.sms", ...) asks "is this setting present with this value?". It reads a single property.

Use @Profile for things that describe the kind of environment as a whole: a console email sender in dev and the SMTP sender in prod; an in-memory database in test; a H2 console. Profiles also select whole config files (application-prod.properties) and can be grouped (spring.profiles.group.prod=proddb,metrics, see section 08). Profile expressions work too: @Profile("!dev"), @Profile("prod & eu").

Use @ConditionalOnProperty for one feature switch that you may flip in any environment: turn on the SMS feature in one region, disable the nightly job in a maintenance window, enable a new payment path for a canary. It works in any profile, and a matchIfMissing = true makes "on unless disabled". It is also the building block of starters (custom starter): quickbite.audit.enabled=false turns a starter's bean off.

The difference in practice: profile answers "what kind of deployment is this", property answers "is this feature on". A bean tied to @Profile("prod") cannot be tested in dev without activating prod, which is a sign you wanted a property. A long list of @Profile values for one feature (dev, test, staging, qa) is also a sign.

Keep production safe: do not create behaviour that exists only under a profile you never test. Anything that runs in production should run, with a different value, in your tests as well.

Picture it

The setup: ConsoleSms is @Profile("dev"), GatewaySms is @Profile("!dev"), and a SmsFeature bean is created only when feature.sms=on. The app runs twice: with no profile, and with --spring.profiles.active=dev --feature.sms=on.

LazyProfile.java (excerpt) · Boot 4.2runs offline
@Component @Profile("dev")
class ConsoleSms implements Sms { ... }

@Component @Profile("!dev")
class GatewaySms implements Sms { ... }

@Component
@ConditionalOnProperty(name = "feature.sms", havingValue = "on")
class SmsFeature { ... }

Make the invisible visible: Run both configurations.

run --demo=profile · Boot 4.2 (code/e22-spring-in-depth/C/)runs offline
# no profile, no property
  profiles=[] Sms -> sent via gateway, SmsFeature present=false

# profile dev, feature.sms=on
  SmsFeature bean created (feature.sms=on)
  profiles=[dev] Sms -> printed to console, SmsFeature present=true

What you see: With nothing set the gateway is used and SmsFeature is absent. With dev and the property, the console implementation is picked and SmsFeature is created. The two switches act independently.

Why: A profile is evaluated against the set of active profile names; a property condition is evaluated against one key in the Environment. They are different questions, so they combine freely.

@Profile

Picks a bean by environment kind.

Sms.java · Boot 4.2runs offline
@Component @Profile("dev")
class ConsoleSms implements Sms {
  public String send() {
    return "printed to console";
  }
}

@ConditionalOnProperty

Picks a bean by one feature switch.

Sms.java · Boot 4.2runs offline
@Component
@ConditionalOnProperty(
    name = "feature.sms",
    havingValue = "on")
class SmsFeature { }

The shift: Environment kind versus single feature flag: choose by the question you are asking.

Land it I use a profile for what kind of environment this is and a property condition for whether one feature is on.

Likely follow-ups
"Can a bean have both a profile and a property condition?"

Yes. Put both annotations on the same class and Spring requires both to match: @Profile("prod") together with @ConditionalOnProperty creates the bean only in prod and only when the property is true. That is useful for a feature that exists only in production but needs an off switch for emergencies.

Conditions of any kind are evaluated at bean-definition time, when the context starts. They are not re-checked while the app runs. To switch behaviour at runtime without a restart, use a normal bean that reads a refreshable value (a feature-flag service), not a condition.

Note that @ConditionalOnProperty lives in Spring Boot, not in the Spring Framework core; it is meant for auto-configuration and application code alike.

"How do I see which profiles are active and which beans each created?"

The active profiles are printed at start-up: "The following 1 profile is active: dev" (or "No active profile set, falling back to 1 default profile: default" as in the logs of the demos). Environment.getActiveProfiles() returns them in code, and /actuator/env shows activeProfiles with the property sources.

For conditions, start with --debug. Spring Boot prints a conditions evaluation report listing each auto-configuration with the conditions that matched or failed, for example "@ConditionalOnProperty (quickbite.audit.enabled) found different value". /actuator/conditions shows the same at runtime, and /actuator/beans lists what exists.

When a bean "is missing", these three outputs answer it faster than reading code: which profile was active, which condition failed, and which bean was created instead.

"What is wrong with if (env.acceptsProfiles("prod")) in business code?"

It scatters environment knowledge through the code and makes behaviour hard to test: to test the "prod" branch you must run the whole app as prod. It also tends to grow: a few years later nobody can say what production does differently.

Move the difference to a bean: define an interface (Sms) and two implementations selected by profile or property. The business code calls the interface and is identical everywhere; what differs is wiring, and wiring is visible in one place.

If the difference is only a number or a URL, it belongs in configuration properties, with defaults in application.properties and overrides in the profile file or the environment, not in an if.

"Are spring.profiles.active and SPRING_PROFILES_ACTIVE the same, and which wins?"

They name the same setting through different property sources. SPRING_PROFILES_ACTIVE=prod is an environment variable, and --spring.profiles.active=prod is a command-line argument. Relaxed binding maps the environment variable to the property name (the precedence idiom).

If both are set, the command-line argument wins, because command-line arguments sit above environment variables in Spring Boot's order. Setting spring.profiles.active inside application.properties is the weakest of the three, and cannot be set inside a profile-specific file.

For deployments I set SPRING_PROFILES_ACTIVE in the container spec, because it is visible in the manifest and needs no change to the command. And spring.profiles.include or groups add profiles on top of the active ones rather than replacing them.

Q65 · Design. "You review a service with @Transactional, @Cacheable, @Async, @Retryable and @PreAuthorize on different methods. What do you check?"

Reveal answer

Strong answer I review it as one question repeated for every annotated method: "does this call go through the proxy, in which order do the advisors run, and on which thread?" Then I check the annotation-specific traps. I write it down as a checklist, because every item below has caused a production incident in this chapter.

Group 1 — does the proxy run at all?

  1. Self-invocation: does any method call another annotated method of the same class (this.x())? If yes, the annotation on the callee is ignored (fix: another bean).
  2. Visibility and type: are annotated methods public, non-final, non-static, in a non-final class, on a bean made by Spring (not new)?
  3. Enabled: @EnableCaching, @EnableAsync, @EnableResilientMethods, @EnableMethodSecurity and the transaction setup are present. A missing switch fails silently.

Group 2 — order. With defaults the chain is retry, then cache, then transaction, then your aspects (section 03). So a cache hit never opens a transaction, each retry gets a fresh transaction, and a custom timing aspect does not see cache hits.

Group 3 — each annotation.

  • @Transactional: where does the transaction start and end, is it too wide (remote calls inside), and is rollbackFor needed for checked exceptions?
  • @Cacheable: is the key explicit and stable, is there a TTL in the provider, does a write evict, is the cached value immutable and per-user data excluded?
  • @Async: which executor, bounded, with an exception handler; are ids passed, not entities; what is lost on shutdown?
  • @Retryable: is the operation idempotent or keyed, are exceptions limited with includes, is there a timeout and a limit on retries?
  • @PreAuthorize: is it tested as the wrong user, and is the role prefix right?

Group 4 — combinations that bite. @Async @Transactional starts the transaction on the worker thread. @Async @PreAuthorize has no security context on the worker. @Cacheable on a method that returns a JPA entity with lazy fields. @Retryable around a method that sends an email inside the transaction.

I end the review with tests, not opinions: one test per trap, and a startup print of the advisor chain for the busiest bean (the advisor-chain idiom).

Picture it

The setup: A short CheckoutService carries one trap in each method. The review is run mechanically: print what each method's call actually does, using the measured demos from sections 02 and 03.

CheckoutService.java (what the reviewer sees) · Boot 4.2runs offline
@Service
public class CheckoutService {
    @Transactional
    public void place(Order o) {
        save(o);
        this.confirm(o);              // (1) self-call
    }
    @Async @Transactional
    public void confirm(Order o) { /* lazy fields */ }   // (2)
    @Cacheable("prices")
    public Price price(Item i) { /* returns entity */ }  // (3)
    @Retryable
    public Receipt charge(Order o) { /* not idempotent */ } // (4)
    @PreAuthorize("hasRole('ADMIN')")
    public void refund(long id) { }       // (5)
}

Make the invisible visible: Each trap, measured earlier in this chapter.

measured results · Boot 4.2 (folders A/, B/, C/, G/)runs offline
(1) A/selfinv.out   same-class @Async call returned after 300 ms, runs on thread main
                    other-bean call returned after 4 ms, runs on thread task-1
(2) B/tx.out        LazyInitializationException ... (no session); pass the ID: lines = 2
(3) A/stacked.out   advisor order: retry, ExposeInvocation, cache, transaction, aspect
(4) C/idempotent.out retry WITHOUT a key: money taken 2 time(s); with a key: 1
(5) G/preauth.out   without @EnableMethodSecurity: bob (ROLE_USER) refund(1) -> refunded 1

What you see: Every line is a one-method defect that looks fine in the code: it compiles, its unit test passes, and the failure shows up only through the Spring proxy or under real conditions.

Why: All five annotations are advice on one proxy. So the review is not five separate reviews; it is one review of the proxy path, repeated for each annotation's own contract.

CheckWhyEvidence
Same-class call to an annotated methodThe proxy is skippedA/selfinv.out
Order of advisorsCache hit skips the transaction; retry wraps bothA/stacked.out
Entity crossing a threadLazy loading needs the sessionB/tx.out
Retry on a non-idempotent callDouble chargeC/idempotent.out
Security annotation actually enabledSilent open doorG/preauth.out

Review by reading

The code looks right line by line.

CheckoutService.javaruns offline
// annotations present: 5 of 5
// tests pass
// reviewer: LGTM

Review by the proxy path

For each call, ask which advisors run and where.

review checklistruns offline
1 call crosses the proxy?
2 advisor order known?
3 thread and security context?
4 idempotent / bounded / keyed?
5 test per trap

The shift: A reviewer who thinks in proxies finds bugs that reading line by line misses.

Land it I review annotated services by tracing each call through the proxy, in order and thread by thread, and I make each trap a test.

Likely follow-ups
"In what order do you check the five annotations if you only have ten minutes?"

First @Retryable and @Transactional, because they can cost money: retry around something non-idempotent, or a transaction that holds a connection during a remote call. Second @PreAuthorize, because a silent open door is a security incident. Third @Async, which loses context, exceptions and work on deploy. Fourth @Cacheable, which usually produces wrong data (stale or per-user) rather than outages. A close fifth is the self-invocation check, which I run across all of them first, since it nullifies any annotation.

In ten minutes I read the class once for self-calls and visibility, print the advisor chain at start-up to confirm the annotations are active, and ask for the test that proves each risky method behaves as intended. If a test does not exist I treat the annotation as unproven.

"How do you check at runtime that the annotations are really active?"

Print the proxy. AopUtils.isAopProxy(bean) and ((Advised) bean).getAdvisors() show the real chain, as the --demo=stacked output does in section 03: retry advisor, ExposeInvocationInterceptor, CacheInterceptor, TransactionInterceptor, and then your aspects. If an expected advisor is missing, the enabling annotation is missing or the bean is not proxied.

Then check behaviour through Actuator: /actuator/caches lists cache names, /actuator/metrics shows cache.gets, /actuator/metrics/executor.* shows pool use, and the loggers endpoint can switch on org.springframework.aop, org.springframework.transaction and org.springframework.cache at DEBUG for a short window.

A small start-up test that asserts the advisor chain of one key bean (for example 'contains a TransactionInterceptor') is a cheap guard against someone removing an enabling annotation.

"What do you recommend when the same method carries three or four of these annotations?"

Split it. A method that is cached, transactional, retried and secured is hiding several responsibilities. Usually a layered shape works: a thin secured entry (@PreAuthorize) calls a retrying wrapper (@Retryable) that calls a transactional unit of work (@Transactional), and the lookup of read-mostly data sits in its own cached bean.

Each piece then has one reason to change, and the order is by construction, not by luck. It also solves self-invocation: the pieces are separate beans, so each call crosses a proxy.

If stacking is unavoidable, write the test that exercises the whole stack together (a cache miss that fails twice and then succeeds, a cache hit, a rollback) and keep the printed advisor chain next to it, as in the section 03 demo.

"What would you add to the team's process so these bugs stop reaching review?"

Four cheap things. An architecture test (ArchUnit or Spring Modulith's checks) that forbids annotated methods in final classes or non-public methods. A shared test base class that asserts the key services are proxied. A short "Spring annotations" page with the chapter's cheat sheet (see the annotation cheat sheet), so people know the traps by name. And a rule in the pull request template: "new annotation on a method means one new test for the failure it hides".

Also make start-up noisy about risk: log the active profiles, the executor settings and the advisor chain of the main services in a debug-level startup listener. The next incident is then a lookup rather than an investigation.

14 · DrillConfiguration, Platform, Integration and Boot 4.x — Q66–Q100

The last thirty-five questions leave the proxy and look at everything around it: where a property comes from, how a starter backs off, what runs in what order at start-up, how logs and migrations behave in production, which extra Spring modules still matter, and what changed in Spring Boot 4.0, 4.1 and 4.2. Interviewers use them to find out whether you can operate a service, not only write one. The matching teaching sections are 08, 09, 10 and 11.

Every output block comes from a run on Spring Boot 4.2.0 and Java 25, with the programs saved under code/e22-spring-in-depth/D/, E/, C/ and G/. Where a library or a service could not be run offline (Testcontainers, a message broker, gRPC, Spring Cloud), the answer says so and shows code marked as an illustration, never an invented output.

Drill · Configuration, starters and lifecycle

Eight questions on how a Spring Boot application is assembled: which property wins, how a starter steps aside for the application, in what order the container calls your code, and why a dependency cycle stops the start.

Q66. "In what order does Spring Boot read properties, and which source wins?"

Reveal answer

The real test Whether you can name the order from the launch command inwards, and know how to ask the running app which source set a value.

Strong answer Spring Boot collects configuration from many property sources into one Environment, and when two sources set the same key, the one higher in a fixed order wins. The full official list has about seventeen entries. For daily work you need the middle of it, which I remember as a ladder from weakest to strongest:

  1. Defaults in code: @ConfigurationProperties field defaults and @Value("${x:default}"). Weakest.
  2. application.properties or application.yml inside the jar.:
  3. Profile files such as application-prod.properties, which beat the plain file for the active profile.:
  4. Config imported with spring.config.import, for example a file mounted by Kubernetes or a config tree of secrets.:
  5. OS environment variables.:
  6. JVM system properties (-Dquickbite.db.url=...).:
  7. Command-line arguments (--quickbite.db.url=...). Strongest of these.:

Test annotations like @TestPropertySource and @SpringBootTest(properties=...) sit above all of this for tests. So the rule of thumb is: the closer to the launch command, the stronger the source. A file inside the jar never beats the environment.

The measured demo below sets the same key in five places and then removes the winner one by one. Each run prints the winner and every source that defines the key, highest first. That second list is the trick for debugging: Spring tells you who set it.

Two details cause most confusion. First, an environment variable QUICKBITE_DB_URL is mapped to the key quickbite.db.url by relaxed binding, so the variable name must match after the mapping. A typo (QUICKBITE_DB_URI) is not an error: it is just a different, unused variable, and the weaker source wins quietly. Second, the same key in two files follows the order of the files, and later profiles override earlier ones.

This is the config-precedence idiom, and section 08 shows the Actuator /actuator/env view as well.

Picture it

The setup: The key quickbite.db.url is set in application.properties, in application-prod.properties (profile prod), as the environment variable QUICKBITE_DB_URL, as a system property and as a command-line argument. The program prints the winner and every source for the key, then reruns without the winner.

PrecedenceDemo.java (excerpt) · Boot 4.2runs offline
for (PropertySource<?> ps : env.getPropertySources()) {
    if (ps.containsProperty("quickbite.db.url")) {
        System.out.printf("  %-45s -> %s%n", ps.getName(),
            ps.getProperty("quickbite.db.url"));
    }
}

Make the invisible visible: Print the winner and the list of sources, highest first.

run --demo=precedence · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
--- all five places set
winner : jdbc:h2:mem:from-command-line
sources that define quickbite.db.url, highest first:
  commandLineArgs                               -> jdbc:h2:mem:from-command-line
  systemProperties                              -> jdbc:h2:mem:from-system-property
  systemEnvironment                             -> jdbc:h2:mem:from-env-var
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the command-line argument
...
sources that define quickbite.db.url, highest first:
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the profile
winner : jdbc:h2:mem:from-application-properties
sources that define quickbite.db.url, highest first:
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- the typo: QUICKBITE_DB_URI instead of QUICKBITE_DB_URL

What you see: All five places set: the command-line argument wins; the file value is the weakest of the five. Remove the argument and the system property wins, then the environment variable, then the profile file, then the plain file. In the last block the typo QUICKBITE_DB_URI defined nothing, so application.properties quietly won.

Why: Each source is wrapped in a PropertySource and kept in a list ordered by precedence. A lookup walks that list top-down and stops at the first source that has the key.

Guessing

"The yaml says prod, so prod it is."

(no output)runs offline
# application.yml says
#   quickbite.db.url: jdbc:...prod
# the pod uses the dev database
# nobody can say why

Asking Spring

Print which source defined the winning value.

/actuator/env/quickbite.db.urlruns offline
{"property":{
   "source":"systemEnvironment",
   "value":"jdbc:h2:mem:from-env-var",
   "origin":"System Environment Property
      \"QUICKBITE_DB_URL\""}}

The shift: The environment can answer which source won, so nobody has to guess.

Land it I remember the ladder as defaults, files, profile files, imports, environment, system properties and arguments, and I ask Actuator which source won.

Likely follow-ups
"How do I see where a value came from in a running application?"

Use the Actuator env endpoint: GET /actuator/env/quickbite.db.url returns the winning value, the name of the property source and, for files, the exact file and line (application.properties ... - 6:18). GET /actuator/env lists all sources in order, with the values of the key under each source. In the measured run, the list started with commandLineArgs, systemProperties and systemEnvironment above the two Config resource entries for the files.

The endpoint is not exposed over HTTP by default and it can show secrets, so expose it only on a protected management port (management.endpoints.web.exposure.include=env, behind authentication). Spring Boot sanitises values whose keys contain password, secret or token and shows ******.

For an app that will not start, there is no endpoint yet, so use --debug or the logging.level of the Boot config package set to trace to log how each config file was loaded.

"Where do Kubernetes ConfigMaps and Secrets fit in?"

Three ways, and they sit at different levels. As environment variables (envFrom a ConfigMap): they rank above files and are mapped by relaxed binding, so QUICKBITE_DB_URL overrides the file. As mounted files imported with spring.config.import with an optional:file: location: imported files rank above the jar's files. As a config tree, one file per key in a directory, imported with optional:configtree:/etc/secrets/: each file name is a key and the contents are the value, which is how mounted secrets look.

The measured config-tree run read db.username and db.password from two files and printed the password only as "22 characters", then printed null for both without the import.

I use environment variables for simple settings, mounted config trees for secrets (they are not visible in kubectl describe pod the way env vars can be), and the jar's files only for defaults that are safe everywhere.

"What is the difference between spring.config.import and spring.config.location?"

spring.config.import adds extra sources on top of the normal ones: the usual files are still read, and the imported sources rank above the file that imported them. It supports prefixes: optional: (do not fail if the file is missing), file:, classpath:, configtree: and external config systems.

spring.config.location replaces the default search locations. If you set it to /etc/qb/, Spring no longer looks in the jar's classpath:/ locations, unless you list them too. That is rarely what you want, and a missing application.properties then shows up as every default disappearing at once. There is also spring.config.additional-location, which adds locations without replacing.

My default is spring.config.import with optional:, because the failure mode of a typo is "the optional file is ignored", which I see in a startup log, instead of "half my config vanished".

"How do you stop the typo problem, a misspelled variable that silently does nothing?"

Make the setting required and validated. In the measured demo, @ConfigurationProperties(prefix = "quickbite.payments") on a record with @NotBlank String url, plus @Validated, makes the application fail at start with "Property: quickbite.payments.url, Value: null, Reason: must not be blank" when only the misspelled QUICKBITE_PAYMENTS_URI is set. With the correct QUICKBITE_PAYMENTS_URL it starts and prints the gateway.

So: use typed properties classes for anything important, give no default for values that must differ per environment (database URL, gateway URL), and let validation stop a mis-configured pod before it takes traffic. A dev default in application.properties that points to a dev database is exactly how a production pod ends up on the dev database: the default is used silently when the real variable is wrong.

Also log, at start, the non-secret values that matter (spring.datasource.url with the password removed). The next typo is then visible in the first log lines.

Q67 · Scenario. "A property set in application-prod.yml is ignored in production. Diagnose."

Reveal answer

Strong answer I treat this as "which of five things is true?" and I test each with the tools above, in order of how often they are the cause.

  1. The prod profile is not active. The file is read only when spring.profiles.active includes prod. Check the log line "The following 1 profile is active" or /actuator/env (activeProfiles). In the measured precedence run, "without the profile" the winner was application.properties: the profile file was simply not loaded.
  2. The name does not match. The file must be application-<profile>.yml and the profile name must be the same string. application-production.yml is never read for prod; a typo in the profile, or application-prod.yaml (extension) in a place that does not look for it, gives the same effect.:
  3. A stronger source overrides it. An environment variable, a system property, a command-line argument or an imported file sits above profile files. /actuator/env/<key> shows which source won.:
  4. The key is wrong or not bound. A typo in the key, wrong YAML indentation (a key landed under another parent), or a property name that no longer exists after an upgrade. YAML is strict about spaces; the migrator (properties migrator) reports renamed keys.:
  5. The file is not on the classpath of the running app. It was left out of the jar (wrong folder), or the container runs an old image. Check with jar tf app.jar | grep prod.:

Also note the YAML-specific rules. In one multi-document YAML, a document is selected by spring.config.activate.on-profile: prod; the old spring.profiles key inside a document was removed. And spring.config.activate.on-profile cannot be used in a profile-specific file.

The proof is always the same: ask Spring. GET /actuator/env/the.key returns the value and the source; if the source is the profile file, the problem is in your reading of the value, and if it is another source, you have found the override. If the key is absent from every source, one of items 1, 2, 4 or 5 is true.

Then fix the process, not just the pod: print the active profiles at start-up, fail the start if a required property has no value (Q66), and test the prod configuration in CI with @ActiveProfiles("prod") against a test database.

Picture it

The setup: A tiny program prints the winner and the defining sources of quickbite.db.url, once with the prod profile active and once without it. A second, wrong variable name QUICKBITE_DB_URI is also tried.

application-prod.properties · Boot 4.2runs offline
# file name decides the profile: application-<profile>.properties
quickbite.db.url=jdbc:h2:mem:from-profile-file

Make the invisible visible: Run with and without the profile, and with the typo.

run --demo=precedence · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
# profile prod is active
--- without the system property
winner : jdbc:h2:mem:from-env-var
sources that define quickbite.db.url, highest first:
  systemEnvironment                             -> jdbc:h2:mem:from-env-var

# without the profile
  file [application-prod.properties]            -> jdbc:h2:mem:from-profile-file
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- without the environment variable
winner : jdbc:h2:mem:from-profile-file

# the typo QUICKBITE_DB_URI
winner : jdbc:h2:mem:from-application-properties
sources that define quickbite.db.url, highest first:
  file [application.properties]                 -> jdbc:h2:mem:from-application-properties
--- the typo: QUICKBITE_DB_URI instead of QUICKBITE_DB_URL

What you see: With the profile active, application-prod.properties is listed and wins over the plain file. Without it, the profile file does not even appear in the list. With the typo, the environment variable is not listed at all, because its name maps to a different key.

Why: A property source that Spring does not load, or that is overridden, leaves no trace unless you print the list. The list is the diagnosis.

Silent

The prod file is never loaded.

shellruns offline
$ java -jar app.jar
# no profile active
# application-prod.yml: not read
# default URL used

Explicit

The profile is active and logged.

shellruns offline
$ SPRING_PROFILES_ACTIVE=prod \
    java -jar app.jar
# "The following 1 profile is
#  active: prod"

The shift: Activate the profile in the deployment manifest and check the log line.

Land it I diagnose a missing property by asking Actuator which profiles are active and which source won, before I touch the file.

Likely follow-ups
"How do I use several documents in one application.yml, each for a profile?"

Separate the documents with --- and mark each with spring.config.activate.on-profile:

application.yml · Boot 4.2runs offline
quickbite:
  greeting: hello from the default document
---
spring:
  config:
    activate:
      on-profile: prod
quickbite:
  greeting: hello from the prod document
  db:
    pool: 20

The first document has no condition, so it always applies. The second applies only when prod is active, and its keys override the first. The measured profiles run printed hello from the default document with no profile and hello from the prod document with --spring.profiles.active=prod, together with the group's pool size 20.

Documents are processed in order, and a later document overrides an earlier one. Keep the documents short: if a profile needs fifty lines, a separate application-prod.yml is clearer.

"What are profile groups and when are they useful?"

A group names a set of profiles that always go together: spring.profiles.group.prod=proddb,metrics means that activating prod also activates proddb and metrics. In the measured run --spring.profiles.active=prod printed active profiles : [prod, proddb, metrics].

They are useful when an environment is made of several independent concerns: database settings, metrics, mail. Each concern lives in its own file (application-proddb.yml), and the environment variable has just one word to set. Without groups, people list five profiles in every manifest and forget one.

Groups must be declared in a file that is loaded early, such as the main application.yml, not in a profile-specific one.

"The value looks right in /actuator/env, but the bean still has the old value. Why?"

Most often the bean captured the value too early or in a different way. @Value is resolved once when the bean is created, so changing the environment later does nothing. A @ConfigurationProperties object is also bound at start; there is no live refresh without Spring Cloud's @RefreshScope.

A second cause: the bean is created from another property name (a different key, or a default in the code that you think is overridden). A third: a static or final field copied the value at class load.

Check with /actuator/configprops, which lists each @ConfigurationProperties bean and the values bound to it. If it shows the new value and the bean behaves as old, the bean copied the value. If it shows the old value, the source is the problem, and you are back to /actuator/env.

"What should never go into application-prod.yml in the repository?"

Secrets: passwords, API keys, tokens, private URLs with credentials. Anything in the repository lives in history forever and in every developer's clone. Put secrets in the platform: a Kubernetes Secret mounted as a config tree, a vault, or the cloud's secret manager, and import them (spring.config.import=optional:configtree:/etc/secrets/).

Keep in the file only values that are safe to publish: pool sizes, timeouts, feature flags. Use placeholders for values that must come from outside (${DB_PASSWORD}), and make the property required through validation (Q66) so that a missing secret stops the start instead of connecting with an empty password.

Add a secret scanner (gitleaks or the host's push protection) to CI. It catches the one time somebody pastes a real key to "just test".

Q68. "@ConfigurationProperties versus @Value — when do you use each?"

Reveal answer

Strong answer Both read a property into a bean. @Value("${quickbite.limits.max-items:10}") injects one value into a field or parameter. @ConfigurationProperties(prefix = "quickbite.limits") binds a group of properties with the same prefix into a typed object, usually a record or a small class. This is revision of E4's configuration section; here is the practical rule.

Use @ConfigurationProperties for anything with more than one or two related settings, for anything you want validated, and for everything that must work with relaxed binding. Its advantages: a typed Duration or DataSize (45s, 10MB), nested objects and lists, @Validated with @NotBlank or @Min, IDE hints from the generated metadata, a single place to see all settings, and easy testing (create the record by hand).

Use @Value for a single, simple, rarely used value in one class, or when you need a SpEL expression. It is quick, and in a small service it is fine.

The difference in binding is real and measured. @ConfigurationProperties accepts several spellings of the same key: order-timeout (kebab case, the recommended form in files), orderTimeout, order_timeout, and for environment variables ORDERTIMEOUT or ORDER_TIMEOUT. @Value has exact matching only, apart from limited relaxed rules for a canonical kebab-case key. If your @Value key is written orderTimeout and the file has order-timeout, it will not be found.

Other differences: @ConfigurationProperties can fail the start-up when a required value is missing (validation), while @Value with no default fails only with an unresolved placeholder error and nothing else. Constructor binding works with records and keeps the object immutable.

My choice for a service: one properties record per feature, enabled with @EnableConfigurationProperties or @ConfigurationPropertiesScan, and no @Value outside tiny cases.

Picture it

The setup: A record Limits(Duration orderTimeout, int maxItems) is bound from the prefix quickbite.limits, with defaults 30 s and 10. The program is started with the same setting spelled in different ways, as a file key, as a command-line argument and as environment variables.

RelaxedDemo.java (excerpt) · Boot 4.2runs offline
@ConfigurationProperties(prefix = "quickbite.limits")
record Limits(@DefaultValue("30s") Duration orderTimeout,
              @DefaultValue("10") int maxItems) { }

Make the invisible visible: Run it with nine different spellings.

run --demo=relaxed · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
--- application.properties/yml spelling: quickbite.limits.order-timeout=45s (kebab case)
orderTimeout = PT45S, maxItems = 10
--- camelCase: --quickbite.limits.orderTimeout=40s
orderTimeout = PT40S, maxItems = 10
--- underscore: --quickbite.limits.order_timeout=35s
orderTimeout = PT35S, maxItems = 10
--- env var QUICKBITE_LIMITS_ORDERTIMEOUT=25s
orderTimeout = PT25S, maxItems = 10
--- env var QUICKBITE_LIMITS_ORDER_TIMEOUT=20s
orderTimeout = PT20S, maxItems = 10
--- env var QUICKBITE_LIMITS_MAXITEMS=7
orderTimeout = PT30S, maxItems = 7
--- env var QUICKBITE_LIMITS_MAX_ITEMS=7
orderTimeout = PT30S, maxItems = 7
--- no setting at all
orderTimeout = PT30S, maxItems = 10
--- wrong env var name QUICKBITE_LIMIT_MAXITEMS=7
orderTimeout = PT30S, maxItems = 10

What you see: Kebab case, camelCase and underscore command-line spellings all bind, and so do environment variables with or without the underscore between the words. The last one, QUICKBITE_LIMIT_MAXITEMS (note LIMIT, not LIMITS), binds nothing, and the default 10 stays.

Why: Relaxed binding normalises both the property name and the variable name before comparing, which makes many spellings legal. It cannot fix a different word.

@Value

One key at a time, exact spelling, no validation.

Mail.java · Boot 4.2runs offline
@Value("${quickbite.mail.host}")
String host;
@Value("${quickbite.mail.port:25}")
int port;

@ConfigurationProperties

A typed, validated group with relaxed binding.

MailProps.java · Boot 4.2runs offline
@Validated
@ConfigurationProperties("quickbite.mail")
record MailProps(
    @NotBlank String host,
    @DefaultValue("25") int port) { }

The shift: A typed record catches missing and mistyped settings at start-up; scattered @Value strings do not.

Land it I bind related settings with a validated @ConfigurationProperties record and keep @Value for a single simple value.

Likely follow-ups
"How do I validate properties, and what happens when validation fails?"

Add @Validated to the properties class and constraint annotations on its fields: @NotBlank String url, @Min(1) int maxItems, @NotNull Duration orderTimeout. For nested objects add @Valid. Bean Validation (the validation starter) must be on the classpath.

If a value breaks a constraint, the application context fails to start, and Spring Boot's failure analyser prints a readable report. The measured run showed "APPLICATION FAILED TO START ... Binding to target ... failed: Property: quickbite.payments.url, Value: "null", Reason: must not be blank. Action: Update your application's configuration".

That is much better than a NullPointerException at the first payment. The cost is zero at runtime, so I validate every setting that has no sensible default.

"What are records and constructor binding for properties?"

A record gives you an immutable properties object: all values arrive through the constructor at start, and nobody can change them later. Spring Boot binds records by constructor automatically (a class with a single constructor and no setters works the same way). @DefaultValue on a component supplies a default.

Immutability removes a class of bugs where some code mutates a shared properties bean. Records are also easy to create in tests: new Limits(Duration.ofSeconds(1), 2).

If a class has several constructors, mark the one to use with @ConstructorBinding; for JavaBean-style binding, provide setters and a no-argument constructor.

"Can properties change at runtime without a restart?"

Not with plain Spring Boot. The @ConfigurationProperties bean is bound once at start-up. Changing a file, or the environment of a running pod, does nothing. Actuator's env endpoint can set properties in memory in some setups, but beans do not see the change.

Spring Cloud adds @RefreshScope and a /actuator/refresh endpoint, which rebuilds the scoped beans with new values. On Kubernetes the common approach is simpler: change the ConfigMap and roll the pods. Rolling restarts are predictable, and every pod ends with the same state.

For values that need real-time change (a feature flag, a rate), do not use configuration at all: read them from a service that caches a flag store.

"How do I show configuration values in documentation and in the IDE?"

Add spring-boot-configuration-processor as an optional dependency. At compile time it creates META-INF/spring-configuration-metadata.json with every property, its type, default and the Javadoc of the field. IDEs use it for auto-complete in application.yml, and for warnings on unknown keys.

The metadata is also what the properties migrator and the documentation tools read. Write a one-line Javadoc on each field; it becomes the tooltip.

At runtime, /actuator/configprops lists each properties bean with the values actually bound, which is useful in an incident.

Q69. "How does auto-configuration decide to back off, and how do you write your own starter?"

Reveal answer

The real test Whether you can say the word back-off, name @ConditionalOnMissingBean and the imports file, and have actually read a conditions report.

Strong answer Auto-configuration is a set of ordinary @Configuration classes that Spring Boot loads from a list, each guarded by conditions. "Back off" means a condition says no, so the auto-configured bean is not created. The most important condition is @ConditionalOnMissingBean: "create this bean only if the application has not defined one of this type". That is why you can replace Boot's ObjectMapper, DataSource or RestClient.Builder by declaring your own: the framework steps aside.

The other conditions you meet: @ConditionalOnClass (a library is on the classpath), @ConditionalOnProperty (a switch in configuration), @ConditionalOnBean, @ConditionalOnWebApplication. They are evaluated at start-up in a defined order, and a failing condition removes the whole configuration class or just one bean method.

Writing your own starter follows from that. A starter is usually two parts:

  1. An auto-configuration class annotated @AutoConfiguration, with @ConditionalOnClass for the library it needs, @ConditionalOnProperty for an off switch (with matchIfMissing = true for "on by default"), and @ConditionalOnMissingBean on every bean method so the application can override it.:
  2. A registration file, the AutoConfiguration.imports file under META-INF/spring, containing the class names, one per line. Without this file nothing loads it.:

A typed @ConfigurationProperties class (quickbite.audit.prefix) gives users settings. Packaging: an optional -starter module with only dependencies, and an -autoconfigure module with the code, though small starters often combine them.

This is the custom-starter idiom. The measured demo below has all four behaviours: the default bean appears, the application's own bean replaces it, a property turns it off, and a second property changes its prefix. The --debug conditions report shows why.

Picture it

The setup: The quickbite-audit-starter module has QuickbiteAuditAutoConfiguration (shown), its .imports file, and an AuditLogger. An application depends on it. Four runs: plain, with its own AuditLogger bean, with quickbite.audit.enabled=false and with quickbite.audit.prefix=QB.

QuickbiteAuditAutoConfiguration.java · Boot 4.2runs offline
@AutoConfiguration
@ConditionalOnClass(AuditLogger.class)
@ConditionalOnProperty(prefix = "quickbite.audit", name = "enabled",
                       matchIfMissing = true)
@EnableConfigurationProperties(AuditProperties.class)
public class QuickbiteAuditAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public AuditLogger auditLogger(AuditProperties props) {
        return new AuditLogger(props.getPrefix(), System.out::println);
    }
}
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsruns offline
com.quickbite.audit.QuickbiteAuditAutoConfiguration

Make the invisible visible: Run the four variations.

run --demo=starter · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
$ java -jar app.jar --demo=starter
AuditLogger bean : present, defined in class path resource [com/quickbite/audit/QuickbiteAuditAutoConfigura...
[starter] AUDIT user=amy action=refund order 1042
kafkaAuditTopic  : false

$ java -jar app.jar --demo=starter --own=true
AuditLogger bean : present, defined in class path resource [com/quickbite/wiring/StarterDemo$OwnAuditLogger...
[app] APP-AUDIT user=amy action=refund order 1042
kafkaAuditTopic  : false

$ java -jar app.jar --demo=starter --quickbite.audit.enabled=false
AuditLogger bean : absent
kafkaAuditTopic  : false

$ java -jar app.jar --demo=starter --quickbite.audit.prefix=QB
AuditLogger bean : present, defined in class path resource [com/quickbite/audit/QuickbiteAuditAutoConfigura...
[starter] QB user=amy action=refund order 1042
kafkaAuditTopic  : false

What you see: Plain run: the bean is defined in the starter's class and prints [starter] AUDIT .... With the app's own bean the definition location is the app's class and the starter's bean backs off. With enabled=false the bean is absent. With prefix=QB the line starts with QB.

Why: The conditions are evaluated against the beans and properties known at the time. Auto-configurations are processed after the application's own beans, which is what lets @ConditionalOnMissingBean see the app's choice.

No back-off

The starter's bean collides with the app's.

StarterConfig.javaruns offline
@Bean
public AuditLogger auditLogger(...) {
    return new AuditLogger(...);
}
// app also defines auditLogger

With back-off

The starter yields to the application.

StarterConfig.javaruns offline
@Bean
@ConditionalOnMissingBean
public AuditLogger auditLogger(...) {
    return new AuditLogger(...);
}

The shift: A starter that cannot be replaced is a trap; add @ConditionalOnMissingBean to every bean.

Land it A good starter is on by default, has an off switch, backs off in front of the application's own bean, and is registered in the imports file.

Likely follow-ups
"How do I see why an auto-configuration did or did not apply?"

Start with --debug (or debug=true). Boot prints a conditions evaluation report with sections "Positive matches", "Negative matches" and "Unconditional classes". For each entry you see the conditions: for example @ConditionalOnMissingBean ... found beans of type for the case where the app overrode our bean, and @ConditionalOnProperty ... found different value for the disabled case. The measured excerpt had exactly those lines.

At runtime, /actuator/conditions returns the same data as JSON. To see the beans themselves, /actuator/beans.

A short rule: read negative matches for the class you expected, and the first failed condition tells you what is missing.

"What is @ConditionalOnMissingBean best practice, and what are the traps?"

Put it on every bean method in your auto-configuration, with the return type or an explicit value, so that the application can override each bean on its own. Without it, defining a bean of the same name fails at start (see the next question), and defining one of the same type causes NoUniqueBeanDefinitionException where it is injected.

The trap is ordering. @ConditionalOnMissingBean can only see beans that are already registered. Auto-configuration classes are processed after user configuration, so user beans are visible. But two auto-configurations that depend on each other need @AutoConfiguration(after = OtherAutoConfiguration.class) so that the condition sees the right state.

Another trap: applying it to a bean of a very general type such as String or Object backs off whenever any such bean exists. Use your own types.

"What do @ConditionalOnClass and spring-boot-starter modules buy library authors?"

@ConditionalOnClass(KafkaProducer.class) makes a configuration active only when the library is on the application's classpath. Your starter can support Kafka, Redis and JMS in one jar, and each part switches on only for applications that bring that dependency. In the measured run the nested KafkaAuditSinkConfiguration did not match because Kafka was not on the classpath, and it printed kafkaAuditTopic : false.

Always put such a conditional on a nested class or a separate configuration class. If the missing library appears in the signature of a bean method of the outer class, the class fails to load with NoClassDefFoundError before the condition is checked.

Starters themselves are mostly empty jars that pull dependencies. Boot 4's modular starters (see section 11) apply the same idea to the framework.

"What breaks if my starter's bean has the same name as one in the application?"

By default Spring Boot forbids overriding bean definitions. Two beans with the same name auditLogger make start-up fail. In the measured run, a starter without @ConditionalOnMissingBean and an application bean of the same name stopped with: "The bean 'auditLogger', defined in class path resource [...QuickbiteAuditAutoConfiguration.class], could not be registered. A bean with that name has already been defined in ... and overriding is disabled. Action: Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true".

Do not turn overriding on as a fix; it makes the winner depend on load order, which is the kind of bug that appears after an upgrade. The right fix is on the starter's side: @ConditionalOnMissingBean. That is the next question in the drill, Q70.

Q70 · Scenario. "Your starter's bean replaces the application's own bean. Fix it."

Reveal answer

Strong answer There are two different symptoms hiding behind this sentence, and the first job is to tell them apart.

In the first, start-up fails with "The bean 'auditLogger' ... could not be registered. A bean with that name has already been defined ... and overriding is disabled". Spring Boot forbids two bean definitions with the same name unless you opt in. In the second, start-up works but the starter's version quietly wins, and the application's bean is never used, for example because spring.main.allow-bean-definition-overriding=true is on, or because the names differ and the injection point picks the wrong one by type or @Primary.

The fix belongs in the starter, not in the application:

  1. Add @ConditionalOnMissingBean to the starter's @Bean method. The auto-configuration is processed after the application's own configuration, so the condition sees the application's bean and the starter backs off.:
  2. Check the .imports registration: the class must be listed as an auto-configuration (not found by component scanning). A starter class that the application's component scan happens to pick up is treated as user configuration and the condition runs too early.
  3. Do not set allow-bean-definition-overriding=true to hide it. With it on, the last definition wins, and "last" depends on load order, which can change when a dependency is upgraded.:

If you do not control the starter, you have three honest options: define your bean with the same type and rely on the starter's back-off (if it has one), exclude the starter's auto-configuration with @SpringBootApplication(exclude = ...) or spring.autoconfigure.exclude, or mark your own bean @Primary so that injection by type chooses it.

The measured demo shows both sides. A starter without back-off stops the app with the message above. The same starter with @ConditionalOnMissingBean lets the application's OwnAuditLogger win: the bean's definition location is the application's class and the log line starts with [app].

Finally add a test in the starter: a ApplicationContextRunner test with a user bean, asserting that the starter's bean is absent. It is the cheapest guard against this regression.

Picture it

The setup: The audit starter is built in two versions: one without @ConditionalOnMissingBean, one with it. The application defines its own auditLogger bean (OwnAuditLogger) and starts with --own=true.

Make the invisible visible: Start the application against each starter version.

run --demo=starter --own=true · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
# starter WITHOUT @ConditionalOnMissingBean
$ java -jar app.jar --demo=starter --own=true     # starter WITHOUT @ConditionalOnMissingBean
APPLICATION FAILED TO START
***************************
Description:
The bean 'auditLogger', defined in class path resource [com/quickbite/audit/QuickbiteAuditAutoConfiguration...
Action:

# starter WITH @ConditionalOnMissingBean
AuditLogger bean : present, defined in class path resource [com/quickbite/wiring/StarterDemo$OwnAuditLogger...
[app] APP-AUDIT user=amy action=refund order 1042
kafkaAuditTopic  : false

What you see: Without back-off the application refuses to start and names both definitions. With back-off it starts, the bean is defined in StarterDemo$OwnAuditLogger, and the printed line is [app] APP-AUDIT ....

Why: Bean names are unique keys in the registry. Two definitions with one name is a conflict by default, and a condition is the polite way for the second definition to withdraw.

Starter without back-off

Start-up fails on the duplicate name.

Auto.javaruns offline
@Bean
public AuditLogger auditLogger() {
    return new AuditLogger();
}
// app: own auditLogger
// -> APPLICATION FAILED TO START

Starter with back-off

The application's bean wins.

Auto.javaruns offline
@Bean
@ConditionalOnMissingBean
public AuditLogger auditLogger() {
    return new AuditLogger();
}
// app bean used: [app] APP-AUDIT

The shift: Back-off turns a collision into a clean override.

Land it I fix a starter that overrides the application by adding @ConditionalOnMissingBean on the starter side and a context-runner test, never by allowing overriding.

Likely follow-ups
"What is ApplicationContextRunner and how does it test a starter?"

ApplicationContextRunner builds a small application context inside a test, without starting a server or scanning your whole application. You tell it which auto-configurations to load, add user beans or properties, and run assertions against the resulting context.

A test for back-off looks like this:

AuditStarterTest.java · Boot 4.2runs offline
new ApplicationContextRunner()
    .withConfiguration(AutoConfigurations.of(QuickbiteAuditAutoConfiguration.class))
    .withBean(AuditLogger.class, () -> own)
    .run(ctx -> assertThat(ctx).getBean(AuditLogger.class).isSameAs(own));

Another test checks the default: no user bean, the starter's bean is present. A third passes .withPropertyValues("quickbite.audit.enabled=false") and asserts ctx has no AuditLogger.

The tests run in milliseconds and cover exactly the four behaviours the demo showed. Library authors write them for every condition they add.

"When would you use @Primary or @Qualifier instead of back-off?"

When both beans must exist. If the application needs the starter's logger for one purpose and its own for another, back-off is wrong, because it removes the starter's bean. Then inject by qualifier (@Qualifier("ownAudit")) where the specific one is needed, and mark one @Primary as the default for unqualified injection points.

@Primary decides only injection by type. It does not remove the other bean, so both still run their own initialisation and any scheduled work. That matters if the starter's bean has side effects at start-up.

If only one should exist, use back-off. If two should exist, use qualifiers. If you are unsure, the number of beans in /actuator/beans tells you which situation you are in.

"Why is my starter's auto-configuration not loaded at all?"

Check four things in order. The registration file must be at the AutoConfiguration.imports file under META-INF/spring inside the jar, with fully qualified class names, one per line. The old spring.factories key EnableAutoConfiguration was removed for this purpose in Boot 3, so an old starter that uses it is silently ignored. The class must be annotated @AutoConfiguration. And the class must not be in the application's component-scan package, or it is processed as normal user configuration.

Then read the conditions report (--debug): the class appears under negative matches with the failing condition, for example @ConditionalOnClass did not find required class. If it appears nowhere, the imports file was not found in the jar: check with jar tf.

In multi-module builds the usual cause is that the autoconfigure module was built without src/main/resources in the artifact.

"How do I let users exclude an auto-configuration?"

Three ways. In code: @SpringBootApplication(exclude = ...). In configuration: spring.autoconfigure.exclude, which is handy per environment. And through your own off switch, the property quickbite.audit.enabled=false, which the measured demo used.

A good starter offers the property switch, because it is documented, discoverable in the IDE (through the metadata file) and does not require the user to know a class name. The exclude mechanism remains the last resort and works for every starter.

Excluding by class name breaks silently when the class is renamed: Boot fails the start if the class named in exclude cannot be found, which is the useful behaviour for @SpringBootApplication(exclude=...) and a reason to prefer the typed form.

Q71. "Walk through a bean's lifecycle callbacks in order."

Reveal answer

Strong answer A singleton bean goes through a fixed sequence between "Spring decides to create it" and "the context closes". Knowing the order tells you where each kind of work belongs. Here is the order measured in the demo (a Kitchen bean with every callback, plus a custom BeanPostProcessor, an ApplicationRunner, a CommandLineRunner and listeners for the Spring Boot events).

  1. Constructor: the object is created. Constructor-injected dependencies are available; nothing else is.
  2. Setter or field injection: @Autowired setters and fields are filled.
  3. Aware callbacks (BeanNameAware and similar) and BeanPostProcessor.postProcessBeforeInitialization.:
  4. @PostConstruct, then InitializingBean.afterPropertiesSet(), then a custom initMethod from @Bean(initMethod=...). All three are "init" hooks; that is their order.:
  5. BeanPostProcessor.postProcessAfterInitialization: this is where proxies are created (transactions, caching, async). The bean you finally get may be a wrapper around the one you built.
  6. SmartInitializingSingleton.afterSingletonsInstantiated(): after all singletons exist.
  7. Events: ContextRefreshedEvent, then ApplicationStartedEvent, then the runners (CommandLineRunner, ApplicationRunner; order not guaranteed), then ApplicationReadyEvent: the app is ready for traffic.
  8. Shutdown: ContextClosedEvent, then @PreDestroy, then DisposableBean.destroy(), then a custom destroyMethod.

Two points of honesty from the measurement. The CommandLineRunner ran before the ApplicationRunner (the order of declaration), and the custom BeanPostProcessor's "before" callback printed ahead of @PostConstruct. Both orders are documented as implementation details or controlled by @Order, so do not build on them.

Where to put work: validation of injected values in @PostConstruct (the bean is only half proxied, so do not call other proxied methods in it); work that needs every bean in SmartInitializingSingleton; warm-up that may call remote services in ApplicationReadyEvent, because readiness probes do not yet pass; one-shot tasks that need command-line args in a runner.

The classic bug: calling a @Transactional or @Cacheable method of the same bean from @PostConstruct. The proxy is applied after initialisation, so the call is not advised: no transaction, no caching.

Picture it

The setup: Kitchen implements InitializingBean, DisposableBean, has @PostConstruct, @PreDestroy, an @Autowired setter, and @Bean(initMethod, destroyMethod). A BeanPostProcessor, two runners and event listeners print their own lines. Every line is numbered as it prints.

Make the invisible visible: Start the context, let it become ready, then close it.

run --demo=lifecycle · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
 1  Kitchen: constructor
 2  Kitchen: @Autowired setter (menu injected)
 3  BeanPostProcessor: before init callbacks
 4  Kitchen: @PostConstruct
 5  Kitchen: afterPropertiesSet()
 6  Kitchen: @Bean(initMethod = customInit)
 7  BeanPostProcessor: after init callbacks
 8  Kitchen: SmartInitializingSingleton.afterSingletonsInstantiated()
 9  ContextRefreshedEvent
10  ApplicationStartedEvent
11  CommandLineRunner.run()
12  ApplicationRunner.run()
13  ApplicationReadyEvent (the app is ready for traffic)
14  ContextClosedEvent (shutdown begins)
15  Kitchen: @PreDestroy
16  Kitchen: destroy() (DisposableBean)
17  Kitchen: @Bean(destroyMethod = customDestroy)

What you see: Lines 1 to 7 are creation and initialisation of one bean. Line 8 comes after all singletons exist. Lines 9 to 13 are the application-level events and runners, ending at ApplicationReadyEvent. Lines 14 to 17 are shutdown, in the reverse spirit: stop accepting, then @PreDestroy, destroy(), custom destroy.

Why: Spring Framework owns lines 1 to 9 and 14 to 17 (the container). Spring Boot adds lines 10 to 13 around SpringApplication.run. Seeing them in one list explains why some hooks see a ready app and others do not.

Work in the constructor

A call to a proxied method too early.

Cache.javaruns offline
@Service
class Warm {
  Warm(PriceService p) {
    p.price("biryani");  // proxies?
  }
}

Work after the context is ready

Everything is wired and proxied.

Warm.javaruns offline
@Component
class Warm {
  @EventListener(ApplicationReadyEvent.class)
  void warm() {
    prices.price("biryani");
  }
}

The shift: Do warm-up and remote calls when the application is ready, not while it is being built.

Land it I put validation in @PostConstruct, cross-bean work in SmartInitializingSingleton, and warm-up in ApplicationReadyEvent, and I never rely on the order of two runners.

Likely follow-ups
"Why does a @Transactional call inside @PostConstruct not open a transaction?"

Because the proxy does not exist yet. @Transactional is applied by a BeanPostProcessor in postProcessAfterInitialization, which runs after @PostConstruct. When @PostConstruct runs, the code is inside the raw object, and this.save() calls the real method directly, with no advice. The same holds for @Cacheable and @Async.

If the bean needs to load data in a transaction at start-up, run it after the context is refreshed: an ApplicationReadyEvent listener in a bean, injecting another bean (a proper proxy) to do the work, or a CommandLineRunner.

The same trap affects a @PostConstruct that calls an injected bean which is not yet fully initialised because of dependency order. Spring initialises dependencies first, so the injected bean's own @PostConstruct has run, but its proxy features work only if it is a different bean.

"What is the difference between BeanFactoryPostProcessor and BeanPostProcessor?"

A BeanFactoryPostProcessor works on bean definitions before any bean is created: it can change or add definitions (property placeholders ${...} are resolved this way; @Configuration class processing is one too). A BeanPostProcessor works on bean instances: it is called for every bean after creation, before and after the init callbacks, and may replace the instance with a proxy.

Almost all of Spring's annotation features are BeanPostProcessors: @Autowired handling, @PostConstruct handling, @Async, @Transactional and @Cacheable proxies (see section 03). In the measured output, the custom post-processor's lines 3 and 7 wrap the init callbacks.

You rarely write either. When you do, declare a BeanPostProcessor as a static @Bean method so that its own configuration class does not get created too early, which would disable some processing for that class.

"Is @PreDestroy always called?"

Not always. It runs on a graceful shutdown: SIGTERM (Kubernetes pod termination), System.exit, or ctx.close(). It does not run after kill -9, after an out-of-memory crash, or when the JVM is hard-stopped. Prototype-scoped beans are never destroyed by the container: Spring hands them over and forgets them.

So do not put critical cleanup there that must happen. For cleanup that only makes the shutdown tidy (closing a pool, flushing a buffer) it is right. For must-happen work (marking a job as stopped) store state so a restart can repair it.

Mind the time budget. Kubernetes sends SIGTERM, waits terminationGracePeriodSeconds (30 s by default), and then sends SIGKILL. With server.shutdown=graceful, Boot waits for in-flight requests first; @PreDestroy code must be quick.

"What changes with SmartLifecycle compared with these callbacks?"

SmartLifecycle is for components that start and stop work: a message listener, a poller, a scheduler. It has start(), stop(), isRunning() and a phase number. Spring starts lifecycle beans in ascending phase order after the singletons exist and stops them in descending order, so a consumer (high phase) stops before the connection pool it uses (low phase).

Unlike @PostConstruct it is meant for long-running activity, and stop(Runnable callback) supports asynchronous shutdown with a timeout (spring.lifecycle.timeout-per-shutdown-phase).

Spring Boot's web server and Kafka/AMQP listener containers use it. If your own bean starts a thread in @PostConstruct, move it to SmartLifecycle and you get ordered, controllable start and stop.

Q72 · Scenario. "Startup fails with "The dependencies of some of the beans in the application context form a cycle". Fix it properly."

Reveal answer

Strong answer A circular dependency means bean A needs B to be built and B needs A. With constructor injection neither can be created first. Since Spring Boot 2.6 cycles are prohibited by default, which is why start-up stops with a diagram of the cycle: orderService needs loyaltyService and loyaltyService needs orderService.

"Properly" means fixing the design, not the symptom. A cycle is usually a sign that two classes share a responsibility that belongs in a third place. I rank the fixes this way, best first:

  1. Extract the shared part into a third bean that both depend on. In the demo the loyalty service really needed only the number of orders per customer; an OrderCounter bean removed the cycle and the code got clearer. This is the real fix.:
  2. Invert with an event: OrderService publishes OrderPlaced, and the loyalty service listens. The order service no longer knows the loyalty service exists. The demo's cycle-event variant printed "amy has 20 loyalty points".
  3. Break one edge with @Lazy on a constructor parameter: a proxy is injected and resolved on first use. It starts, but the cycle is still there, now hidden behind a proxy and a first-call surprise.
  4. Setter or field injection plus spring.main.allow-circular-references=true: the last resort. It only works when at least one side uses setter or field injection; with constructor injection on both sides the app still fails, as the measured run shows.

How to find the right extraction: look at what each side calls on the other. Often one method is the culprit, and it moves to a new class with one clear job (calculating a discount, counting orders).

Prevent it: keep services in layers (controller, service, repository) and avoid same-layer calls where you can. Run an architecture test (ArchUnit or Spring Modulith's verify()) so a cycle fails the build instead of the deployment. This is the break-a-cycle idiom.

Picture it

The setup: OrderService and LoyaltyService need each other through constructors (variant Broken). The fixes: cycle-extract (a third bean OrderCounter), cycle-event (an event), cycle-lazy (@Lazy), and cycle-allow-ctor / cycle-allow-setter (the allow flag with constructor or setter injection).

Make the invisible visible: Run the broken variant and read the report.

run --demo=cycle · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
APPLICATION FAILED TO START

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  orderService defined in class path resource [.../Cycles$Broken.class]
↑     ↓
|  loyaltyService defined in class path resource [.../Cycles$Broken.class]
└─────┘

Action:

Relying upon circular references is discouraged and they are prohibited by default.
Update your application to remove the dependency cycle between beans. As a last resort,
it may be possible to break the cycle automatically by setting
spring.main.allow-circular-references to true.

// trimmed: timestamps and the first WARN line removed

Make the invisible visible: Now run each fix and the two allow-flag variants.

run --demo=cycle-extract / cycle-event / cycle-lazy / cycle-allow-* · Boot 4.2runs offline
cycle-extract      -> order of 2000 cents costs 1800
cycle-event        -> amy has 20 loyalty points
cycle-lazy         -> order of 2000 cents costs 1800
cycle-allow-setter -> order of 2000 cents costs 1800
cycle-allow-ctor   -> APPLICATION FAILED TO START (same cycle report, flag set, constructors on both sides)

What you see: The first three variants start and print a result. The allow flag fixes the setter-injection version, but with constructor injection on both sides the flag changes nothing and the same report appears.

Why: Spring can break a cycle only by creating one bean early and filling its dependencies later (setter or field injection). A constructor needs the finished dependency, so no early reference exists.

Cycle

Each side asks for the other in its constructor.

Cycle.javaruns offline
OrderService(LoyaltyService l) {..}
LoyaltyService(OrderService o) {..}
// -> start-up fails

Extracted

Both depend on a third bean.

Fixed.javaruns offline
OrderService(LoyaltyService l) {..}
LoyaltyService(OrderCounter c) {..}
OrderCounter { int countFor(..) }

The shift: The cycle was one shared responsibility in the wrong place; give it its own bean.

Land it I remove a cycle by extracting the shared responsibility or publishing an event, and I treat @Lazy and the allow flag as debts.

Likely follow-ups
"Why does spring.main.allow-circular-references=true not help with constructor injection?"

Because to create A with a constructor, Spring needs a finished B, and B's constructor needs a finished A. There is nothing to create first. The flag lets Spring expose an early reference to a half-built bean, but a half-built bean exists only after its constructor returned, and here the constructor is exactly what is blocked. The measured cycle-allow-ctor run failed with the same cycle report.

Setter and field injection split creation from wiring: Spring creates A with its default constructor, publishes the early reference, creates B with that reference, and fills A's field later. That is why cycle-allow-setter started.

It also shows the cost of the flag: it only works for the style of injection that Spring and the community tell you not to use. Constructor injection makes dependencies explicit and objects immutable, and it made the cycle visible at start-up, which is a gift.

"How can I find a cycle in a big application with fifty beans in the report?"

The failure analyser prints only the beans in the cycle, so for a long chain read the box from top to bottom and write the names. If a chain passes through proxies or auto-configured beans, run with --debug and -Dlogging.level.org.springframework.beans.factory=DEBUG to see the creation order.

To find cycles before they bite, add a test with Spring Modulith (ApplicationModules.of(App.class).verify() reports cycles between modules) or ArchUnit's slices().matching("..(*)..").should().beFreeOfCycles() for packages. Package-level cycles are the early warning of bean-level cycles.

A graph tool also helps: /actuator/beans can be dumped to JSON and turned into a graph, in which a cycle shows as a loop.

"Is a cycle ever acceptable?"

Rarely, and only with a clear reason. Some frameworks have natural two-way references (parent and child objects in a domain model), but those are plain objects, not Spring beans. Beans are collaborators with behaviour, and two collaborators that need each other usually should be one, or share a third.

An event or a Supplier / ObjectProvider is often an honest representation of "I need that later, not now": ObjectProvider<LoyaltyService> in the order service says explicitly that the dependency is optional and lazy.

If a legacy system forces a cycle, keep the flag off for new code, document the cycle in the class Javadoc, and add the removal to a backlog item with a name on it.

"What does Spring do for @Autowired field injection cycles inside a single bean?"

A bean that injects itself (directly or through a lazy proxy) is a special case. Since Spring 4.3 a bean can be injected into itself as a fallback candidate, mainly so that a method can call self.otherMethod() through the proxy, a fix for self-invocation. It is accepted but considered a smell, and the same advice applies: move the method to another bean (the self-invocation fix).

Field-injected cycles between two beans work only with the allow flag on, as the setter variant of the demo did. Without the flag Spring Boot stops the start even for field injection, which is why the default surprised many teams when they upgraded to Boot 2.6.

Q73. "ApplicationReadyEvent versus ContextRefreshedEvent versus CommandLineRunner — what does each give you?"

Reveal answer

Strong answer Three hooks, three different moments, and the demo's numbered output shows them side by side (lines 9 to 13).

ContextRefreshedEvent is a Spring Framework event. It fires when the application context has been fully built: all singletons exist, all SmartInitializingSingleton callbacks have run. It can fire more than once (a parent and a child context each publish it, and refresh() can be called again), and the web server may not be accepting requests yet. Use it only when you really mean "the container is built".

CommandLineRunner (and ApplicationRunner) are Spring Boot interfaces. After the context is refreshed and ApplicationStartedEvent has fired, Boot calls each runner with the command-line arguments (ApplicationRunner gets them parsed into options and values). Use them for one-shot work that needs the arguments: import a file, run a migration step, run a demo. They run on the main thread, in @Order, and an exception in a runner stops the start-up. In the measured run the CommandLineRunner ran first, in declaration order; use @Order rather than assume.

ApplicationReadyEvent is a Spring Boot event published last, after the runners: "the application is ready to service requests". Use it for warm-up and for anything that should happen once, when traffic may start: pre-load a cache, register with a service registry, log "ready". Because it fires once per SpringApplication, it is safer than ContextRefreshedEvent for one-time work.

A summary I give in interviews:

  • Need all beans built, no args: SmartInitializingSingleton or ContextRefreshedEvent.
  • Need command-line args, one-shot job: a runner.
  • Need "ready for traffic", once: ApplicationReadyEvent.

Two related facts for Kubernetes. Readiness probes (/actuator/health/readiness) report ACCEPTING_TRAFFIC after ApplicationReadyEvent. A long task inside a runner delays readiness, so start-up looks slow, and if it takes longer than the probe's timeout the pod is killed in a restart loop. Put long warm-up in a background thread started from ApplicationReadyEvent, and decide whether readiness should wait for it.

Picture it

The setup: One bean prints a numbered line for each hook: ContextRefreshedEvent, ApplicationStartedEvent, an ApplicationRunner, a CommandLineRunner and ApplicationReadyEvent, then the shutdown events.

Make the invisible visible: Look at lines 8 to 13 of the lifecycle output.

run --demo=lifecycle (lines 8 to 13) · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
 8  Kitchen: SmartInitializingSingleton.afterSingletonsInstantiated()
 9  ContextRefreshedEvent
10  ApplicationStartedEvent
11  CommandLineRunner.run()
12  ApplicationRunner.run()
13  ApplicationReadyEvent (the app is ready for traffic)

What you see: The refresh event comes first, then Boot's started event, then both runners, and finally the ready event. Everything before line 13 happens while the pod would still report "not ready".

Why: SpringApplication.run wraps the context refresh: refresh, started, call runners, ready. Each Boot event marks the end of one step.

ContextRefreshedEvent

Too early, and possibly fired twice.

Warm.java · Boot 4.2runs offline
@EventListener(ContextRefreshedEvent.class)
void warm() {
    // may run for parent AND child
    // context; server not yet ready
}

ApplicationReadyEvent

Once, after runners, at readiness.

Warm.java · Boot 4.2runs offline
@EventListener(ApplicationReadyEvent.class)
void warm() {
    // once; app is ready for traffic
    prices.preload();
}

The shift: Choose the hook by the moment you need: built, args available, or ready for traffic.

Land it I use a runner for one-shot args-driven work, ApplicationReadyEvent for warm-up, and I avoid ContextRefreshedEvent unless I truly mean the container is built.

Likely follow-ups
"Why would ContextRefreshedEvent fire twice?"

Because an event is published by each context. In an application with a parent and a child context (some Spring Cloud setups, Spring MVC with a separate servlet context, or an Actuator management context on a separate port), each context publishes its own ContextRefreshedEvent, and a listener in the parent hears the children's events too. Calling refresh() manually on a context fires it again.

Guard against it by checking event.getApplicationContext() equals your own context, or switch to ApplicationReadyEvent, which SpringApplication publishes once. The Boot docs recommend using Boot events for application-level hooks and Framework events for container-level ones.

Management on a separate port (management.server.port) creates a child context, so this is not rare in production.

"What is the difference between ApplicationRunner and CommandLineRunner?"

They differ only in the argument type. CommandLineRunner.run(String... args) gets the raw array, as in main. ApplicationRunner.run(ApplicationArguments args) gets parsed arguments: args.getOptionNames(), args.getOptionValues("input") for --input=a.csv, and args.getNonOptionArgs() for the rest.

Use ApplicationRunner when you read options, since you do not parse strings yourself. Both are beans, both can be ordered with @Order or Ordered, and both run before ApplicationReadyEvent.

A runner is not for work that must run for the life of the application. It runs once on the startup thread, so a never-ending loop in a runner stops the app from becoming ready.

"How do I run warm-up without delaying readiness?"

Start the work on another thread from an ApplicationReadyEvent listener (or an @Async listener) and let the app become ready. Decide explicitly what a request does before the warm-up completes: it may be slower, or it may be served from a fallback.

If requests must not be served until a cache is warm, hold readiness back: publish AvailabilityChangeEvent.publish with REFUSING_TRAFFIC before the work, and ACCEPTING_TRAFFIC after it, or add a custom health indicator to the readiness group (management.endpoint.health.group.readiness.include). Kubernetes then keeps the pod out of the Service until warm.

Set the probe's initialDelaySeconds and failureThreshold for the real warm-up duration, measured on a cold start, or the kubelet will restart the pod before it finishes.

"Where does @PostConstruct fit in this comparison?"

@PostConstruct belongs to a single bean's initialisation (step 4 in the lifecycle list). It runs while the context is still being built, before other beans may exist, and before any proxy for this bean is applied. That makes it right for validating the bean's own injected values and wrong for anything that needs the whole application.

The three hooks in this question all run later: after every singleton is built and proxied. Anything that calls other beans' advised methods (transactional, cached, secured) belongs in them. As a practical rule, if the code in @PostConstruct calls another bean, ask whether it should be an ApplicationReadyEvent listener instead.

Drill · Logging, migrations and developer experience

Nine questions on running a service: JSON logs and trace ids, changing a log level without a redeploy, Flyway and its checksum rule, and the development tools that start your dependencies.

Q74. "How do you turn on structured JSON logging in Spring Boot, and why would you?"

Reveal answer

Strong answer A normal log line is text for a human: date, level, thread, logger, message. A structured log line is a JSON object with named fields: timestamp, level, logger, message, plus fields you add. Log platforms (Elasticsearch, Loki, CloudWatch, Datadog) can then filter and count by field instead of by regular expression.

Since Spring Boot 3.4 this is built in. One property is enough: logging.structured.format.console=ecs. The built-in formats are ecs (Elastic Common Schema), logstash and gelf. The same key with .file writes the file in that format. Nothing else changes in your code: log.info("order {} found", id) is now one JSON line.

Why bother: during an outage the team grepped plain logs from twelve pods and could not join lines that belong to one request. With JSON each line carries traceId, a customer or order field and a level that a query can combine: "level=ERROR and customer=asha in the last 10 minutes". You also stop breaking lines on multi-line stack traces, because the exception becomes one field.

Adding your own fields is done through the MDC: MDC.put("customer", c) before the work, MDC.remove after (try/finally). The measured run below shows "customer":"asha" appearing as a top-level field, and the ECS line carries service name and version from spring.application.name and the build info. For fields known at start-up, use logging.structured.json.add.region=ap-south-1.

Choice of format: ECS if you ship to Elastic or use its dashboards, logstash if your pipeline expects Logback's logstash encoder shape, GELF for Graylog. They carry the same information in different field names, so pick the one the platform already expects.

Cost and care: JSON lines are bigger (about two to three times) and unreadable in a terminal, so keep a plain text profile for local development (logging.structured.format.console set only in the prod profile). And never log secrets; structure makes them easier to search, too.

This is the structured-logging idiom, shown in section 09 with trace ids.

Picture it

The setup: A small web app logs order {} found in a controller after putting the customer into the MDC. It is started three times with different log settings. Each run calls GET /orders/42 once with the header X-Customer: asha.

SvcApp.java (excerpt) · Boot 4.2runs offline
@GetMapping("/orders/{id}")
String order(@PathVariable long id,
             @RequestHeader(value = "X-Customer", defaultValue = "anon") String c) {
    MDC.put("customer", c);
    try { log.info("order {} found", id); return "order " + id; }
    finally { MDC.remove("customer"); }
}

Make the invisible visible: Print the same log line with ecs and with logstash (trimmed to the order line).

run --demo=svc --logging.structured.format.console=ecs · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
{
 "@timestamp": "2026-12-01T19:33:57.480380551Z",
 "log": {
  "level": "INFO",
  "logger": "com.quickbite.svc.SvcApp"
 },
 "process": {
  "pid": 1807020,
  "thread": {
   "name": "http-nio-18391-exec-2"
  }
 },
 "service": {
  "name": "drill",
  "version": "0.0.1-SNAPSHOT"
 },
 "message": "order 42 found",
 "customer": "asha",
 "ecs": {
  "version": "8.11"
 }
}
// the request line; trimmed: pretty-printed for reading (the app prints one line)
run --demo=svc --logging.structured.format.console=logstash · Boot 4.2runs offline
{
 "@timestamp": "2026-12-02T01:04:09.558361159+05:30",
 "@version": "1",
 "message": "order 42 found",
 "logger_name": "com.quickbite.svc.SvcApp",
 "thread_name": "http-nio-18391-exec-2",
 "level": "INFO",
 "level_value": 20000,
 "customer": "asha"
}

What you see: One line is one JSON object. The ECS one has nested objects (log.level, process.thread.name, service.name) and an ecs.version. The logstash one is flat (logger_name, thread_name, level_value). In both, the MDC entry customer: asha is a field of its own.

Why: The structured formatter replaces the layout of the console appender. It turns the log event, its MDC and its exception into JSON, so no code changes are needed.

Plain text

Fine for people, hard for queries.

consoleruns offline
2026-12-02 01:04:09 INFO
 [http-nio-exec-2] c.q.svc.SvcApp :
 order 42 found
// customer? grep and hope

Structured

One JSON object per event, with fields.

application.propertiesruns offline
logging.structured.format.console=ecs
# MDC.put("customer", c) adds
#   "customer":"asha"
# to every line in that scope

The shift: Make logs queryable by field; keep a text profile for your laptop.

Land it I switch on structured logging with one property, add request fields through the MDC, and keep plain text for local development.

Likely follow-ups
"How do I add fields that are the same on every line, like region or version?"

Use logging.structured.json.add.<name>=<value>, for example logging.structured.json.add.region=ap-south-1. The name and value become a field on every line. For values known only at runtime, put them into the MDC in a filter or interceptor, so they appear for the duration of the request.

The service name and version are taken from spring.application.name and the application's build info (spring-boot-maven-plugin with build-info). The measured ECS line had service.name = drill and service.version = 0.0.1-SNAPSHOT. Set them properly in every service: a log line without a service name is hard to attribute when twelve services write to one index.

If the built-in formats lack something, you can write a custom StructuredLogFormatter and refer to it by class name in logging.structured.format.console.

"What about exceptions and multi-line stack traces?"

In plain text a stack trace spreads over dozens of lines, and tools that read line by line split one event into pieces, which are then mixed with lines from other threads. In the structured formats the exception becomes fields of one object: type, message and the stack trace as a string (for ECS: error.type, error.message, error.stack_trace).

That makes error.type:"SQLTimeoutException" a query, and "errors by type in the last hour" a chart. The trade-off is size: a stack trace of 80 frames, repeated 1,000 times in a failure loop, is a lot of data. Logback can shorten stack traces with a root-cause-first order and a depth limit through logging.exception-conversion-word and the structured stacktrace settings (logging.structured.json.stacktrace.* in recent Boot versions: check the reference docs for the exact keys of your version).

Log an exception once, at the place that handles it. Logging it at every layer is the usual source of a hundred identical traces.

"Logback or Log4j2?"

Logback is the Spring Boot default and the right choice almost always. It is the reference implementation of SLF4J, fast enough, and every Boot feature (levels in properties, the loggers endpoint, structured formats, graceful startup) works with it out of the box.

Log4j2 is worth it when you need its specific strengths: asynchronous loggers built on the LMAX Disruptor for very high log volumes with low latency, or an existing Log4j2 setup and plugins. In Boot you exclude spring-boot-starter-logging and add spring-boot-starter-log4j2. Structured logging works there as well.

Do not switch for fashion. A log call that costs microseconds is not your bottleneck; a log volume of gigabytes an hour is, and that is solved by levels and sampling, not by the framework. Write to stdout in containers and let the platform ship it.

"How do I keep secrets and personal data out of structured logs?"

Three habits. Do not log request bodies or whole entities; log ids. Mask at the source: a toString() that hides the card number, and a small Redactor for the few places that must log user input. And review the MDC: anything you put there appears on every line in scope, so never put tokens or emails.

Then add a safety net on the platform side: field-level redaction rules in the log pipeline for known patterns (card numbers, bearer tokens). Structured logs make that easier because you can drop or hash one named field.

Finally test it: a unit test that logs a sample order and asserts the output does not contain the card number. It is the same test you would write for an API response.

Q75 · Scenario. "You need DEBUG logs for one package in production, now, without redeploying."

Reveal answer

Strong answer Use the Actuator loggers endpoint. Spring Boot keeps the log levels in the logging system (Logback), and the endpoint reads and changes them at runtime, per logger name. A POST with the new level takes effect on the next log call, in every thread, with no restart.

The steps are short:

  1. Check the current level: GET /actuator/loggers/com.quickbite.platform shows effectiveLevel (and configuredLevel if one was set explicitly).
  2. Raise it: POST /actuator/loggers/com.quickbite.platform with the JSON body {"configuredLevel":"DEBUG"}. The response is 204 No Content.
  3. Reproduce the problem and read the DEBUG lines (in the structured output they have "level":"DEBUG").:
  4. Put it back: POST {"configuredLevel":null}. This clears the explicit level, so the logger inherits again.

Always do step 4. A DEBUG level left on in one package can multiply log volume by fifty and fill the disk or the log budget, and nobody remembers it three days later. A safer habit is to limit the blast radius: raise one package, not root, and set a calendar reminder or a script that resets it after ten minutes.

Preconditions, which you must prepare before the incident: expose the endpoint (management.endpoints.web.exposure.include=health,loggers), put it behind authentication and a separate management port, and allow only operators to POST. The endpoint can also change root, so it is a powerful tool; treat it like shell access.

In Kubernetes, the change applies to one pod only (the one your request reached) and is lost when the pod restarts. That is usually what you want for a quick look. To change the level across the fleet, change configuration and roll, or call each pod. This is the runtime-log-level idiom.

Picture it

The setup: A web app has OrderController.get() with a log.debug("loading order {} from the database", id) line and an info line. The root level is warn and the package level is info. Actuator exposes loggers on the app's port.

Make the invisible visible: Request an order, raise the level, request again, reset it.

curl against the running app · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
$ curl -s localhost:18412/actuator/loggers/com.quickbite.platform
{"effectiveLevel":"INFO"}
$ curl -s localhost:18412/orders/1042      # DEBUG is off
order 1042
$ curl -i -X POST localhost:18412/actuator/loggers/com.quickbite.platform -H "Content-Type: applicati...
HTTP/1.1 204 
$ curl -s localhost:18412/actuator/loggers/com.quickbite.platform
{"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"}
$ curl -s localhost:18412/orders/1043      # DEBUG is on
order 1043
$ curl -X POST ... -d {"configuredLevel":null}   # put it back
{"effectiveLevel":"INFO"}

What you see: The first read shows effectiveLevel: INFO. After the POST (HTTP 204), the read shows configuredLevel: DEBUG. The next request produces a DEBUG line (see below), and the final POST with null puts the level back.

application log lines · Boot 4.2 (trimmed to the orders)runs offline
{"log": {"level": "INFO", "logger": "com.quickbite.platform.OrderController"}, "message": "order 1042 found, total 2000 cents", "traceId": "2d9b45ef931e60b65c1dcd0aa940f0c5"}
{"log": {"level": "DEBUG", "logger": "com.quickbite.platform.OrderController"}, "message": "loading order 1043 from the database", "traceId": "e34fdfbd79d9830a5652811d5b9eca41"}
{"log": {"level": "INFO", "logger": "com.quickbite.platform.OrderController"}, "message": "order 1043 found, total 2000 cents", "traceId": "e34fdfbd79d9830a5652811d5b9eca41"}
{"log": {"level": "INFO", "logger": "com.quickbite.platform.OrderController"}, "message": "order 1044 found, total 2000 cents", "traceId": "da3c8eac7f7c24e67eb7bb3e964124cf"}

Why: The endpoint talks to the LoggingSystem abstraction, which changes the level in Logback's logger context in memory. No file is read again and no thread is restarted.

Redeploy to change a level

Slow, loses the evidence.

stepsruns offline
1 edit application.yml
2 build, push image
3 roll 12 pods (10 minutes)
4 problem no longer happens

Change it live

Seconds, one pod, reversible.

curlruns offline
curl -X POST \
  localhost:8080/actuator/loggers/com.quickbite \
  -H 'Content-Type: application/json' \
  -d '{"configuredLevel":"DEBUG"}'

The shift: Keep the loggers endpoint ready and protected before you need it.

Land it I raise one package to DEBUG through the protected loggers endpoint, reproduce, and reset it to null so it cannot be forgotten.

Likely follow-ups
"How do I secure the loggers endpoint?"

Do not expose it on the public port. Use management.server.port=9090 and let only the cluster's internal network or the operations network reach it, with a network policy. Add Spring Security rules for the management paths: EndpointRequest.to("loggers") requires a role such as OPS, and in Boot 4 you can also restrict an endpoint's access level with management.endpoint.loggers.access=read-only (or none) in each environment, so production can allow only reads unless a flag is raised.

Expose only what you need: management.endpoints.web.exposure.include. Never * in production. Log every POST (who and what) to an audit log, since changing log levels changes what you can see and what you pay.

Check the property names against the reference for your Boot version: the access-level settings were reworked in the 3.4 line.

"Can I set a log level for several pods at once?"

The endpoint is per instance, so a script has to call each pod: list the pods with kubectl get pods -l app=orders, then loop with kubectl exec or a port-forward, or call the pod IPs from a jump host. Spring Boot Admin offers a button that does it for every registered instance.

The more robust route for a planned change is configuration: set logging.level.com.quickbite.orders=DEBUG in a ConfigMap and roll the deployment, or use spring.config.import with a config tree and a refresh. It is slower but uniform and recorded in Git.

For a sustained need, such as a new feature in canary, think about sampling instead: log at DEBUG for 1 % of requests with a filter that sets a logger level for the request using the MDC (Logback's TurboFilter or MDCFilter). That keeps volume predictable.

"What are logger groups and how do they help?"

A logger group names a set of packages so that one setting changes them all: logging.group.quickbite and then logging.level.quickbite=debug. Spring Boot predefines two groups: web (Spring MVC and Tomcat related packages) and sql (Hibernate SQL and related), so logging.level.sql=debug shows SQL statements.

Groups also work through the endpoint: POST /actuator/loggers/sql. During an incident they are quicker than remembering the package names of a framework.

Define groups for your own subsystems (payments, orders) in application.yml once, document them in the runbook, and the on-call engineer has a short vocabulary for changing detail.

"What happens to the level after a restart?"

It returns to what the configuration says. The endpoint changes only the in-memory state. So an engineer who raised a level and then saw a pod restart (a crash, a deploy, an autoscaler move) is back at the configured level, which can explain "the DEBUG lines stopped".

That is also the safety net: a forgotten DEBUG level will not survive a deploy. But do not rely on it. The reset step in the procedure is part of the habit, and some teams add an automatic reset: a scheduled task that reads a debugUntil timestamp and clears the level after it passes.

Q76. "How do you get a trace id into every log line?"

Reveal answer

Strong answer A trace id is a unique id that follows one request through every service it touches. Tracing libraries create it at the first service (or read it from an incoming traceparent header) and pass it to the next call. A span id identifies one step inside the trace. If each log line carries the trace id, you can search for it and see every line of that request across all pods.

In Spring Boot you do not write this yourself. Micrometer Tracing (Boot's actuator integration) puts traceId and spanId into the SLF4J MDC, a per-thread map that logging reads. You need a tracing bridge on the classpath (the OpenTelemetry starter, spring-boot-starter-opentelemetry, or micrometer-tracing-bridge-otel) and a sampling probability above zero (management.tracing.sampling.probability=1.0; the default is 0.1, and unsampled requests have no ids).

How the ids reach the line depends on the format. In plain text the default pattern includes [%X{traceId}-%X{spanId}] once tracing is active. In structured logging they are fields. In the measured ECS output, they appear as traceId and spanId, not the ECS standard trace.id; if your platform expects trace.id, add a mapping in the log pipeline.

The measured run was entirely offline: the OTLP exporters for traces, metrics and logs were switched off (management.tracing.export.otlp.enabled=false and similar), sampling was 1.0, and every request still got ids. A request that came with a traceparent header kept the same trace id, which is what lets a downstream service join the trace.

Three failure causes. Sampling at 0.1 means 90 % of lines have no id. Work on another thread loses the MDC (a plain @Async, a custom executor, a reactive hop) unless a decorator copies it (the task-decorator idiom). And a client that calls another service with a hand-built HttpClient does not propagate the header; use the Boot-built RestClient.Builder, which is instrumented.

And one return trip: put the trace id in the response header or in the error body (ProblemDetail) so a customer's complaint contains the key you need.

Picture it

The setup: The platform app has spring-boot-starter-opentelemetry, ECS structured logging, sampling 1.0 and every exporter disabled (no collector on this machine). One request is made per order id.

application.properties · Boot 4.2runs offline
logging.structured.format.console=ecs
management.tracing.sampling.probability=1.0
# no collector on this machine: tracing on, exporting off
management.tracing.export.otlp.enabled=false
management.otlp.metrics.export.enabled=false
management.logging.export.otlp.enabled=false

Make the invisible visible: Look at the log lines written for two different requests.

app log lines · Boot 4.2 (code/e22-spring-in-depth/D/, trimmed to message and ids)runs offline
{"message": "order 1042 found, total 2000 cents", "traceId": "2d9b45ef931e60b65c1dcd0aa940f0c5", "spanId": "838c011eb8eb9f5d"}
{"message": "loading order 1043 from the database", "traceId": "e34fdfbd79d9830a5652811d5b9eca41", "spanId": "436b3859cb78c326"}
{"message": "order 1043 found, total 2000 cents", "traceId": "e34fdfbd79d9830a5652811d5b9eca41", "spanId": "436b3859cb78c326"}
{"message": "order 1044 found, total 2000 cents", "traceId": "da3c8eac7f7c24e67eb7bb3e964124cf", "spanId": "e3bf7febd9deaa04"}

What you see: Each request has its own traceId. Inside one request, two lines (the DEBUG one and the INFO one for order 1043) share the same traceId and the same spanId, so a search on that id returns the whole story of that request.

Why: The tracing bridge opens a span for each HTTP request through Boot's observation instrumentation and copies the ids to the MDC for the span's duration. Logback reads the MDC at the moment of each log call.

No ids

Lines cannot be joined.

logruns offline
INFO order 1043 found
INFO payment started
INFO payment ok
// which request? which pod?

With trace ids

Every line has the request's key.

log (ECS fields)runs offline
"traceId":"e34fdfbd7...",
"message":"order 1043 found"
"traceId":"e34fdfbd7...",
"message":"payment ok"

The shift: Put the trace id on every line and in the error response, so one search shows one request.

Land it I get ids into lines with the tracing starter, sampling above zero and a structured format, and I carry the MDC across threads explicitly.

Likely follow-ups
"What is the difference between a trace and a span?"

A trace is the whole journey of one request: the browser call, the gateway, the order service, the payment service, the database. A span is one timed step inside it, with a start time, a duration, a name and attributes. Spans form a tree: the HTTP request is the root span, a call to the payment service is a child span, and its database query is a grandchild.

All spans of one trace share the trace id; each has its own span id and knows its parent's id. A trace viewer (Jaeger, Tempo, Zipkin) draws the tree as a waterfall, so you see which step took the time.

In logs you usually care about the trace id for joining and the span id for "which step". The measured output shows both fields.

"Why do my @Async or executor threads have no trace id?"

The MDC is a ThreadLocal. A worker thread has its own, empty one. The trace id lives in the caller's MDC and in the tracing context, and neither moves to the worker by itself. The measured @Async demo printed requestId=null on the worker (task-1) for exactly this reason.

Fix it with a TaskDecorator that copies the MDC (and, with Micrometer's context propagation library, the observation context) into the worker for the duration of the task. In Boot 4.2 a TaskDecorator bean is applied automatically to the default executor, as the async measurements in section 05 showed. Spring's ContextPropagatingTaskDecorator (from io.micrometer:context-propagation) is the ready-made version that carries trace context.

Virtual threads have the same property: new thread, empty MDC. Check any custom ExecutorService you create yourself; Executors.newFixedThreadPool knows nothing about Spring's decorators.

"How do I put the trace id into the response so a customer can quote it?"

Add it as a response header from a filter or from the observation: read it from Tracer.currentSpan().context().traceId() (Micrometer Tracing) and set X-Trace-Id. Or put it into the error body, for example as a traceId property of your ProblemDetail.

Customer support then asks for the id from the error screen, and an engineer searches the log platform for it and finds every line from every service within seconds. This one header shortens many incidents.

Mind privacy: a trace id is random and carries no personal data, so it is safe to expose. Do not expose internal span names or stack traces.

"What is the cost of sampling everything?"

Spans and ids are cheap to create; what costs is exporting and storing them. At sampling 1.0 each request produces a tree of spans that must be sent to a collector and stored. For a service with 500 requests a second and ten spans per request, that is 5,000 spans a second, a visible network and storage bill.

A typical production setting is a low sampling probability (1 % to 10 %) with tail-based sampling in the collector, which keeps the traces that had errors or were slow and drops the boring ones. The ids still appear in logs for sampled requests only, which is a reason to keep sampling for the log correlation use case in mind: with 0.1, nine in ten requests have no id.

Some teams give every request an id for logging (a correlation id from a filter) and sample spans separately. Both are valid; just be clear which one your log lines carry.

Q77. "How does Flyway run in Spring Boot, and what are the naming rules for migrations?"

Reveal answer

Strong answer Flyway is a tool that keeps a database schema in step with your code by applying numbered SQL scripts in order. With Spring Boot you add the Flyway starter (in Boot 4, spring-boot-starter-flyway; for PostgreSQL, MySQL and some others also the matching flyway-database-... module) and put scripts in src/main/resources/db/migration. Boot runs Flyway before the JPA entity manager is created, so by the time Hibernate starts, the schema is ready.

What happens at each start-up:

  1. Flyway creates the flyway_schema_history table if it does not exist.:
  2. It reads all scripts and validates the already-applied ones against the history: same version, same checksum.
  3. It applies, in version order, the scripts that are not yet in the history, each in a transaction where the database allows it, and records each in the history table.:
  4. Then the application continues; if anything fails, start-up fails.:

Naming rules, with two underscores after the version:

  • Versioned: V1__create_orders.sql, V2__add_status.sql, V2_1__index.sql. Applied once, in version order. The version can be 1, 2.1, 20261202.
  • Repeatable: R__order_summary_view.sql. No version; it is applied again whenever its checksum changes, after all versioned ones. Good for views and stored procedures.
  • Underscores in the description become spaces in the history ("create orders").

In the measured run an empty database applied three migrations: version 1 "create orders", version 2 "add status" and the repeatable "order summary view", and the history table listed each with a checksum and success=true.

Rules of safe practice: a version number is never reused, an applied file is never edited (Q78), and every change is a new file. Keep scripts small and forward-only (the forward-only idiom), and use the expand and contract pattern from E20 for changes that must be compatible with the old and new application during a rolling deploy.

Settings you meet: spring.flyway.locations (default classpath:db/migration), spring.flyway.baseline-on-migrate for an existing database, spring.flyway.clean-disabled (leave it true in production, since clean drops everything), spring.flyway.out-of-order.

Picture it

The setup: A platform app with Flyway enabled, an empty H2 file database and three scripts: V1__create_orders.sql, V2__add_status.sql, R__order_summary_view.sql. The program prints the Flyway log and then the contents of the history table.

db/migration · Boot 4.2runs offline
-- V1__create_orders.sql
create table orders (id bigint primary key, total_paise bigint not null);

-- V2__add_status.sql
alter table orders add column status varchar(20) default 'NEW' not null;

-- R__order_summary_view.sql  (repeatable)
create or replace view order_summary as select status, count(*) n from orders group by status;

Make the invisible visible: Start against an empty database and print the history.

run 1 · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
INFO org.flywaydb.core.FlywayExecutor         : Database: jdbc:h2:file:./target/flywaydb (H2 2.5)
INFO o.f.c.i.s.JdbcTableSchemaHistory         : Schema history table "PUBLIC"."flyway_schema_history" d...
INFO o.f.core.internal.command.DbValidate     : Successfully validated 3 migrations (execution time 00:...
INFO o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table "PUBLIC"."flyway_schema_h...
INFO o.f.core.internal.command.DbMigrate      : Current version of schema "PUBLIC": << Empty Schema >>
INFO o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version "1 - create orders"
INFO o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" to version "2 - add status"
INFO o.f.core.internal.command.DbMigrate      : Migrating schema "PUBLIC" with repeatable migration "or...
INFO o.f.core.internal.command.DbMigrate      : Successfully applied 3 migrations to schema "PUBLIC", n...
INFO c.q.platform.PlatformApplication         : Started PlatformApplication in 4.969 seconds (process r...
rank  version  description          type  checksum     success
-1    null     << Flyway Schema History table created >> TABLE null         true
1     1        create orders        SQL   1934866666   true

What you see: Flyway creates its history table, validates 3 migrations, applies version 1, version 2 and the repeatable one, and ends "now at version v2". The table lists the three with their checksums; the repeatable has no version (null) and a rank of 3.

Why: The history table is Flyway's memory. Without it Flyway could not know which scripts already ran; with the checksum it can tell whether an applied script still matches its file.

Hibernate generates the schema

ddl-auto=update guesses changes.

application.propertiesruns offline
spring.jpa.hibernate.ddl-auto=update
# no history
# renames become drop + add
# no review, no rollback plan

Flyway migrations

Reviewed SQL, applied once, recorded.

db/migrationruns offline
V1__create_orders.sql
V2__add_status.sql
R__order_summary_view.sql
# history table: version,
# checksum, success

The shift: Schema changes are code: versioned, reviewed and recorded.

Land it I let Flyway own the schema with small forward-only V files, repeatables for views, and I never touch an applied file.

Likely follow-ups
"Why does Flyway run before Hibernate in Spring Boot?"

Because Hibernate may validate the schema (ddl-auto=validate) or at least expects tables to exist when the first query runs. Boot makes the entityManagerFactory bean depend on the Flyway initialiser, so the migrations finish first. You can see the dependency in the measured error from Q78: "Failed to initialize dependency 'flywayInitializer' of LoadTimeWeaverAware bean 'entityManagerFactory'".

Practical rule: set spring.jpa.hibernate.ddl-auto=none or validate once Flyway owns the schema. validate makes Hibernate check that entities match the tables and fail at start if not, which catches a missing migration before the first request. Never update or create in a Flyway-managed database; two tools changing the schema produce surprises.

If other beans need the schema earlier (a JdbcTemplate bean used at start), they also depend on flywayInitializer; Boot handles the common cases.

"What happens when two pods start at once and both run Flyway?"

Flyway takes a lock on the history table (a database lock, in most databases a table lock or an advisory lock) while it migrates. The second pod waits until the first finishes, then sees an up-to-date history and applies nothing. So parallel start-ups are safe on databases that support this locking.

The risk is a long migration: pod two waits, readiness probes time out, and Kubernetes restarts it. For large migrations, run them as a separate step before the rollout (a Kubernetes Job running the Flyway command line or the application with a migrate-only profile) and let the application only validate.

With the application configured as spring.flyway.enabled=false in normal pods, and a one-shot job that sets it to true, the rollout never waits on schema work.

"How do I roll back a migration?"

Flyway's community edition has no automatic undo; undo scripts (U2__...) are a paid feature. The recommended practice is to roll forward: write a new migration that reverses or fixes the change (V3__drop_status.sql). This matches reality, because after a migration has run in production, data may have been written that an undo script could destroy.

The way to make forward-only safe is to design changes in two steps (expand and contract). Add the new column (expand), deploy code that writes both, backfill, deploy code that reads the new one, and only then drop the old column (contract), in a later release. At any moment the previous application version still works with the schema, so a rollback of the application is safe.

For emergency use, take a backup or snapshot before risky migrations, and test the migration on a copy of production data.

"Which databases and which version of Flyway does Boot 4.2 manage?"

Boot 4.2 manages Flyway 12.11.0 (see the baseline table in section 11). Since Flyway 10 the database support lives in separate modules: H2 works from the core, but PostgreSQL needs org.flywaydb:flyway-database-postgresql and similar for MySQL, SQL Server and Oracle. A missing module appears as "Unsupported Database" at start.

In the measured run I used an H2 file database. The H2 version used (2.5) is newer than Flyway had verified, which printed a warning, and migrations still applied. Flyway on PostgreSQL itself was not run for this chapter because that module was not available offline; the behaviour of the history table and checksums is the same across databases.

Pin Flyway through Boot's dependency management and read the release notes of Flyway major versions before upgrading Boot: validation rules and supported databases change.

Q78 · Scenario. "A deploy fails with "Validate failed: Migrations have failed validation" because of a checksum mismatch. What happened, and what do you do?"

Reveal answer

Strong answer Flyway stores, for every applied migration, a checksum: a number computed from the file's contents. At each start it recomputes the checksum of every applied file and compares. If someone changed a file that is already in the history, even by one word or one space, the numbers differ and Flyway refuses to start. That is the protection working: the database no longer matches what the history says was run.

The typical story is a hot fix. A migration ran in production, somebody noticed a problem and edited V2__add_status.sql in place ("just change the default") and the next deploy failed with "Migration checksum mismatch for migration version 2: applied to database 292701503, resolved locally -1700206075".

What do you do, in order:

  1. Do not "repair" first. Find out what changed: git diff on the file, and what actually exists in the database. The edit may be harmless (a comment), or it may describe a change the database never got.
  2. If the edit was a mistake, restore the file byte for byte from the commit that was applied, and put the intended change into a new migration, V3__default_status_placed.sql. This is the normal fix, and the measured run printed the history with version 3 applied cleanly.:
  3. If the file was changed by tooling only (line endings, a formatter, a comment) and the database is correct, align the history with flyway repair. Repair rewrites the stored checksums to match the files. In the measured run --repair=true printed "Repairing Schema History table for version 2" and the next start validated 4 migrations.:
  4. Understand why it happened and block it: a CI check that fails the build if any already-released migration file changed (compare with the main branch), and a formatter exclusion for the migration folder.

Why repair is dangerous: it tells Flyway "trust the files from now on", whatever they contain. If the edited file contains a different change, the history now lies, and other environments (test, staging) that ran the old version differ from production in a way nothing records.

Never "fix" it with spring.flyway.validate-on-migrate=false. That switches the alarm off. Use ignoreMigrationPatterns only for specific, known cases such as missing migrations in a long-lived branch.

The idiom is forward-only migrations: applied files are history, and history is never rewritten.

Picture it

The setup: Run 1 applies three migrations. Then V2__add_status.sql is edited (one word changed). Run 2 is "the next deploy". The fix is shown in runs 3 (restore V2 and add V3) and 4 (a comment-only change repaired).

V2__add_status.sql after the hot fix · Boot 4.2runs offline
alter table orders add column status varchar(20) default 'PLACED' not null;
-- was: default 'NEW'

Make the invisible visible: Run the next deploy, then the fix.

run 2 and run 3 · Boot 4.2 (code/e22-spring-in-depth/D/, trimmed)runs offline
# run 2: the next deploy
...Validate failed: Migrations have failed validation
Migration checksum mismatch for migration version 2
-> Applied to database : 292701503
-> Resolved locally    : -1700206075
Either revert the changes to the migration, or run repair to update the schema history.

# fix: put V2 back byte for byte, add the change as V3
# run 3
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:309) ~[spring-boot-4.2.0.jar!...
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1354) ~[spring-boot-4.2.0.jar...
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-4.2.0.jar...
	at com.quickbite.platform.PlatformApplication.main(PlatformApplication.java:9) ~[!/:0.0.1-SNAPSHOT]
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:10...
	at java.base/java.lang.reflect.Method.invoke(Method.java:565) ~[na:na]

What you see: Run 2 fails during start-up, before Hibernate (the error names flywayInitializer as a dependency of entityManagerFactory) and prints both checksums. Run 3, after restoring V2 and adding V3, validates 4 migrations, applies only version 3 and starts.

Why: Validation compares file contents with what the database history recorded. The numbers show that the file is not the one that ran, whatever the reason.

Edit the applied file

The checksum no longer matches; start fails.

V2__add_status.sqlruns offline
alter table orders add column
  status varchar(20)
  default 'PLACED' not null;
-- edited after it was applied

Add a new migration

History stays true; the change rolls forward.

V3__default_status_placed.sqlruns offline
alter table orders
  alter column status
  set default 'PLACED';
-- V2 untouched

The shift: Fix mistakes with a new version, never by rewriting an applied one.

Land it I restore the applied file and roll the change forward as a new version, and I repair checksums only for a tooling accident I have inspected.

Likely follow-ups
"What exactly does flyway repair change?"

repair does two things in the history table, and nothing in your own tables. It removes entries of failed migrations (for databases that cannot roll back DDL, a failed script may leave a failed row), and it realigns the stored checksums, descriptions and types of applied migrations with what is on disk.

In the measured run: "Repairing Schema History table for version 2 (Description: add status, Type: SQL, Checksum: -6469213)" and then "Successfully repaired schema history table". The next start validated four migrations.

It does not undo or redo any SQL. So if the edited file would have produced a different schema, repair hides the difference. Use it only after you have checked that the database is in the state the file describes. In Spring Boot you can run it from the Flyway command line, or from a FlywayMigrationStrategy bean that calls flyway.repair() before migrate() for a single, controlled deploy, and then remove the bean.

"How do I stop people from editing applied migrations?"

Use process, because the tool only notices later. A CI step compares the migration folder with the main branch and fails if any file that exists on main is modified or deleted (only additions are allowed). A simple version lists the changed files with git diff --name-status against the main branch, limited to the migration folder, and fails on any line that does not start with A.

Add the folder to the formatter and line-ending exclusions (.gitattributes with *.sql -text stops Windows and Linux checkouts from producing different checksums, which is another real cause of this error).

Review rules help too: a migration file is reviewed like a deployed artefact, and the review checklist asks "is there a new version number, and is the previous one untouched?".

"What if I must change a migration that has not left my machine yet?"

If it has run only on your own local database, you may change it, and then rebuild the local database (flyway clean is safe locally, or just delete the H2 file or the container volume). A migration is "immutable" from the moment it exists in a shared environment: the shared branch, the CI database or another developer's machine.

Rule of thumb: until the migration is merged, edit freely and recreate your database; after it is merged, add a new file. Teams with many branches also adopt date-based versions (V20261202_1__x.sql) so that two branches adding V7 do not collide; Flyway's outOfOrder setting handles a late-merged lower version.

Never run clean against anything but a disposable database. Keep spring.flyway.clean-disabled=true (the default since Flyway 9) everywhere else.

"The mismatch only appears in one environment. Why?"

Look at differences in how the file reached that environment. Typical causes: a different line-ending conversion (Git for Windows with autocrlf, so the file differs by \r), a build step that filters resources (@variable@ replacement by Maven resource filtering changes the SQL text), an editor that adds a trailing newline or a BOM, or an environment that really did get a hot-fixed copy.

To find it, compute the checksum of the file as deployed: unpack the jar and compare bytes with the repository file. Flyway's own info command shows the applied checksum and the locally resolved one.

Turn off resource filtering for the db/migration directory in the Maven or Gradle build, and set .gitattributes to stop line-ending conversion for .sql. Those two changes remove the most common non-malicious cause.

Q79. "Flyway versus Liquibase."

Reveal answer

Strong answer Both solve the same problem: versioned, recorded database changes applied at deploy time. They differ in how you write the changes and how much the tool does for you. Both integrate with Spring Boot with one starter and run before JPA starts.

Flyway is SQL-first. A migration is a plain SQL file named V<version>__<description>.sql. What you write is exactly what runs. Rules are few: versions, repeatables, a history table with checksums. It is easy to learn and to read in a code review, because the file is the database change. The price is that SQL is database-specific: a script written for PostgreSQL does not run on Oracle, and there is no built-in rollback in the free edition.

Liquibase describes changes as changesets in XML, YAML, JSON or SQL, in a changelog file. Because the format is abstract (createTable, addColumn), the same changelog can target several databases. It supports rollback instructions per changeset, preconditions ("run only if this table does not exist"), contexts and labels (run these changes only in test), and can generate a diff between two databases. The price is more concepts, more verbose files, and an extra layer between what you write and the SQL that runs.

The history table in each: flyway_schema_history (version, checksum, success) and DATABASECHANGELOG (id, author, file, checksum), with a lock table DATABASECHANGELOGLOCK in Liquibase.

How to choose:

OptionPick it whenCost or catch
FlywayOne database product, a team that knows SQL, simple reviewSQL is not portable; rollback means a new forward script
LiquibaseSeveral database products, preconditions, rollback, contexts per environmentMore concepts and verbose changelogs; abstraction hides the SQL
Hibernate ddl-autoThrowaway demos and tests onlyNo history, no review, renames become drop and add

For most Spring Boot services on one database, I pick Flyway with plain SQL. I pick Liquibase when a product must ship on several database engines or when I need preconditions and contexts as first-class features. Whatever the tool, the discipline matters more than the choice: forward-only, never edit applied changes, test migrations on production-like data.

Picture it

The setup: The same change, "add a status column with a default", written for each tool.

Flyway

A SQL file named by version.

V2__add_status.sqlruns offline
alter table orders
  add column status varchar(20)
  default 'NEW' not null;

Liquibase

A changeset in a changelog file.

db.changelog.yamlruns offline
- changeSet:
    id: 2-add-status
    author: asha
    changes:
      - addColumn:
          tableName: orders
          columns:
            - column:
                name: status
                type: varchar(20)
                defaultValue: NEW

The shift: Flyway runs your SQL as written; Liquibase generates SQL from a description.

Make the invisible visible: Look at what Flyway recorded after it ran the three scripts of the platform demo.

flyway_schema_history · Boot 4.2 (code/e22-spring-in-depth/D/)runs offline
rank  version  description          type  checksum     success
-1    null     << Flyway Schema History table created >> TABLE null         true
1     1        create orders        SQL   1934866666   true
2     2        add status           SQL   292701503    true

What you see: One row per applied script with the version, description, type, a checksum and a success flag. Liquibase's DATABASECHANGELOG would hold the changeset id and author in place of the version.

Why: Both tools are "apply what is not yet recorded, and prove that what was recorded has not changed". The difference is the language of the change.

Land it I pick Flyway for a single-database service because the SQL file is the change, and Liquibase when portability, preconditions or contexts are required.

Likely follow-ups
"Can I use both tools in one project?"

You can, but you should not unless forced. Two tools managing one schema means two histories and two views of the truth, and the order in which they run matters. One legitimate case is a legacy module that ships Liquibase changelogs and a new module that wants Flyway on a different schema or database; give each its own schema or its own DataSource, and configure each tool with its own locations or changelog.

Spring Boot auto-configures both if both starters are present, and they run in no guaranteed order relative to each other unless you control it. If you inherit a Liquibase project, migrating to Flyway means baselining at the current state (baseline-on-migrate) and writing new changes in Flyway only; it is a one-time decision recorded in the README.

Do not mix them in the same tables.

"How do rollbacks work in each?"

Flyway Community has none. You roll forward with a new migration. Undo migrations (U<version>__...sql) exist only in the paid editions, and have the same data-loss limits as any undo.

Liquibase lets you define a rollback block per changeset (or infers one for simple changes like createTable), and you can run rollback to a tag or a number of changesets. It works well for structural changes and badly for data changes: a rollback of "dropped a column" cannot bring back the data.

My practice for both: design changes so the previous application version works with the new schema (expand and contract), so that the real rollback is a redeploy of the old application, not a database change. Take a snapshot before a risky migration, and test the migration, including its failure path, on a copy of production-sized data.

"Which one handles environment-specific data like test fixtures?"

Flyway uses locations and callbacks: spring.flyway.locations set to both folders in the test profile adds a folder of extra scripts, and callbacks (afterMigrate.sql) run after every migration. The same effect is possible with profile-specific properties.

Liquibase has contexts and labels built in: a changeset marked context: test runs only when spring.liquibase.contexts=test. It is a cleaner fit for "this data only in test".

Whichever tool, keep reference data (countries, order statuses) in normal migrations, and fixture data (fake customers) out of production migrations. A migration that inserts test users into production is a classic mistake.

"How does each behave on large tables, such as adding an index?"

Neither tool is smart about lock time. They run the SQL you give them. An alter table or create index on a table with 200 million rows can lock it for a long time in some databases, and the application, whose pods wait for the migration at start-up, appears hung. That is a database question, not a tool question.

Use the database's online options: PostgreSQL create index concurrently (which cannot run inside a transaction, so Flyway needs executeInTransaction=false for that script), MySQL online DDL, or a gradual backfill in batches. Run the migration as a separate job before the rollout, as noted for Flyway, and watch lock waits.

In both tools, validate the plan on a copy of production data and agree a maintenance window for anything that locks.

Q80. "What do DevTools do, and why must they never reach production?"

Reveal answer

Strong answer spring-boot-devtools is a development-time helper. You add it as a dependency with runtime scope and optional and it gives three things:

  • Automatic restart. Boot starts your classes in a special restart classloader and everything else (libraries) in a base classloader. When a file on the classpath changes (your IDE rebuilt a class), DevTools throws away only the restart classloader and starts the application again. Because the libraries stay loaded, a restart is far quicker than a cold start.
  • LiveReload. A small server tells a browser extension to refresh the page when a resource changes.
  • Development property defaults. It sets sensible defaults, such as disabling template caching and turning on more web logging, which you would otherwise set by hand.

The measured run shows the speed difference: the first start took 4.6 seconds on restartedMain; after a class changed, "Restarting due to 1 class path change" and the application was up again in 0.67 seconds, then 0.48 seconds after a second change.

Why never in production: it can restart the application by itself when a file changes; it opens a remote-debug-style channel (remote DevTools, with a secret) that can run code; it disables caches and turns on verbose behaviour; and a second classloader changes class identity in ways that cause strange bugs. It also costs memory and file-watching threads.

Spring Boot protects you by default: the Maven and Gradle plugins exclude DevTools when they build the executable jar, and DevTools turns itself off when it detects a production-style launch (java -jar of a packaged archive, or a classloader that is not the dev one). The measured Docker Compose run showed the same exclusion principle for spring-boot-docker-compose: ./mvnw spring-boot:run had it, while java -jar failed with "Failed to configure a DataSource" because the plugin leaves it out of the jar.

Keep the optional flag and runtime scope, so that the dependency does not travel to projects that depend on yours, and never override the plugin's exclusion with excludeDevtools=false.

Two gotchas: a restart resets static state and in-memory data (use an external database), and a class that holds a thread or a file open across restarts leaks. For a setup that needs hot swap of bodies only, use your IDE's debugger-based reload or JRebel.

Picture it

The setup: A small app with spring-boot-devtools is started with spring-boot:run. While it runs, a class is recompiled twice (by changing a source file and running the compiler).

Make the invisible visible: Read the start-up lines and the two restarts.

run · Boot 4.2 (code/e22-spring-in-depth/D/devtools/, trimmed)runs offline
--- first start (restartedMain thread), then the file watcher reacts to a recompiled class:
INFO [restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Se...
INFO [restartedMain] com.quickbite.dev.DevApplication         : Started DevApplication in 4.624 secon...
2026-12-02T00:48:10.778+05:30  INFO 1791068 --- [devtools] [   File Watcher] rtingClassPathChangeChan...
INFO [restartedMain] com.quickbite.dev.DevApplication         : Started DevApplication in 0.672 secon...
INFO [restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
2026-12-02T00:48:12.952+05:30  INFO 1791068 --- [devtools] [   File Watcher] rtingClassPathChangeChan...
INFO [restartedMain] com.quickbite.dev.DevApplication         : Started DevApplication in 0.477 secon...
INFO [restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged

What you see: The first start runs on the restartedMain thread (the restart classloader) and takes 4.6 s. A file watcher thread notices a class path change, and the application restarts in 0.67 s and then 0.48 s. The "Condition evaluation unchanged" line is DevTools telling you the auto-configuration result did not change between restarts.

Why: Only the application's own classes are reloaded. The slow part of a cold start (loading, scanning and initialising thousands of library classes) is skipped, because the library classloader survives.

Without DevTools

A manual stop and start for every change.

terminalruns offline
edit code
stop app
start app   (5 to 10 s)
refresh browser

With DevTools

The IDE build triggers a quick restart.

pom.xmlruns offline
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <scope>runtime</scope>
  <optional>true</optional>
</dependency>

The shift: DevTools shortens the edit loop; the plugin keeps it out of the packaged jar.

Land it I add DevTools as runtime and optional, trust the plugin to leave it out of the jar, and never run a DevTools build in production.

Likely follow-ups
"How can I confirm DevTools is not in my production jar?"

List the jar's libraries: jar tf app.jar | grep devtools should print nothing (for a Boot fat jar the libraries are under BOOT-INF/lib/). In CI add that as a check that fails the build if found. You can also run ./mvnw dependency:tree and check the scope: runtime with optional is what you want.

At run time, start the packaged jar and look at the log: the line "Devtools property defaults active!" appears only in development runs, as in the measured output.

If a container image runs spring-boot:run or an IDE launch command by mistake, DevTools is back. Always run the packaged jar (or a layered image built from it) in deployment.

"What is the remote DevTools feature and is it safe?"

Remote DevTools lets a locally running IDE push class changes to an application running somewhere else (for example in a container on a dev cluster) and restart it. It requires spring.devtools.remote.secret to be set on the server and the client, and it exposes a special HTTP endpoint.

It is not safe in production: anyone who knows or guesses the secret can upload code. The Boot docs state clearly that it should never be enabled on a production deployment, and it is off unless the secret is set. In a dev cluster, protect it with the network (VPN, no public ingress).

For containers, most teams do not use it; they use a bind mount with spring-boot:run locally, or tools such as Skaffold and Tilt that rebuild and redeploy on change.

"Why do I sometimes get ClassCastException or odd bugs only with DevTools?"

Because DevTools loads your classes in the restart classloader and libraries in the base one. The same class name loaded by two classloaders is two different types. A cache or a static field in a library class that holds an instance of one of your classes now holds an object from the old classloader, and a cast to the new class fails: "class X cannot be cast to class X".

Typical culprits: libraries that cache classes, serialisation to a store that survives restarts (a session or a cache with Java serialisation), and multi-module projects where a library module you own sits in the base classloader. DevTools handles other modules in the same workspace by treating them as restart classes, but jars from a repository stay in the base.

Fix with spring.devtools.restart.exclude or an META-INF/spring-devtools.properties file telling DevTools which jars to treat as restartable, or turn restarts off (spring.devtools.restart.enabled=false) for that project. When a bug disappears with restart off, you have found the cause.

"What are the alternatives to DevTools for fast feedback?"

Your IDE's own hot swap, which replaces method bodies in a running debug session with no restart (limited to body changes). JRebel, a commercial tool that reloads almost any change. Running the unit and slice tests (@WebMvcTest, @DataJpaTest), which give feedback in seconds without starting the whole application, and are the better loop for most changes. And Spring Boot's own build improvements: AOT and CDS (class data sharing) shorten start-up for the packaged app.

My loop: slice tests for logic, DevTools for UI and wiring changes, and a full integration test before the pull request. DevTools is a convenience, not a requirement.

Q81. "What does Docker Compose support do at startup, and how does it compare with Testcontainers at dev time?"

Reveal answer

Strong answer Docker Compose support (spring-boot-docker-compose, since Boot 3.1) lets Spring Boot start your dependencies for you. You put a compose.yaml next to the project (a Postgres, a Redis, a RabbitMQ), add the dependency, and run the app.

At start-up Boot finds the file, runs docker compose up for the services, waits until they are healthy, and then creates the connection settings itself: it reads the container's image and published ports and configures the datasource, with no spring.datasource.url to write. When the app stops, Boot stops the containers (configurable).

The measured run shows it. With a compose.yaml that publishes only the container port 5432, the log printed that Boot was "Using Docker Compose file", then the container went Creating, Created, Starting, Started, Waiting, Healthy, and the app started in 6.1 seconds. The app then printed jdbc:postgresql://127.0.0.1:32800/quickbite: Docker had picked a free host port (32800) and Boot used it. The database was PostgreSQL 16.14, and a table written at start had one row.

Important limits, both measured or documented. The dependency is for development: the Boot Maven plugin leaves it out of the executable jar, so java -jar failed with "Failed to configure a DataSource". It also needs Docker and the docker compose command on the machine. And it recognises images by name (a Postgres image, a Redis image) to know how to build the connection details.

Testcontainers starts containers from Java code, usually in tests (and, with TestApplication, at dev time through spring-boot-testcontainers). A container is declared as a bean with @ServiceConnection, and Boot builds the connection details from it (Q82). Containers are created from test code, they get random ports, and are removed after the run.

How I choose:

OptionPick it whenCost or catch
Docker Compose supportLocal development with ./mvnw spring-boot:run; the whole team shares one compose.yamlNeeds Docker; not for the production jar; one shared definition for all runs
Testcontainers (@ServiceConnection)Integration tests; a throwaway database per test class; CICode and a library to learn; start-up cost per run unless containers are reused
Installed servicesNothing else is possibleVersion drift between machines; "works on my machine"

I use Compose support for the dev loop and Testcontainers for tests, with the same image tag in both so that dev and test share the database version.

Picture it

The setup: A web app has spring-boot-docker-compose and the PostgreSQL driver. The compose.yaml defines Postgres 16 with a database, user and password, and publishes only the container port. There is no datasource property anywhere. It is started with ./mvnw spring-boot:run.

compose.yamlruns offline
services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: quickbite
      POSTGRES_USER: quickbite
      POSTGRES_PASSWORD: secret
    ports:
      - "5432"          # only the container port: Docker picks a free host port

Make the invisible visible: Run the app and read the start-up lines.

run · Boot 4.2 (code/e22-spring-in-depth/D/dockercompose/, trimmed)runs offline
INFO .s.b.d.c.l.DockerComposeLifecycleManager : Using Docker Compose file /home/iam100god/Desktop/AI_...
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Creating 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Created 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Starting 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Started 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Waiting 
INFO o.s.boot.docker.compose.core.DockerCli   :  Container dockercompose-postgres-1 Healthy 
INFO c.quickbite.compose.ComposeApplication   : Started ComposeApplication in 6.068 seconds (process ...
JDBC url     : jdbc:postgresql://127.0.0.1:32800/quickbite?ApplicationName=dockercompose
server       : PostgreSQL 16.14 on x8
orders table : 1 row(s)

real	0m9.425s
user	0m15.278s
sys	0m2.235s

What you see: Boot found compose.yaml, started the container, waited for Healthy, and used the published port 32800 for the JDBC URL. The app ran in 6.1 s in total. No datasource property was needed.

Why: Boot's Docker Compose module inspects docker compose ps output: image names tell it which connection-details factory to use, and the published ports give it the host and port.

Hand-written settings

URL, user and password copied into properties.

application.propertiesruns offline
spring.datasource.url=
  jdbc:postgresql://localhost:5432/quickbite
spring.datasource.username=quickbite
spring.datasource.password=secret
# and start the DB yourself

Compose support

Boot starts the container and wires the connection.

compose.yaml + pomruns offline
services:
  postgres:
    image: postgres:16-alpine
# pom: spring-boot-docker-compose
# no datasource properties at all

The shift: Let the container definition be the single source of truth for local connection settings.

Land it I use Compose support for the local dev loop and Testcontainers for tests, with the same image tag, and I never expect Compose support in the packaged jar.

Likely follow-ups
"Why did java -jar fail while spring-boot:run worked?"

Because spring-boot-docker-compose is a development-time module, and the Boot Maven plugin excludes it from the executable jar when it repackages. The jar therefore has no Compose support and no spring.datasource.url, and the datasource auto-configuration fails with "Failed to configure a DataSource: 'url' attribute is not specified".

That is by design: a production jar must not start containers on the machine it runs on. In production the connection comes from real configuration: environment variables, a config tree or a secret store.

If you want to test the packaged jar locally, start the compose services yourself (docker compose up -d) and pass the datasource properties on the command line or use a dev profile with explicit values.

"Can Compose support also start containers only for some services, or keep them after exit?"

Yes. The property spring.docker.compose.lifecycle-management takes none, start-only and start-and-stop (the default for non-test runs). With start-only the containers stay up when your app stops, which saves the start time on every restart (useful with DevTools). spring.docker.compose.skip.in-tests is true by default so tests do not start Compose; spring.docker.compose.file selects another file; and spring.docker.compose.profiles.active selects Compose profiles.

Services can be excluded from connection detection with the label org.springframework.boot.ignore on the service in compose.yaml, and org.springframework.boot.service-connection can name the type when the image name is not recognised (a private registry image of Postgres, for instance).

I use start-only locally: Postgres keeps its data between runs, and DevTools restarts do not wait for containers.

"What goes wrong when the image name is not recognised?"

Boot cannot tell it is a database, so no connection details are created and you get the same "Failed to configure a DataSource" error even though the container is running. This happens with images from a private registry, with custom tags that rename the image (registry.corp/db/pg:16), or with images based on another image.

The fix is the label on the service: the label org.springframework.boot.service-connection with the value postgres. Boot then treats it as Postgres. Check the Boot reference for the list of supported types and the exact label name for your version.

If connection fails even with the right type, check the credentials: Boot reads POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB from the service's environment, as set in the measured compose.yaml.

"How do I keep dev and test on the same database version?"

Use one image reference in both places. Put the tag in a single constant or a properties file read by both: the compose.yaml image and the @Container declaration in the Testcontainers class (DockerImageName.parse("postgres:16-alpine")). A Dependabot or Renovate rule that updates both in one pull request avoids drift.

The reason is practical: an integration test against Postgres 15 and a developer on 16 will disagree about behaviour sooner or later (a function that exists in one, a changed default in the other), and production may be a third version. Pin all three to the same major version.

Beyond version, use the same extensions and settings (a Postgres with pg_trgm in production needs it in dev and test, too).

Q82. "How does @ServiceConnection replace hand-written datasource properties in tests?"

Reveal answer

Strong answer In an integration test you want a real database, usually through Testcontainers: a library that starts a Docker container from test code and removes it afterwards. The container listens on a random free port, so you cannot write the URL in application.properties. The old solution was a @DynamicPropertySource method that copied container.getJdbcUrl(), the username and the password into the Environment. It worked, and it was boilerplate repeated in every test class, with the property names (spring.datasource.url, spring.kafka.bootstrap-servers, spring.data.redis.host...) to remember.

@ServiceConnection (from spring-boot-testcontainers, since Boot 3.1) removes it. You declare the container as a bean and annotate it. Spring Boot looks at the container's type and image, builds a connection details object (for example JdbcConnectionDetails with URL, username, password) and the auto-configuration uses it instead of the properties.

The shape of the code (illustrative, see the note below):

  • A @TestConfiguration(proxyBeanMethods = false) class with a @Bean @ServiceConnection PostgreSQLContainer postgres() method.
  • @Import of that class in the test, or @Import through a TestApplication.main that starts the whole app against containers at dev time (SpringApplication.from(App::main).with(...).run(args)).
  • Nothing about the URL: the datasource just works.

Benefits: less code, the same mechanism for every technology Boot knows (PostgreSQL, MySQL, MongoDB, Redis, Kafka, RabbitMQ, Elasticsearch and more), connection details are typed rather than copied as strings, and the same container bean serves tests and the dev-time run.

Mind the honesty note for this chapter: Testcontainers' Maven module and the PostgreSQL driver that Boot 4.2 manages (Testcontainers 2.0.5, PostgreSQL driver 42.7.14) were not available in the offline Maven cache of the course machine, so this answer's code is shown as an illustration and was not run here.

Testcontainers 2 also renamed some packages and classes compared with version 1 (for example the module and container class names), so check the Testcontainers 2 and Spring Boot 4.2 documentation for the exact imports. The Docker Compose run in Q81 shows the same connection-details mechanism working for real.

Picture it

The setup: No Testcontainers run was possible offline (modules not cached), so the picture shows the shape of the code and, for real evidence of the mechanism, the Compose run from Q81, where Boot built the JDBC URL itself.

// illustrative — ContainersConfig.java · Boot 4.2 (not run here)runs offline
// illustrative: check the Testcontainers 2 imports for your version
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
    @Bean
    @ServiceConnection
    PostgreSQLContainer postgres() {
        return new PostgreSQLContainer("postgres:16-alpine");
    }
}

@SpringBootTest
@Import(ContainersConfig.class)
class OrderRepositoryIT { /* no datasource properties */ }

Make the invisible visible: What the same mechanism printed in the real Compose run (Boot built the URL from the running container).

run · Boot 4.2 (code/e22-spring-in-depth/D/dockercompose/, trimmed)runs offline
INFO c.quickbite.compose.ComposeApplication   : Started ComposeApplication in 6.068 seconds (process ...
JDBC url     : jdbc:postgresql://127.0.0.1:32800/quickbite?ApplicationName=dockercompose
server       : PostgreSQL 16.14 on x8
orders table : 1 row(s)

What you see: The JDBC URL contains the random host port that Docker published. Nothing in the project's properties said so. @ServiceConnection produces exactly this kind of connection details for a Testcontainers container.

Why: Boot has a registry of ConnectionDetailsFactory classes. Each knows one kind of container or service and produces a typed connection-details bean. Auto-configuration prefers a connection-details bean over properties.

@DynamicPropertySource

Copy each value into properties by hand.

OrderIT.javaruns offline
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
  r.add("spring.datasource.url",
        pg::getJdbcUrl);
  r.add("spring.datasource.username",
        pg::getUsername);
  r.add("spring.datasource.password",
        pg::getPassword);
}

@ServiceConnection

Declare the container; Boot wires it.

ContainersConfig.javaruns offline
@Bean
@ServiceConnection
PostgreSQLContainer postgres() {
    return new PostgreSQLContainer(
        "postgres:16-alpine");
}

The shift: Typed connection details replace a screenful of property copying.

Land it I declare the container as a bean with @ServiceConnection and let Boot build the connection details, and I check the Testcontainers 2 imports before copying old snippets.

Likely follow-ups
"What technologies does @ServiceConnection support?"

Boot supports the common stores and brokers through connection-details factories: relational databases (PostgreSQL, MySQL, MariaDB, Oracle, SQL Server) for JDBC and R2DBC, MongoDB, Redis, Kafka, RabbitMQ, Elasticsearch, Cassandra, Neo4j, and Zipkin or OTLP collectors, among others. The exact list depends on the Boot version, so read the Testcontainers section of the reference for 4.2.

For an image Boot does not recognise (a custom image, a generic container), you can name the connection type with @ServiceConnection(type = ...) or fall back to @DynamicPropertySource.

Because the factory is selected by the container class and image, using a GenericContainer with a name like postgres is not enough; use the specific container class (PostgreSQL, Kafka) so Boot knows the protocol.

"How do I avoid starting a container for every test class?"

Three techniques. First, a single static container shared by all test classes: declare it in one @TestConfiguration that every test imports, and Spring's test context cache reuses the context, so the container starts once per JVM. Second, Testcontainers' reuse feature (withReuse(true) and testcontainers.reuse.enable=true in the home directory file), which keeps a container alive between runs, useful for local loops but not for CI. Third, @RestartScope on the container bean for dev-time TestApplication runs with DevTools, so a restart keeps the container.

The usual cost is 2 to 5 seconds per container start. A test suite with 40 classes each starting Postgres would take minutes; with a shared context it takes one start.

Clean state between tests with transactions rolled back (@Transactional on tests), or a truncate step, not by recreating the container.

"What is TestApplication and how does it relate?"

It is a main method in your test source tree that starts your application using the test configuration: SpringApplication.from(...).with(...).run(args). You run it from the IDE or with ./mvnw spring-boot:test-run. The application starts with containers declared as @ServiceConnection beans, so a developer gets a working local environment without installing or configuring any service.

Compared with Docker Compose support: the definition lives in Java code and can share the container beans with your integration tests, so test and dev use the same setup. Compose support uses a YAML file and is easier to share with people who do not run Java tests.

Pick one for the dev loop and say so in the README; running both at once means two databases and confusion about which one the app is using.

"What goes wrong in CI where Docker is not available?"

Container-based tests fail at start with "Could not find a valid Docker environment". Fix the environment first: use a CI runner with Docker (Docker-in-Docker or a mounted socket), or a service container, and make sure the CI user can access the socket.

When Docker cannot be had (some locked-down build agents), run those tests only when it is present using @Testcontainers(disabledWithoutDocker = true), so the build does not fail but the gap is visible, and run the container tests in a separate pipeline stage on a runner that has Docker.

Do not replace Postgres with H2 in tests just to avoid Docker unless the SQL is portable: differences in types, functions and locking give tests that pass on H2 and fail in production.

Drill · Web extras, messaging and the ecosystem

Nine questions on the parts of the Spring ecosystem around the core: pushing updates to browsers, the layers around a web request, uploads, HTTP clients, messaging, batch jobs, Modulith, Spring Cloud on Kubernetes and gRPC.

Q83. "Server-sent events versus WebSocket versus polling — when do you use each?"

Reveal answer

Strong answer All three answer one question: how does a browser or client learn that something changed on the server? They differ in direction, cost and complexity.

Polling means the client asks again and again: "any news about order 42?" every second. It is the simplest thing that works, and any HTTP client can do it. It is also wasteful: most answers are "no change", every request carries headers and authentication, and latency is up to one polling interval. At QuickBite, a tracking page polling every second produced about 40 % of API traffic (see section 10).

Server-sent events (SSE) keep one HTTP response open, and the server writes events into it as they happen, in a simple text format (id:, event:, data:). The direction is server to client only. Browsers have EventSource with automatic reconnection and a Last-Event-ID header for resuming. It travels over normal HTTP, so proxies, load balancers and authentication work as for any request. In Spring MVC you return an SseEmitter.

WebSocket upgrades an HTTP connection into a two-way channel with its own framing. Both sides can send at any time, with low overhead per message. You need a handler (or STOMP messaging on top of it), your own reconnect logic, and care with proxies, authentication at the handshake and scaling (sessions are tied to one server, so a broadcast needs a broker or a shared message bus).

How I choose:

OptionPick it whenCost or catch
PollingUpdates are rare or a delay of seconds is fine; simplest client; no long-lived connectionsWasted requests; latency equals the interval; load grows with users times rate
SSEThe server pushes updates and the client only listens (order status, notifications, progress bars)One direction only; one open connection per client; browser limit of about six connections per host on HTTP/1.1
WebSocketTwo-way, low-latency traffic (chat, collaborative editing, live trading, games)Own protocol and reconnect logic; harder load balancing and scaling; more testing

The measured SSE run shows the format: status events with ids, and a comment line :heartbeat between them. The heartbeat keeps proxies from closing a connection they think is idle. The measured WebSocket run exchanged messages in both directions (the server pushed a status, the client sent "cancel order 42?") and closed with code 1000.

Practical rules for SSE: set a timeout on the emitter (30 s in the demo) and let the client reconnect; send a heartbeat every 15 to 30 seconds; stop pushing when the client leaves (onCompletion and IOException); and in Spring MVC remember that each emitter holds a connection (and, with platform threads, possibly a pusher thread), so use a small executor or virtual threads. This is the SSE idiom.

Picture it

The setup: GET /orders/42/status returns an SseEmitter with a 30 s timeout. A virtual thread sends five states, 0.8 s apart, with a heartbeat comment in between. A WebSocket handler pushes one status and echoes one client message.

OrderStatusController.java (excerpt) · Boot 4.2runs offline
@GetMapping(path = "/orders/{id}/status",
            produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter status(@PathVariable long id) {
    SseEmitter emitter = new SseEmitter(30_000L);
    pusher.submit(() -> {
        for (String s : STATES) {
            emitter.send(SseEmitter.event().id(...).name("status").data(...));
            Thread.sleep(400);
            emitter.send(SseEmitter.event().comment("heartbeat"));
            Thread.sleep(400);
        }
        emitter.complete();
    });
    return emitter;
}

Make the invisible visible: Call it with curl and note the time of each line.

curl · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
# seconds since the request started
  0.0s  HTTP/1.1 200 
  0.0s  Content-Type: text/event-stream
  0.0s  Transfer-Encoding: chunked
  0.0s  Date: Tue, 01 Dec 2026 19:04:47 GMT
  0.0s  
  0.0s  id:1
  0.0s  event:status
  0.0s  data: {"order":42,"status":"PLACED"}
  0.1s  
  0.4s  :heartbeat
  0.4s  
  0.8s  id:2
  0.8s  event:status
  0.8s  data: {"order":42,"status":"ACCEPTED"}
  0.8s  
  1.2s  :heartbeat
  1.2s  
  1.6s  id:3
  1.6s  event:status
  ...
  3.2s  id:5
  3.2s  event:status
  3.2s  data: {"order":42,"status":"DELIVERED"}
  3.2s  
  3.6s  :heartbeat
  3.6s  

What you see: The response is text/event-stream, chunked. Events arrive at 0.0 s, 0.8 s, 1.6 s and so on, with a :heartbeat comment 0.4 s after each. The connection stays open until the sixth state completes it.

WebSocket test client · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
client: open
client received: {"order":42,"status":"PLACED"}
client received: server got: cancel order 42?
server: connection closed CloseStatus[code=1000, reason=bye]

Why: SSE is a long HTTP response with a defined text format. WebSocket is a different protocol after the upgrade handshake, which is why it can carry traffic both ways, and why intermediaries need to support it.

Polling

Ask every second, mostly hear "no change".

tracking.jsruns offline
setInterval(async () => {
  const r = await fetch(
    '/orders/42');
  show(await r.json());
}, 1000);

Server-sent events

One request; the server speaks when there is news.

tracking.jsruns offline
const es = new EventSource(
  '/orders/42/status');
es.addEventListener('status',
  e => show(JSON.parse(e.data)));

The shift: Replace repeated questions with one open stream when the data only flows one way.

Land it I use SSE for one-way push, WebSocket only when both sides talk freely, and polling when updates are rare or the client is simple.

Likely follow-ups
"How does an SSE client resume after a dropped connection?"

The browser's EventSource reconnects by itself, waiting a few seconds, and sends the header Last-Event-ID with the id of the last event it received. The measured output shows id:1 to id:5 on each event. The server can read that header (@RequestHeader(value = "Last-Event-ID", required = false)) and send only the events after that id, replaying from a store.

So that resuming works, event ids must be ordered and meaningful (an order-status sequence number), and the server must keep recent events (a small table or a bounded buffer). Without that the client simply starts again from the current state.

The server can also set the reconnect delay with a retry: field. For one-shot streams that end with a final event, complete the emitter and let the client close its EventSource, or it will reconnect after the completion and ask again.

"What happens to SSE and WebSocket connections behind a load balancer or proxy?"

Idle timeouts are the main problem. Many proxies and load balancers close a connection that carries no bytes for 30 to 120 seconds. That is why the demo sends a comment heartbeat between events (SSE) and why WebSocket servers send ping frames. Pick a heartbeat shorter than the shortest idle timeout on the path.

Proxies may also buffer responses: Nginx needs proxy_buffering off (or the header X-Accel-Buffering: no) for SSE, or events arrive in bursts. For WebSocket the proxy must pass the Upgrade and Connection headers.

Scaling: a connection is tied to one pod. If an update originates on another pod, you need a way to reach the pod that holds the connection: a message broker or Redis pub/sub that every pod listens to, then pushes to its own connections. For SSE with a few thousand clients per pod this works well; sticky sessions are not needed because SSE reconnects.

"How many SSE or WebSocket connections can one Spring Boot pod hold?"

It depends on threads and memory, not on the protocol. With the servlet stack on platform threads, each open SseEmitter does not necessarily hold a request thread (the request is processed asynchronously), but your own code that pushes events usually holds one thread per stream, as in a loop that sleeps. A pool of 200 threads then caps you at roughly 200 streams.

The measured demo used a virtual thread per stream, which removes that cap: tens of thousands of sleeping virtual threads are fine. The remaining limits are file descriptors (set ulimit -n), memory per connection (a few KB to tens of KB) and the proxy's own limits.

Measure with a load test that opens thousands of connections and watch heap, threads and the proxy's connection count. Decide the limit, set a maximum per pod and reject above it with 503 so the load balancer moves clients elsewhere.

"Why not use WebSocket for everything?"

Because the extra power costs complexity you may not need. WebSocket connections are stateful, so load balancing, deployments (draining thousands of connections), authentication refresh and monitoring all get harder. There is no built-in reconnect, resume, or request/response model; you design a message protocol (STOMP gives you a standard one) and handle ordering and acknowledgements yourself.

SSE, as plain HTTP, reuses cookies, tokens, proxies, HTTP/2 multiplexing and your existing observability. For a server-to-client feed it is easier to build and operate, and a client's "send" side is an ordinary POST.

Choose WebSocket when you really have frequent messages in both directions with low latency needs, such as chat or live collaboration. Choose SSE for feeds. Choose polling when the simplicity of a client matters more than efficiency.

Q84. "Filters versus interceptors versus argument resolvers — their order and their uses."

Reveal answer

Strong answer They all run around a web request, and they live at different layers of the stack, which decides what each can see.

A servlet filter (jakarta.servlet.Filter, in Spring usually OncePerRequestFilter) belongs to the servlet container, before Spring MVC. It sees the raw request and response, runs for every request including static files and errors, and can wrap the request, stop it, or change the response. Spring Security is a chain of filters. Use filters for cross-cutting work that does not need to know about controllers: authentication, request ids and MDC, CORS, compression, logging of all traffic.

A HandlerInterceptor belongs to Spring MVC. It runs after the DispatcherServlet has chosen the handler, so it knows which controller method will run. It has preHandle (return false to stop), postHandle (after the controller, before the response is written) and afterCompletion (always, even after an exception). Use it for per-controller concerns: timing, audit lines, locale, rate limiting by endpoint.

A HandlerMethodArgumentResolver supplies one parameter of a controller method. When a method asks for a type or annotation Spring does not know (@CurrentCustomer String who), the resolver builds the value from the request. Use it to keep request-parsing out of controllers.

Add @ControllerAdvice: @ExceptionHandler methods turn exceptions into responses, and ResponseBodyAdvice can touch the body before it is written.

The measured order for one request, with all of them registered, was:

  1. Filter: before chain.
  2. Interceptor: preHandle (with the handler method name).
  3. Argument resolver: resolveArgument.
  4. Controller method.:
  5. Response advice: beforeBodyWrite.
  6. Interceptor: postHandle, then afterCompletion.
  7. Filter: after chain, with the final status.

For a request that throws, steps 5 and postHandle are skipped, the @ExceptionHandler builds the 409, afterCompletion still runs, and the filter sees the status 409.

Registration traps: a filter bean is picked up by Boot automatically. An interceptor and a resolver are not beans on their own; you must register them in a WebMvcConfigurer (addInterceptors, addArgumentResolvers). Forgetting this is the most common reason an interceptor "does nothing". Link: section 10.

Picture it

The setup: A filter, an interceptor, an argument resolver (@CurrentCustomer), a response advice and an exception handler each print a numbered line. Two requests are made: one that works and one whose controller throws.

Make the invisible visible: Send both requests and read the server console.

curl and server log · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
$ curl -s -H "X-Customer: asha" localhost:18081/chain/hello
hello asha

# server console, same request
1 filter           before chain
2 interceptor      preHandle  (handler = hello)
3 argument resolver resolveArgument
4 controller       hello(asha)
5 advice           beforeBodyWrite
6 interceptor      postHandle
7 interceptor      afterCompletion, exception = null
8 filter           after chain, status 200

$ curl -si localhost:18081/chain/boom | head -1
HTTP/1.1 409

# server console, the request that throws
1 filter           before chain
2 interceptor      preHandle  (handler = boom)
3 argument resolver resolveArgument
4 controller       boom(anonymous) throws
4b advice          @ExceptionHandler caught: kitchen closed
7 interceptor      afterCompletion, exception = null
8 filter           after chain, status 409

What you see: The filter wraps everything: first in and last out. The interceptor knows the handler name. The resolver runs while arguments are prepared, before the method body. In the failing request, lines 5 and 6 never print, the advice produced the 409, and afterCompletion reports exception = null because the advice had already handled the exception.

Why: The layers nest like an onion: servlet container, then the DispatcherServlet, then the interceptor, then argument resolution and the controller. The response unwinds in reverse.

Interceptor never registered

A bean alone does nothing.

Timing.javaruns offline
@Component
class TimingInterceptor
    implements HandlerInterceptor {
  // never called
}

Registered in the MVC config

The configurer adds it to the chain.

WebConfig.javaruns offline
@Configuration
class WebConfig implements WebMvcConfigurer {
  public void addInterceptors(
      InterceptorRegistry r) {
    r.addInterceptor(timing);
  }
}

The shift: Filters are picked up as beans; interceptors and resolvers must be registered.

Land it I pick the layer by what the code needs to know: raw requests in a filter, the chosen handler in an interceptor, one parameter in a resolver.

Likely follow-ups
"When do I choose a filter over an interceptor?"

Choose a filter when the work must happen for every request regardless of Spring MVC: security, request ids, compression, CORS, or anything that needs to wrap the request or response objects (for example a caching wrapper to read the body twice). Filters run before Spring decides what to call, so they also see requests that no controller handles, and they can reject a request very early.

Choose an interceptor when you need the handler: handler instanceof HandlerMethod tells you the controller method and its annotations, so you can apply a rule only to methods marked @RateLimited or log which endpoint was hit. Interceptors can be limited to URL patterns in addInterceptors(...).addPathPatterns(...).

If you can do it in either, the interceptor is less risky for business-flavoured concerns because it runs inside Spring's error handling, while a filter exception travels up to the container. Security belongs in the filter chain, always.

"Where do Filter and HandlerInterceptor sit relative to Spring Security and exception handling?"

Spring Security's FilterChainProxy is itself a servlet filter, ordered early (default order -100 in Boot). Filters you register with a lower order number run before it, and others after. An authentication failure is handled inside the security chain (AuthenticationEntryPoint), which writes the 401 itself; an interceptor and a @ControllerAdvice never see it.

@ExceptionHandler methods handle exceptions thrown from the controller layer (including interceptors and argument resolvers, because they run inside the dispatcher). Exceptions thrown by a servlet filter are outside the dispatcher: they go to the container's error handling and, in Boot, to /error through BasicErrorController.

So the practical rule: put logic that may throw domain errors in interceptors or controllers, where @ControllerAdvice gives a consistent response format, and keep filters free of business exceptions.

"How do I read the request body in a filter and still let the controller read it?"

The body of an HTTP request is a stream you can read once. If a filter reads it (to log it or to verify a signature), the controller finds it empty and fails with "Required request body is missing".

The fix is a wrapper: ContentCachingRequestWrapper caches what is read, but only after the downstream code reads it; for reading before the controller you write a custom HttpServletRequestWrapper that buffers the bytes and returns a new stream each time. Both cost memory.

For logging, prefer logging after the call with ContentCachingRequestWrapper. For signature checks, limit the body size first (a client could send gigabytes), then buffer. Never log request bodies that contain personal data or card details, and cap what you log (the first 1 to 2 KB).

"How do I write a custom argument resolver like @CurrentCustomer?"

Create an annotation (an annotation named @CurrentCustomer that targets parameters), a resolver class implementing HandlerMethodArgumentResolver, and register it:

CurrentCustomerResolver.java · Boot 4.2runs offline
class CurrentCustomerResolver implements HandlerMethodArgumentResolver {
    public boolean supportsParameter(MethodParameter p) {
        return p.hasParameterAnnotation(CurrentCustomer.class)
            && p.getParameterType() == String.class;
    }
    public Object resolveArgument(MethodParameter p, ModelAndViewContainer m,
            NativeWebRequest req, WebDataBinderFactory f) {
        String h = req.getHeader("X-Customer");
        return h == null ? "anonymous" : h;
    }
}

Then addArgumentResolvers in a WebMvcConfigurer adds it. The measured run printed "3 argument resolver resolveArgument" and the controller received asha, or anonymous when the header was missing.

In a secured app, prefer Spring Security's @AuthenticationPrincipal, which is the built-in resolver for the logged-in user, over reading a header you must trust.

Q85 · Scenario. "Large uploads fail with MaxUploadSizeExceededException. Fix it and protect the server."

Reveal answer

Strong answer First understand what the exception protects. Spring Boot's multipart support (MultipartFile) parses the upload before your controller runs and limits two things: spring.servlet.multipart.max-file-size (one file) and spring.servlet.multipart.max-request-size (the whole request). The defaults are 1 MB and 10 MB.

An upload over the limit is refused with MaxUploadSizeExceededException, and the client receives HTTP 413 (Payload Too Large). In the measured run, with limits of 1 MB and 2 MB, a 500 KB file was stored, and a 3 MB file got a bare 413 with an empty body.

"Fix it" has two honest meanings, and you must decide which one you need.

If users legitimately upload bigger files (photos of 8 MB): raise the limits to a number you can defend, for example max-file-size=10MB and max-request-size=12MB, and tell the front end the limit so it can check before uploading. Do not set -1 (unlimited): one client can then fill the disk or the memory of every pod.

If files are very large (videos, backups, hundreds of MB): do not use MultipartFile at all. A multipart parser spools the file to a temporary directory (and small ones to memory), and the whole request holds a thread for the transfer. Instead, stream the body: read request.getInputStream() in small chunks and write it straight to storage.

The measured /photos/stream endpoint received the same 3 MB body that was refused as multipart, and answered "streamed 3000000 bytes" while holding only an 8 KB buffer. Better still, let clients upload directly to object storage with a pre-signed URL, so the bytes never pass through your service.

Protecting the server, whichever way you go:

  1. Set limits at every layer: the reverse proxy (client_max_body_size in Nginx, the ingress annotation), Tomcat (server.tomcat.max-swallow-size, max-http-form-post-size) and Spring's multipart limits. The smallest wins, and the proxy should refuse first.
  2. Validate the content: check the declared type and also the file's magic bytes, limit the file name (never use it as a path; generate your own name), and scan if the files are shared.
  3. Apply timeouts and rate limits so a slow-upload client cannot hold threads for hours (server.tomcat.connection-timeout).:
  4. Return a clear 413 with a message that states the limit, with an @ExceptionHandler(MaxUploadSizeExceededException.class).:
  5. Store files outside the application (object storage), never in the container's file system, which disappears with the pod.:

Remember the temporary directory: spring.servlet.multipart.location points to where large parts are spooled, and a tiny /tmp fills quickly with concurrent uploads.

Picture it

The setup: The app sets max-file-size=1MB and max-request-size=2MB. POST /photos takes a MultipartFile and POST /photos/stream reads the raw body in 8 KB pieces. Three requests: a 500 KB file, a 3 MB file as multipart, and the same 3 MB as a raw body.

UploadController.java · Boot 4.2runs offline
@PostMapping("/photos")
String photo(@RequestParam("file") MultipartFile file) throws IOException {
    return "stored " + file.getOriginalFilename() + " " + file.getSize() + " bytes";
}

@PostMapping("/photos/stream")      // raw body, never fully in memory
String stream(HttpServletRequest req) throws IOException {
    byte[] buf = new byte[8192];
    long total = 0;
    try (var in = req.getInputStream()) {
        int n;
        while ((n = in.read(buf)) != -1) total += n;
    }
    return "streamed " + total + " bytes";
}

Make the invisible visible: Run the three uploads with curl.

curl · Boot 4.2 (code/e22-spring-in-depth/E/, headers trimmed)runs offline
$ curl -s -i -F file=@e_half.bin localhost:18081/photos
HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 30
Date: Tue, 01 Dec 2026 19:05:26 GMT

stored e_half.bin 500000 bytes

$ curl -s -i -F file=@e_3mb.bin localhost:18081/photos
HTTP/1.1 100 

HTTP/1.1 413 
Content-Length: 0
Date: Tue, 01 Dec 2026 19:05:26 GMT
Connection: close



$ curl -s -i -X POST --data-binary @e_3mb.bin localhost:18081/photos/stream
HTTP/1.1 100 

HTTP/1.1 200 
Content-Type: text/plain;charset=UTF-8
Content-Length: 22
Date: Tue, 01 Dec 2026 19:05:26 GMT

streamed 3000000 bytes

What you see: The 500 KB multipart upload is stored. The 3 MB multipart upload gets HTTP/1.1 413 with no body and the connection closed. The same 3 MB sent as a raw stream is accepted, because the multipart size limits do not apply and the code never holds more than 8 KB.

Why: The limits belong to the multipart parser. A streamed body bypasses it, which is exactly why you must set your own limits (proxy, Tomcat, and a byte counter in your code) when you stream.

Everything in the multipart parser

Fine for photos; heavy for videos.

Upload.java · Boot 4.2runs offline
@PostMapping("/photos")
String photo(
    @RequestParam MultipartFile f) {
  // parsed, spooled, limited
}

Streamed body

Constant memory, your own limits.

Upload.java · Boot 4.2runs offline
@PostMapping("/photos/stream")
String stream(HttpServletRequest r) {
  try (var in = r.getInputStream()) {
    // 8 KB at a time
  }
}

The shift: Use multipart for small files and stream or pre-signed URLs for large ones.

Land it I raise multipart limits only to a defended number, stream or pre-sign for large files, and set limits at the proxy, the container and the code.

Likely follow-ups
"Why do I get 413 from Nginx before Spring even sees the request?"

Because Nginx has its own limit: client_max_body_size defaults to 1 MB, and a request over it is refused with 413 by the proxy. The same exists for Kubernetes ingress controllers (an annotation such as proxy-body-size), API gateways and cloud load balancers (some have a fixed maximum).

When the Spring limit is raised and users still see 413, check each hop in the path, starting from the outside. The response body tells you who answered: Nginx returns its own HTML error page, Tomcat or Spring returns an empty body or a Boot error JSON.

Set the limits consistently: the proxy a little above Spring's max-request-size, so that the application's clearer message wins for ordinary overruns while the proxy still protects against absurd sizes.

"What is the difference between max-file-size and max-request-size?"

max-file-size is the limit for each single uploaded file part. max-request-size is the limit for the whole multipart request, all files and form fields together. So a request with three 800 KB files passes a file limit of 1 MB and fails a request limit of 2 MB, since the total is 2.4 MB.

Set max-request-size at least as large as max-file-size times the number of files you allow, plus a little for form fields. If you want only one file, set both about equal.

There is a third limit for non-file form data, server.tomcat.max-http-form-post-size, and a fourth, server.tomcat.max-swallow-size (how much of a rejected request body Tomcat reads and discards so that the client sees the 413 instead of a connection reset). That last one explains many "connection reset" reports from clients that upload large bodies.

"How do I return a clear error for an oversize upload?"

Handle the exception in a @RestControllerAdvice: @ExceptionHandler(MaxUploadSizeExceededException.class) returns a ProblemDetail with status 413, a title such as "File too large" and a detail naming the limit (read it from the configured property so the text never goes stale).

Note the timing: the exception can be raised while the request is parsed, before your controller is invoked, and with some servers the client may already have sent the whole body or may get a connection reset when the server closes early. Test the behaviour with a real client such as curl, as the measured run did, not only with MockMvc, which does not reproduce the container's limit handling.

On the client side, check the size before uploading and show the limit in the UI; the server message is the safety net.

"How do I stream a large file download safely?"

Return a ResponseEntity<StreamingResponseBody> or a Resource (InputStreamResource or FileSystemResource) so that the content is copied to the response in chunks, not loaded into a byte[]. A 2 GB file as a byte[] is an out-of-memory error for the pod.

Set Content-Length when you know it, Content-Disposition to give a safe file name, and support range requests (Spring's ResourceHttpMessageConverter does for Resource) so that interrupted downloads resume.

For big or popular files, redirect to a pre-signed object-storage URL and let a CDN serve them. Your service then only authorises and hands over a link. Apply the same safety rules as for uploads: never build file paths from user input (path traversal), and check that the caller is allowed to read that file.

Q86. "HTTP interface clients versus RestClient versus OpenFeign versus RestTemplate (deprecated in 4.2)."

Reveal answer

Strong answer Four ways to call another HTTP service from Spring, in the order they appeared in the tutorials, and in the order I would choose today: HTTP interface, RestClient, OpenFeign if you already have it, never RestTemplate in new code.

RestTemplate is the old blocking client (Spring 3). Its template methods (getForObject, exchange) grew into a large, hard-to-extend API. In Spring Boot 4.2 on Spring Framework 7.1 both RestTemplate and Boot's RestTemplateBuilder are marked @Deprecated(since = "7.1", forRemoval = true): the compiler warns "has been deprecated and marked for removal". It still works today, but it has an end date.

RestClient (Spring 6.1) is the modern blocking client with a fluent API: client.get().uri("/price").retrieve().body(Map.class). It has status handlers (onStatus), an exchange method that sees the raw response without throwing, request interceptors, and builder-level configuration of base URL, headers and timeouts. It runs on the JDK HttpClient, Apache or other request factories.

HTTP interface clients (@HttpExchange, Spring 6) go one level up: you write a Java interface with annotated methods (@GetExchange("/menu/{id}")), and Spring generates an implementation that calls a RestClient (or WebClient) underneath.

Boot 4 adds a registry: @ImportHttpServices(group = "menu", types = MenuApi.class) registers the proxy as a bean, and spring.http.serviceclient.menu.base-url and read-timeout configure that group. In the measured run the bean's class was jdk.proxy2.$Proxy123, api.item(7) returned a MenuItem, and a call to a slow endpoint with a 1 s read timeout failed after 1,005 ms with ResourceAccessException.

OpenFeign (Spring Cloud) was the first declarative client, with the same idea and different annotations (@FeignClient, @GetMapping). It brings its own stack (load-balancer, circuit-breaker integration) and release train. It remains usable; for new code on Boot 4 the built-in HTTP interfaces cover the declarative need with less to maintain.

OptionPick it whenCost or catch
HTTP interface (@HttpExchange)A stable remote API you call often; you want a typed interface and easy mockingNeeds a configured RestClient underneath; fewer escape hatches than raw RestClient
RestClientOne-off or irregular calls; full control of status handling and streamingMore code per call than an interface
OpenFeignYou already run Spring Cloud with Feign across many servicesSeparate release train; overlaps with built-in features
RestTemplateExisting code, until you migrateDeprecated for removal in Framework 7.1; no new features

Always configure timeouts first (Q53): a client without a read timeout waits forever.

Picture it

The setup: A local JSON server answers /price, /missing (404) and /slow (1.5 s). The same calls are made with RestTemplate and with RestClient (read timeout 500 ms). The @HttpExchange client comes from the measured E run.

RestClientDemo.java (excerpt) · Boot 4.2runs offline
var factory = new JdkClientHttpRequestFactory();
factory.setReadTimeout(Duration.ofMillis(500));
RestClient rc = RestClient.builder().baseUrl(base)
        .requestFactory(factory).build();

Map<?, ?> b = rc.get().uri("/price").retrieve().body(Map.class);
var res = rc.get().uri("/missing").exchange((req, r) -> r.getStatusCode());
rc.get().uri("/slow").retrieve().toBodilessEntity();

Make the invisible visible: Run the same calls through both clients.

run --demo=restclient · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
RestTemplate  getForObject -> {item=biryani, paise=24900}
RestTemplate  404 -> NotFound 404 NOT_FOUND
RestClient    retrieve().body -> {item=biryani, paise=24900}
RestClient    404 handler -> no such item
RestClient    exchange() sees status without throwing -> 404 NOT_FOUND
RestClient    /slow -> ResourceAccessException after 504 ms
RestClient.create(restTemplate) exists: true
run --demo=httpclient · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
client class  : jdk.proxy2.$Proxy123
api.item(7)   : MenuItem[id=7, name=Chicken biryani, priceInPaise=24900]
api.slow()    : ResourceAccessException after 1005 ms
root cause    : java.net.http.HttpTimeoutException: Request cancelled

What you see: RestTemplate and RestClient return the same JSON. RestTemplate throws NotFound for the 404; RestClient can turn it into your own exception with onStatus or read the status with exchange. The slow call is cut at 504 ms by the 500 ms read timeout. The interface client, configured through properties, was cut at 1,005 ms.

Why: All three newer styles share the same machinery (a request factory with timeouts, message converters). The interface only changes how the call is declared, so a timeout is still a request-factory setting.

RestTemplate

Template methods; deprecated for removal in 7.1.

PriceClient.javaruns offline
RestTemplate rt = builder
    .build();
Map<?, ?> m = rt.getForObject(
    base + "/price", Map.class);

HTTP interface

A typed interface; Spring writes the client.

MenuApi.javaruns offline
@HttpExchange("/menu")
interface MenuApi {
  @GetExchange("/{id}")
  MenuItem item(@PathVariable long id);
}

The shift: Declare the remote API as an interface and keep the HTTP details in configuration.

Land it I declare stable remote APIs as HTTP interfaces on RestClient, use RestClient directly for irregular calls, set timeouts first, and plan RestTemplate's removal.

Likely follow-ups
"How do I migrate a RestTemplate call to RestClient?"

Mostly one-to-one. restTemplate.getForObject(url, T.class) becomes restClient.get().uri(url).retrieve().body(T.class). postForEntity becomes restClient.post().uri(url).body(x).retrieve() followed by toEntity. exchange with a ParameterizedTypeReference becomes .body(new ParameterizedTypeReference<List<Item>>() {}).

The biggest semantic difference is error handling: RestTemplate throws RestClientResponseException subclasses for 4xx and 5xx by default, and so does RestClient with retrieve(), but you can now customise it per call with onStatus or use exchange to handle every status yourself.

Migrate in steps: replace the builder (RestClient.Builder is auto-configured by Boot, with the same message converters and customisers), move timeouts to spring.http.clients.* or the request factory, port the interceptors, and run your tests against a stub server. The measured RestClient.create(restTemplate) factory also exists to let new code reuse an old template's configuration during the transition.

"Where do I set timeouts for these clients in Boot 4.2?"

The global settings are spring.http.clients.connect-timeout and spring.http.clients.read-timeout; they apply to clients built from Boot's auto-configured builders. In a measured run read-timeout=500ms cut a 3-second call after about 590 ms, and the group form spring.http.serviceclient.menu.read-timeout=1s applied to one HTTP interface group.

Per client in code: configure the request factory (JdkClientHttpRequestFactory.setReadTimeout, HttpComponentsClientHttpRequestFactory with a request config) and pass it to the builder, as the demo above did with 500 ms.

Set both timeouts for every remote dependency. A connect timeout of 300 ms to 1 s and a read timeout slightly above the dependency's normal 99th percentile is a good start. Without them one slow dependency can hold every request thread.

"How do I test code that uses an HTTP interface client?"

Mock the interface. It is a plain Java interface, so @MockitoBean MenuApi api (or a hand-written fake) replaces the whole HTTP layer in a service test, which is the main benefit of the interface style.

To test the HTTP behaviour itself (paths, headers, timeouts, error mapping), run the real client against a stub server: WireMock, MockWebServer, or Spring's MockRestServiceServer bound to the RestClient.Builder. The demo for this chapter uses a small embedded HTTP server and a real 1-second timeout to prove that the setting works.

Add one test per error mapping (404 to "not found", 503 to a retryable exception) and one for the timeout, since a timeout setting that is silently ignored is a common production surprise.

"Should I add retries or a circuit breaker to the HTTP client itself?"

Add them around the call, in the service that uses the client, where you know whether the operation is safe to repeat (section 06). An interceptor that retries every failed request is dangerous for POST and for anything that is not idempotent.

The right split: the client handles HTTP (URL, headers, serialisation, timeouts); the caller's service method carries @Retryable and @CircuitBreaker with the business rules. The HTTP interface fits this well, because a mock of the interface is also where a test injects failures.

If many services need the same policy for safe GETs, an interceptor or a ClientHttpRequestInterceptor that retries idempotent methods only is acceptable; keep the policy visible in one place.

Q87. "Spring Kafka versus Spring AMQP versus JMS — when do you use each?"

Reveal answer

Strong answer All three connect your application to a message broker, so that services talk through a queue or a log instead of calling each other directly. They fit different jobs.

Spring for Apache Kafka (spring-kafka, @KafkaListener, KafkaTemplate) is for a distributed, replayable log. Messages are appended to partitions, kept for days or forever, and each consumer group tracks its own position. Pick Kafka for event streams at high volume, for several independent consumers reading the same events, for replay (rebuild a read model from history) and for ordering per key. Cost: a cluster to run, partition and consumer-group thinking, and at-least-once delivery that needs idempotent consumers. The full story is in E17.

Spring AMQP (spring-amqp, spring-rabbit, @RabbitListener, RabbitTemplate) is for queues with routing, mostly RabbitMQ. A message goes to an exchange, is routed to queues by rules (direct, topic, fanout), and is removed when a consumer acknowledges it. Pick it for task queues and work distribution (send an email, resize an image), flexible routing, per-message priorities, dead-letter queues and delayed retries.

Cost: no replay by default (a consumed message is gone), and ordering is per queue. Boot 4.2 adds AMQP 1.0 support, the open standard protocol, next to the classic RabbitMQ AMQP 0.9.1 client; check the reference for which broker features you get.

JMS (spring-jms, @JmsListener, JmsTemplate) is the Java standard API for messaging, with brokers such as ActiveMQ, Artemis or IBM MQ behind it. Pick it when the enterprise already runs a JMS broker, or you need its transactional integration (XA) with other resources. Cost: it is an API, not a protocol, so details depend on the vendor, and it is the least used in new cloud-native systems.

OptionPick it whenCost or catch
Spring KafkaHigh-volume event streams, replay, many consumers, per-key orderingCluster and partition design; consumers must be idempotent
Spring AMQP (RabbitMQ)Work queues, routing rules, dead-letter and delay, modest volumeNo replay; scale-out and ordering are queue-bound
JMSAn existing enterprise JMS broker, XA transactionsVendor differences; older style
Outbox plus any of theseThe message must be sent exactly when the database change commitsAn extra table and a relay process

Whichever you pick, three rules hold. Delivery is at least once, so consumers must tolerate duplicates (an idempotency key, E20). A message that cannot be processed needs a dead-letter destination, not an infinite retry. And to send a message exactly when a database change commits, use the outbox pattern (E7), not a send inside the transaction.

No broker was run for this answer: the RabbitMQ and Kafka images were not part of the offline setup of this chapter, so there is no output block here, and I do not invent one.

Picture it

The setup: No broker output is claimed. The picture shows the listener shape for each technology side by side, as code to read.

// illustrative — listeners · Boot 4.2 (not run here)runs offline
// illustrative: the three listener styles

@KafkaListener(topics = "orders", groupId = "invoicing")
void onOrder(OrderPlaced e) { /* replayable log */ }

@RabbitListener(queues = "mail.send")
void send(MailTask t) { /* work queue, ack on return */ }

@JmsListener(destination = "ORDERS.IN")
void legacy(String text) { /* enterprise JMS broker */ }
QuestionKafkaRabbitMQ (AMQP)JMS broker
Message removed after reading?No, kept by retentionYes, after ackYes, after ack
Replay old messages?Yes, reset the offsetNot by defaultNot by default
OrderingPer partition keyPer queuePer queue
RoutingTopics and partitionsExchanges and bindingsQueues and topics
Typical useEvent streams, analyticsTask queues, workflowsExisting enterprise systems

What you see: The listener code looks similar, which hides the real difference: what the broker does with a message after you read it.

Why: Choose by the broker's model (log or queue) before the Spring API. The annotations are the easy part.

Send inside the transaction

The message can leave before the commit succeeds.

OrderService.javaruns offline
@Transactional
void place(Order o) {
  repo.save(o);
  rabbit.convertAndSend(
      "orders", o.id());
  // later: rollback
}

Outbox

The row and the message intent commit together.

OrderService.javaruns offline
@Transactional
void place(Order o) {
  repo.save(o);
  outbox.save(new Msg(
      "orders", o.id()));
}
// a relay sends and marks done

The shift: Write the intent to the database in the same transaction and let a relay publish it.

Land it I choose Kafka for replayable event streams, RabbitMQ for routed work queues and JMS only where a JMS broker already exists, and I use an outbox for must-send messages.

Likely follow-ups
"What does "at least once" mean for my listener code?"

The broker guarantees that a message is delivered once or more, never silently lost, but it may deliver the same message twice: after a consumer crash before the acknowledgement, after a rebalance in Kafka, or after a network failure. So the listener must give the same result if it sees a message twice.

The usual technique is an idempotency key: each message has a unique id, and the consumer records the ids it has processed (a table with a unique constraint) in the same transaction as its effect. A second delivery hits the constraint and is skipped. Or make the operation naturally idempotent ("set status to PAID" rather than "add 100 to balance").

"Exactly once" exists in limited forms (Kafka transactions within Kafka), but across a database and a broker it is built from at-least-once plus idempotency. State that in an interview; it shows you know where the guarantee ends.

"What is a dead-letter queue and why do I need one?"

A dead-letter queue (DLQ) is a separate destination where a message goes after it has failed too many times. Without it, a message that always fails (bad JSON, a bug) is retried forever, blocks the queue behind it (in Kafka, a partition) and burns CPU.

In Spring Kafka you use DefaultErrorHandler with DeadLetterPublishingRecoverer and a back-off (retry three times with delay, then publish to orders.DLT). In Spring AMQP you declare a dead-letter exchange on the queue, and a rejected message with requeue=false goes there. In JMS, brokers have their own dead-letter address.

Then someone must own the DLQ: an alert when it is not empty, a tool to inspect and re-drive messages after a fix, and a retention policy. An unwatched DLQ is a place where orders quietly die.

"Can I use Spring Cloud Stream instead of these libraries directly?"

Spring Cloud Stream puts a binder abstraction over Kafka, RabbitMQ and others: you write functions (Function<Order, Invoice>, Consumer<Order>) and configure bindings in properties, and the binder connects them to the broker. It reduces broker-specific code and makes a function easy to unit test.

The price is another abstraction with its own release train, naming and configuration, and the broker's special features (Kafka partition control, RabbitMQ routing) leak through binder-specific properties. For one service and one broker, plain Spring Kafka or Spring AMQP is simpler to understand and debug. For many services with a uniform style, or a plan to move between brokers, Stream can pay off.

I use the direct library until a clear second need appears.

"How do I test listeners without a real broker?"

Two levels. For logic, extract the work into a plain service method and test it without any broker; the listener is a thin adapter. For wiring, use Testcontainers with the real broker (Kafka, RabbitMQ), declared with @ServiceConnection (Q82), and send a message through the real template, then wait with Awaitility for the effect.

Spring Kafka also offers @EmbeddedKafka, an in-process broker for quick tests, and Spring AMQP has a test harness (TestRabbitTemplate). Embedded versions differ from production in subtle ways (security, versions), so keep at least one test per integration on the real broker.

Always test the failure path: a poison message must end in the DLQ, not in a loop.

Q88. "Spring Batch: job, step, chunk, reader/processor/writer and restartability."

Reveal answer

Strong answer Spring Batch is a framework for jobs that process many records reliably: import a 5-million-line CSV, close the month's invoices, recalculate prices overnight. It supplies the structure and the bookkeeping that a plain loop lacks: transactions, progress, failure handling and restart.

The vocabulary:

  • A job is the whole piece of work ("import the menu"). A job runs with job parameters (for example file=menu.csv), and a job instance is one job with one set of identifying parameters.
  • A job execution is one attempt to run an instance. If it fails and you run it again with the same parameters, that is a second execution of the same instance.
  • A job is made of steps. The common step is chunk-oriented.
  • In a chunk-oriented step an ItemReader reads one item at a time, an optional ItemProcessor transforms or filters it, and an ItemWriter receives a whole chunk (say 100 items) and writes them. Each chunk is one transaction: after the writer succeeds, Spring commits and records progress.
  • The job repository is a database schema where Batch stores every job, execution, step and its counts, and the reader's position.

Restartability follows from that bookkeeping. If chunk number 7 fails (a bad row), the previous six chunks are already committed, and the repository says so. Running the same job again restarts at the failed chunk: the reader resumes from its saved position and does not read the first 600 rows again.

The measured run on Spring Batch 6.1 (Boot 4.2) imported a 1,000-line CSV with chunks of 100. Run 1 had a forced bad row at 650: the step failed with 600 rows written, 6 commits and 1 rollback, and the table held 600 rows. Run 2 with the row fixed restarted and read only the remaining 400 rows (4 commits), ending with 1,000 rows. Run 3, the same parameters again, was refused: "A job instance already exists and is complete".

A detail that cost real time: spring-boot-starter-batch alone gave an in-memory repository in this setup, so a "restart" re-read from row 1 and hit a duplicate-key error. Restartability needed @EnableBatchProcessing, @EnableJdbcJobRepository and the Batch schema in a real database.

When not to use Batch: for small jobs a @Scheduled method with a loop is enough; for streaming data use Kafka consumers; for huge parallel computation use a data platform. Pick Batch when you need restart, a record of what ran, and chunked transactions.

Picture it

The setup: A job importMenu reads menu.csv (1,000 rows) in chunks of 100, upper-cases the name in a processor and writes to the menu_import table. A system property forces row 650 to fail in the first run.

BatchDemo.java (excerpt) · Boot 4.2, Spring Batch 6.1runs offline
@Configuration
@EnableBatchProcessing
@EnableJdbcJobRepository
class BatchDemo {
    @Bean Step importStep(JobRepository repo, PlatformTransactionManager tx,
            FlatFileItemReader<MenuRow> r, ItemProcessor<MenuRow, MenuRow> p,
            JdbcBatchItemWriter<MenuRow> w) {
        return new StepBuilder("importStep", repo)
            .<MenuRow, MenuRow>chunk(100)
            .transactionManager(tx)
            .reader(r).processor(p).writer(w).build();
    }
}

Make the invisible visible: Run the job three times: with a bad row, after the fix, and again.

run --demo=batch · Boot 4.2 (code/e22-spring-in-depth/E/, trimmed)runs offline
# run 1: row 650 is bad (-DfailAt=650)
INFO 1772305 o.s.batch.core.step.AbstractStep         : Executing step: [importStep]
ERROR 1772305 o.s.b.core.step.item.ChunkOrientedStep   : Rolling back chunk transaction

java.lang.IllegalStateException: bad row 650 (forced)

ERROR 1772305 o.s.batch.core.step.AbstractStep         : Encountered an error executing step impo...

org.springframework.batch.core.step.FatalStepExecutionException: Unable to process chunk

INFO 1772305 o.s.batch.core.step.AbstractStep         : Step: [importStep] executed in 398ms
job instance 1, execution 1
step context: {batch.executed=true, menuReader.read.count=600, batch.version=6.1.0, batch.stepTyp...
step importStep: FAILED read=700 written=600 commits=6 rollbacks=1
job status : FAILED  exit=FAILED
rows in menu_import: 600

# run 2: same command, bad row fixed
INFO 1772662 o.s.batch.core.step.AbstractStep         : Executing step: [importStep]
INFO 1772662 o.s.batch.core.step.AbstractStep         : Step: [importStep] executed in 266ms
job instance 1, execution 2
step context: {batch.executed=true, menuReader.read.count=1001, batch.version=6.1.0, batch.stepTy...
step importStep: COMPLETED read=400 written=400 commits=4 rollbacks=0
job status : COMPLETED  exit=COMPLETED
rows in menu_import: 1000

# run 3: job already COMPLETED
ERROR 1773027 o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner

Caused by: JobInstanceAlreadyCompleteException: A job instance already exists and is complete for...

What you see: Run 1: FAILED read=700 written=600 commits=6 rollbacks=1; the failing chunk is rolled back, the first six stay. Run 2 (the same job, a fixed file): read=400 written=400, final count 1,000. Run 3: JobInstanceAlreadyCompleteException, because the identical job is complete.

Why: Progress is a row in the repository, written in the same transaction as each chunk. That is why a restart knows exactly where to continue.

A plain loop

No record of progress; a failure means start over.

Import.javaruns offline
for (String line : lines) {
    repo.save(parse(line));
}
// failed at row 650:
// 649 rows saved, no memory of it

Chunked step

Commits per chunk, progress recorded.

Step.javaruns offline
new StepBuilder("importStep", repo)
  .<Row, Row>chunk(100)
  .transactionManager(tx)
  .reader(r).processor(p).writer(w)
  .build();
// restart continues at row 601

The shift: A step with a repository turns "start over" into "continue where it stopped".

Land it I use Batch when I need chunked transactions, a record of runs and restart, and I check that the job repository is a real database.

Likely follow-ups
"How do I choose the chunk size?"

A chunk is the commit interval, so it trades transaction overhead against memory and the cost of a rollback. Small chunks (10) mean many commits and a slow job. Huge chunks (100,000) keep many rows in memory and make one failed row roll back a great deal of work.

Start around 100 to 1,000, measure throughput and memory, and adjust. The right number depends on row size, writer type (batch inserts like JdbcBatchItemWriter like 500+) and how bad the failure cost is. Remember the demo: the chunk of 100 containing the bad row 650 was rolled back as a whole; only 600 rows stayed, so rows 601 to 649, which were fine, had to be read again on restart.

Also set the JDBC batch size and use rewriteBatchedStatements (MySQL) or reWriteBatchedInserts (PostgreSQL) so that a chunk is a few round trips, not hundreds.

"How do skip, retry and the job parameters work?"

Skip and retry are configured on a fault-tolerant step. skip(DataFormatException.class).skipLimit(10) tells Batch to drop a bad record (and count it) instead of failing, up to 10 times. retry(DeadlockLoserDataAccessException.class).retryLimit(3) retries the chunk for transient errors. After the limit, the step fails. Skipped items can be logged through a SkipListener to a reject file for later repair.

Job parameters identify the instance. Two runs with the same identifying parameters (file=menu.csv) are the same instance: after a completed run the second is refused (run 3 above). For a repeatable job (a nightly run) add a changing identifying parameter such as the date or a run id, so each night is a new instance. Parameters marked non-identifying do not take part in the identity.

Choose consciously: "one instance per file" gives you free duplicate protection, and a timestamp parameter removes it.

"How do I run a Batch job on a schedule or from a REST call?"

Boot runs jobs at start-up by default (spring.batch.job.enabled=true); the demo set it to false and started the job from a runner. For a schedule, call JobOperator.start(job, parameters) from a @Scheduled method with a unique parameter, protected by ShedLock if several pods exist (Q56). For a REST trigger, a controller starts the job asynchronously and returns the execution id, so the HTTP request does not wait for hours.

For big jobs, a Kubernetes CronJob that starts the application with spring.batch.job.name=importMenu is cleaner: one pod per run, its own resources, and a clear success or failure status.

Always make the job repository a shared database, not memory, or two pods will not see each other's runs.

"How is Batch different from a Kafka consumer or @Scheduled loop?"

A Kafka consumer processes an unbounded stream continuously, one record or one poll batch at a time, and tracks progress by offset. Batch processes a bounded set (a file, a table) in a run with a start and an end, and records a job-level history (what ran, with which parameters, how many rows, success or failure).

A @Scheduled loop is the minimum: it has no memory of partial progress or of previous runs unless you build it. Batch gives you that, chunked transactions, skip and retry policies, partitioning for parallel steps and restart, at the cost of a framework, a schema and concepts.

Rule: if you would need to write "where did we stop and what did we already do" yourself, use Batch.

Q89. "What is Spring Modulith, and how does it verify module boundaries?"

Reveal answer

Strong answer A modular monolith is one deployable application whose code is split into modules with clear boundaries, so that it can be understood, tested and, one day, split into services without a rewrite. The risk in a normal monolith is that boundaries exist only in a diagram: after two years every class calls every other.

Spring Modulith makes the boundaries checkable. Its convention: every direct sub-package of your application's main package is a module. In QuickBite, com.quickbite.menu, com.quickbite.orders and com.quickbite.payments are three modules. The classes in the module's base package are its public API; classes in sub-packages (menu.internal) are internal, and other modules may not touch them.

The check is a test, using ApplicationModules:

ModularityTests.java · Boot 4.2, Spring Modulith 2.2runs offline
class ModularityTests {
    static final ApplicationModules modules = ApplicationModules.of(BaseApplication.class);

    @Test void listModules() { modules.forEach(System.out::println); }

    @Test void verifiesModularStructure() { modules.verify(); }
}

verify() analyses the compiled classes (with ArchUnit) and fails when it finds: a module using another module's internal types, a dependency cycle between modules, or a dependency not allowed by an explicit @ApplicationModule(allowedDependencies = ...) declaration.

In the measured run the first test printed each module with its base package and beans, and when OrderService took the internal MenuRepository in its constructor, verify() failed with "Module 'orders' depends on non-exposed type com.quickbite.menu.internal.MenuRepository within module 'menu'!", listing the constructor, the field and the method call. The fixed version, using the menu module's public MenuApi, passed (2 tests, 0 failures).

What else Modulith gives you: module-level integration tests (@ApplicationModuleTest starts only one module's beans), generated documentation (C4 and UML diagrams with Documenter), and an event publication registry: application events that listeners must handle are stored in a table in the same transaction that publishes them, and incomplete ones are republished after a restart, which is a built-in version of the outbox for in-process events (section 10).

Where it fits: a team that wants monolith simplicity (one deploy, one database, simple transactions) and microservice discipline (clear ownership, no tangled calls). It does not make you faster at runtime; it protects the structure of the code. When a module later becomes a service, its API is already a clean boundary.

Picture it

The setup: Three modules: menu (public MenuApi, internal MenuService and MenuRepository), orders and payments. First OrderService takes the internal MenuRepository directly. Then it is changed to use MenuApi.

Make the invisible visible: Run ModularityTests before and after the fix.

mvn test · Boot 4.2 (code/e22-spring-in-depth/E/modulith/, trimmed)runs offline
# Menu
> Logical name: menu
> Base package: com.quickbite.menu
> Excluded packages: none
> Spring beans:
  o ….internal.MenuRepository
  o ….internal.MenuService

# Payments
> Logical name: payments
> Base package: com.quickbite.payments
> Excluded packages: none
> Spring beans:
  + ….PaymentService

# Orders
> Logical name: orders
> Base package: com.quickbite.orders
> Excluded packages: none
> Spring beans:
  + ….OrderService

org.springframework.modulith.core.Violations: 
- Module 'orders' depends on non-exposed type com.quickbite.menu.internal.MenuRepository within m...
OrderService declares constructor OrderService(MenuRepository, PaymentService) in (OrderService.j...
- Module 'orders' depends on non-exposed type com.quickbite.menu.internal.MenuRepository within m...
Method <com.quickbite.orders.OrderService.place(long)> calls method <com.quickbite.menu.internal....
- Module 'orders' depends on non-exposed type com.quickbite.menu.internal.MenuRepository within m...
Field <com.quickbite.orders.OrderService.menu> has type <com.quickbite.menu.internal.MenuReposito...
- Module 'orders' depends on non-exposed type com.quickbite.menu.internal.MenuRepository within m...
Constructor <com.quickbite.orders.OrderService.<init>(com.quickbite.menu.internal.MenuRepository,...

...

# after: OrderService uses menu's public MenuApi
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.808 s -- in com.quickbit...
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

What you see: listModules prints three modules with their beans; the internal ones are marked o (internal) and the exposed ones +. verify() names the rule that was broken, which module did it, which type it touched and exactly where (constructor, field, method call). After the fix both tests pass.

Why: The test reads the compiled bytecode. A boundary violation is a failed build, found before review, not a diagram a year later.

Boundary only in a diagram

Anyone can reach into anyone.

OrderService.javaruns offline
class OrderService {
  OrderService(
    MenuRepository repo) { }
  // com.quickbite.menu.internal
}

Boundary in a test

Only a module's public API is allowed.

OrderService.javaruns offline
class OrderService {
  OrderService(MenuApi menu) { }
  // com.quickbite.menu (public)
}
// verify(): passes

The shift: A rule that is checked by the build stays true.

Land it Spring Modulith turns top-level packages into modules whose internals are protected by a verify() test that fails the build on a violation or a cycle.

Likely follow-ups
"How do modules communicate in Modulith, and when should they use events?"

There are two ways. A direct call to another module's public API (a Spring bean in the module's base package) is simple and synchronous, and appropriate when the caller needs an answer: orders asks menu for a price. An application event is a one-way notification: orders publishes OrderPlaced, and loyalty or notifications listen. The publisher does not know the listeners, so the dependency arrow points only one way.

Use events when the reaction is a side effect that should not be part of the caller's decision, and when you want the dependency to run from the reacting module to the event owner. Use calls when the answer is needed.

Modulith's @ApplicationModuleListener is a shortcut for "asynchronous, in its own transaction, after the publisher's commit", with the event stored in the publication registry until handled. It combines everything from the events section of this chapter (after-commit, async, durable) in one annotation.

"What is the event publication registry?"

A table (event_publication) where Modulith records every event that has listeners, in the same transaction as the publisher's work. When a listener finishes successfully, the entry is marked completed. If the application stops before that, or the listener fails, the entry stays incomplete, and on the next start (or on demand) Modulith resubmits it.

It gives at-least-once delivery for in-process events without a message broker: the order and its "order placed" event commit together, so there is no window where one exists without the other, which is the outbox idea built into the framework. Listeners must still be idempotent, because a resubmission can repeat a successful side effect.

You need a persistence starter for the registry (JDBC, JPA, MongoDB), a schema (it can be initialised automatically), and a housekeeping policy for completed entries (a property to delete or archive them). It can also externalise events to Kafka or AMQP with @Externalized.

"Does Modulith replace microservices?"

No, it postpones the decision and makes it cheaper. A modular monolith has one process, one deployment and local transactions, so there are no network failures between modules and no distributed data. For most teams below a certain size that is a strength.

Microservices solve different problems: independent deployment and scaling per team, fault isolation, different technology per service. They cost network calls, distributed transactions and operations. If your modules are clean and communicate through APIs and events, extracting one into a service later is a bounded project: its public API becomes the HTTP or message contract.

Start modular; split only when a module needs a different scaling profile, release cadence or ownership, not because the architecture slide says so. See E7 for the trade-offs.

"How do I introduce Modulith into an existing messy monolith?"

Gradually. First add the dependency and the verify() test and run it; expect a long list of violations. Do not try to fix everything. Record the current violations as accepted (a short allow list, or turn the test into a report), so the build stays green, then make a rule that the list may only shrink.

Pick the most valuable boundary first (the module that changes most often, or that you want a different team to own) and clean it: move public classes to the module's base package, internals to a sub-package, replace direct repository access by an API method, and replace calls into other modules by events where it fits.

Use the Documenter to generate the module diagram, and show it to the team; seeing the real tangle is persuasive. Measure progress by violations count per week.

Q90. "Spring Cloud today: Config, Gateway, OpenFeign and service discovery — which still matter on Kubernetes?"

Reveal answer

Strong answer Spring Cloud grew up before Kubernetes won, and it supplied what a distributed system needs: central configuration, finding other services, routing, client-side load balancing and resilience. Kubernetes now provides much of that in the platform, so the question is which Spring Cloud parts still earn their keep. My answer, part by part:

Service discovery (Eureka, Consul). A registry where services register and look each other up. On Kubernetes, a Service object gives every group of pods a stable DNS name (http://orders) and load-balances across pods, so a registry is redundant. Keep Eureka only for mixed environments (VMs plus Kubernetes) or when you move off a legacy platform.

Config Server. A server that serves configuration from a Git repository to all services, with refresh. On Kubernetes, ConfigMaps and Secrets, mounted as files or env vars and imported with spring.config.import (the config-tree run in section 08), cover most needs, with Git as the source via GitOps tools. Config Server still helps when you want one central place with history and per-application, per-profile files outside the cluster, or non-Kubernetes deployments.

Spring Cloud Gateway. A reactive API gateway: routing, filters, rate limiting, authentication relay, path rewrites. It still matters when you want gateway logic written in Java and tested like code. For plain routing and TLS, an Ingress controller or a cloud gateway does it with less custom code. A service mesh handles service-to-service concerns.

OpenFeign (and load-balancer). A declarative HTTP client plus client-side load balancing. On Kubernetes, load balancing is already done by the Service, and for the declarative part Spring's own HTTP interface clients (Q86) are the built-in option. Existing Feign code keeps working.

Resilience (Circuit Breaker abstraction, Resilience4j). Still valuable, because a mesh cannot know your fallback: see section 06.

Still relevant: Spring Cloud Stream and Bus for messaging abstractions, Spring Cloud Task, Contract (consumer-driven contract tests), Vault integration and Kubernetes-specific modules (spring-cloud-kubernetes, for reading ConfigMaps and discovering services through the Kubernetes API).

ComponentKubernetes gives youStill pick Spring Cloud when
Discovery (Eureka)Service DNS and load balancingMixed VM and cluster estate
Config ServerConfigMaps, Secrets, GitOpsCentral versioned config outside the cluster
GatewayIngress and cloud gatewaysYou want Java-coded filters and routing logic
OpenFeignService DNS; HTTP interfaces in SpringLarge existing Feign code base
Circuit breakerMesh retries and timeouts (no fallbacks)You need business fallbacks (keep it)

The honest summary: the platform replaced the plumbing, and the application-level policies (fallbacks, contracts, messaging) remain the application's job. Check each project's current status and the compatibility with your Boot version, because Spring Cloud release trains follow Boot versions closely. I did not run Spring Cloud for this chapter, so this answer rests on documentation and experience, not on a measured output.

Picture it

The setup: No Spring Cloud component was run. The picture contrasts how two services find each other in the two worlds, as configuration you could read.

// illustrative — two ways to reach the orders serviceruns offline
// illustrative

# Spring Cloud era (Eureka + Feign)
orders-client:  @FeignClient(name = "orders")        -> asks Eureka -> picks an instance
eureka:         every pod registers itself, sends heartbeats, can be stale

# Kubernetes era
orders-client:  @HttpExchange against http://orders  -> cluster DNS -> Service -> a ready pod
kubernetes:     readiness probes decide which pods receive traffic

What you see: The second line of each pair is the same capability. In Kubernetes it is part of the platform and has no registry to run or keep consistent.

Why: Discovery and load balancing are infrastructure problems, and the platform now solves them for every language. Application libraries are most useful where they hold business knowledge.

Eureka and Feign

A registry, heartbeats and a client library.

OrdersClient.javaruns offline
@FeignClient(name = "orders")
interface OrdersClient {
  @GetMapping("/orders/{id}")
  Order get(@PathVariable long id);
}
// + Eureka server and client

Service DNS and HTTP interface

The platform resolves the name.

OrdersApi.javaruns offline
@HttpExchange("/orders")
interface OrdersApi {
  @GetExchange("/{id}")
  Order get(@PathVariable long id);
}
// base-url: http://orders

The shift: Let Kubernetes find and balance; keep Spring for policy and contracts.

Land it On Kubernetes I drop Eureka, use ConfigMaps for config and HTTP interfaces for clients, and keep Spring for gateways with logic, contracts and fallbacks.

Likely follow-ups
"Do I still need a service mesh if I use Resilience4j?"

They solve overlapping problems at different levels. A mesh (Istio, Linkerd) sits beside each pod as a proxy and gives retries, timeouts, circuit breaking (outlier detection), mutual TLS and traffic metrics for every service, whatever the language, with no code changes. Resilience4j runs in your code and can use business knowledge: it can return a fallback (a queued payment), treat "card declined" as not a failure, and protect one specific method.

A mesh cannot know that a retry of POST /charge is dangerous, or what to return when a service is down. Mesh-level retries on non-idempotent calls can multiply the very problem you tried to solve; configure them for GETs only.

My split: the mesh for transport concerns (TLS, basic timeouts, traffic shifting, metrics), the application for semantic concerns (idempotency, fallbacks, bulkheads). Do not configure both to retry the same call: three retries in the mesh times three in the code is nine.

"What does spring-cloud-kubernetes do?"

It lets a Spring Boot application use Kubernetes objects directly: read ConfigMaps and Secrets as property sources (with optional reload on change), discover services and endpoints through the Kubernetes API instead of Eureka, and expose health information that fits the probes. It needs RBAC permissions for the pod's service account to read those objects.

Compare it with plain mounting: a ConfigMap mounted as a file and imported with spring.config.import=optional:file:... or as a config tree needs no extra library and no API permissions, and it is easy to reason about. The library adds convenience and live reload at the price of coupling to the API and extra permissions.

I prefer plain mounted configuration and Service DNS names, and I add the library only if live reload or API-based discovery is a real requirement.

"Is Spring Cloud Gateway the same as an Ingress controller?"

No. An Ingress controller (Nginx, Traefik, a cloud load balancer) receives traffic at the cluster edge and routes by host and path to Services, and handles TLS. It is configured with YAML and is language-neutral.

Spring Cloud Gateway is an application you write and deploy: routes and filters are defined in Java or YAML, and filters are code, so they can implement authentication relay, request rewriting, per-user rate limits (with Redis), A/B routing and response shaping with the full Spring ecosystem and your unit tests.

Many systems use both: the Ingress for the edge and TLS, and a gateway behind it for API-level policy. If your gateway does only path routing, the Ingress alone is enough, and one fewer service to run.

"What replaced Hystrix and Ribbon, which older tutorials mention?"

Both are gone from current Spring Cloud. Netflix Hystrix (circuit breaker) was replaced by the Spring Cloud Circuit Breaker abstraction with Resilience4j as the usual implementation; Ribbon (client-side load balancing) was replaced by Spring Cloud LoadBalancer. If a tutorial uses @HystrixCommand or @RibbonClient, it is years old.

On Boot 4 the practical path is Spring Framework 7's built-in @Retryable and @ConcurrencyLimit, plus Resilience4j for breakers (see section 06), and Kubernetes Service for load balancing.

When you inherit an old code base, look at the Spring Cloud and Boot compatibility matrix first: a Spring Cloud release train supports specific Boot lines, and mixing them is the quickest way to a start-up error.

Q91. "What does gRPC support in Spring Boot 4.1 give you?"

Reveal answer

Strong answer gRPC is a remote procedure call system from Google: services and messages are described in .proto files, a compiler generates client and server code, messages are sent as compact binary (Protocol Buffers) over HTTP/2, and streaming in both directions is built in. It is popular for internal service-to-service calls where speed, strong contracts and streaming matter, and for polyglot systems because the generated code exists for many languages.

Before Boot 4.1 you wired gRPC yourself, or with a community starter. With the Spring gRPC project, Spring Boot 4.1 (June 2026) adds auto-configuration for both sides: for a gRPC server (your service implementations are picked up as beans and registered, with a server port, TLS through SSL bundles, health and reflection options) and for gRPC clients (channels created from named configuration, so you inject a stub instead of building a channel by hand). Metrics and tracing integrate through the usual Boot and Micrometer support.

What this gives you in practice: less boilerplate (no manual ServerBuilder or ManagedChannel), configuration through application.properties like the rest of Boot, and the Boot conveniences (actuator, security integration, testing support) around gRPC services.

Be careful with detail. I did not run gRPC for this chapter: the Spring gRPC libraries were not in the offline Maven cache of the course machine, so I cannot show a measured output, and the exact property names and annotations should be taken from the Spring Boot 4.1 and Spring gRPC reference documentation for your version rather than from this answer.

When to choose it: internal calls with high volume or latency-sensitive paths, streaming (server push of order updates, client upload streams), and contract-first APIs shared across languages. When not: browser-facing APIs (browsers need gRPC-Web and a proxy), public APIs where REST tooling and caching are expected, and teams without the skills to manage .proto versioning.

Contract rules for protobuf: never reuse or renumber a field, add new fields as optional, and deprecate rather than delete; that is how old and new services keep talking during a rolling deploy. Compare with REST in E6.

Picture it

The setup: No gRPC code was run. This picture is the contract-first workflow, written as a .proto file and the way to read it.

// illustrative — menu.proto (not compiled or run here)runs offline
// illustrative
syntax = "proto3";
package quickbite.menu;

service MenuService {
  rpc GetItem (ItemRequest) returns (Item);
  rpc WatchPrices (PriceFilter) returns (stream PriceChange);  // server streaming
}

message ItemRequest { int64 id = 1; }
message Item { int64 id = 1; string name = 2; int64 price_paise = 3; }

What you see: Field numbers (= 1, = 2) are the contract: they travel on the wire, not the names. A service has plain request/response calls and, with the stream keyword, streaming ones.

Why: Because the numbers are the identity, you may rename a field but never renumber or reuse one. That is the protobuf compatibility rule that matters most.

REST and JSON

Text, human-readable, easy for browsers and caches.

MenuController.javaruns offline
@GetMapping("/menu/{id}")
MenuItem item(@PathVariable long id) {
    return menu.find(id);
}

gRPC

Binary, generated stubs, streaming built in.

MenuGrpc.javaruns offline
// generated base class from menu.proto
class MenuGrpc extends MenuServiceImplBase {
  public void getItem(ItemRequest r,
      StreamObserver<Item> out) { ... }
}

The shift: Pick gRPC for internal, typed, streaming calls and REST for public and browser-facing ones.

Land it Boot 4.1 auto-configures gRPC servers and clients so I write only the service logic; I confirm the property names in the reference and keep browsers on REST.

Likely follow-ups
"What is the difference between gRPC and REST in one paragraph?"

REST over HTTP/JSON is resource-oriented and text-based: it works in a browser, a curl command and a cache, and the contract is often informal (OpenAPI helps). gRPC is operation-oriented and binary: the contract is a .proto file, clients and servers are generated, messages are small and fast to parse, HTTP/2 multiplexes many calls on one connection, and streaming is a first-class part.

The cost is tooling and visibility: you cannot read a gRPC message with curl and your eyes, browsers need a translation layer, and debugging uses special tools (grpcurl, reflection). REST is the default for public APIs; gRPC is a good internal choice.

"How do deadlines and errors work in gRPC?"

gRPC has deadlines rather than plain timeouts: the client sets withDeadlineAfter(2, SECONDS) and the deadline is passed to the server, which can stop work when it expires, and further calls made by the server inherit the remaining time. Always set one, for the same reason as any HTTP timeout (Q53).

Errors are status codes, not HTTP statuses: OK, INVALID_ARGUMENT, NOT_FOUND, DEADLINE_EXCEEDED, UNAVAILABLE and so on. Retry only the transient ones (UNAVAILABLE) and only idempotent calls; gRPC channels support retry policies in configuration.

Map your domain errors to the right code deliberately, so clients can decide what to do.

"How do I load balance gRPC on Kubernetes?"

A gRPC client keeps one long-lived HTTP/2 connection and sends many calls over it. A normal Kubernetes Service balances connections, not calls, so one client may send everything to one pod. That is the classic gRPC surprise.

Options: use a headless Service and a client-side load balancer (the gRPC client resolves all pod addresses and round-robins), use a service mesh whose sidecar balances per call (Istio, Linkerd), or put an L7 proxy such as Envoy in front. Check what your platform does before you load-test.

Also watch for connection draining during deploys: servers should send GOAWAY and finish in-flight calls, which a graceful shutdown setting helps with.

"Can I expose the same service over both REST and gRPC?"

Yes, by keeping the business logic in a plain service class and writing two thin adapters: a @RestController and a gRPC service implementation, both calling the same service. Neither adapter contains rules. This also keeps the domain independent of the wire format.

Tools exist to generate a REST facade from .proto files (gRPC-Gateway in Go, Envoy's JSON transcoding), which is attractive if the contract should be defined once.

The risk is doubled surface: two contracts to version, two sets of tests, two kinds of errors. Do it only when you really have both kinds of clients.

Drill · Spring Boot 4.x

Nine questions on the 4.0, 4.1 and 4.2 releases: what breaks, what the modular starters change, why JSON output moved, how API versioning and RestClient work, and how to plan an upgrade and a production-ready service.

Q92. "What changed in Spring Boot 4.0 that breaks a 3.5 application?"

Reveal answer

Strong answer Boot 4.0 (November 2025) is a major release on Spring Framework 7, so some breaks are expected, and most are compile errors that tell you what to do. I group them by how you find them: build, compile, run and test.

Build. Starters are now modular (Q93). spring-boot-starter-aop is gone, replaced by spring-boot-starter-aspectj: on 4.2.0 the dependency spring-boot-starter-aop could not be resolved at all, and Maven reported the artifact as absent. spring-boot-starter-web still resolves in 4.2.0 but is deprecated in favour of spring-boot-starter-webmvc (a spring-boot-starter-classic also exists as a bridge), so treat it as a warning to fix now. Each technology also gets its own test starter, such as spring-boot-starter-webmvc-test.

Compile. Jackson 3 moved its packages: com.fasterxml.jackson.databind is now tools.jackson.databind (the annotations stay in com.fasterxml.jackson.annotation). The measured compile of a 3.5-style class against 4.2 failed with "package com.fasterxml.jackson.databind does not exist" and "cannot find symbol: class ObjectMapper". org.springframework.boot.web.client.RestTemplateBuilder moved to org.springframework.boot.restclient and, with RestTemplate, is deprecated for removal. Other packages moved with the modularisation (auto-configuration classes now live in per-module packages such as org.springframework.boot.flyway.autoconfigure).

Run. Defaults and renamed properties: spring-boot-properties-migrator prints renamed keys at start (Q94 area, and the idiom). In the measured run server.tomcat.redirect-context-root was mapped automatically to server.tomcat.servlet.redirect-context-root, and management.endpoints.enabled-by-default was reported as no longer supported. JSON output changes with Jackson 3 (Q94). Undertow support was removed (check your web server choice).

Test. @MockBean and @SpyBean are removed: use @MockitoBean and @MockitoSpyBean from Spring Framework 7. JUnit is on version 6, and a new RestTestClient joins MockMvc.

Framework 7 itself raises the baseline (Jakarta EE 11, Servlet 6.1, Hibernate ORM 7), removes long-deprecated APIs, and adds core resilience annotations and API versioning (section 11).

How I find them: read the official "Spring Boot 4.0 migration guide" and the release notes of 4.1 and 4.2, add the properties migrator, upgrade to the latest 3.5.x first so that deprecation warnings are visible, and then let the compiler list the rest. Treat warnings as the work list.

Picture it

The setup: A small 3.5-style PriceClient imports com.fasterxml.jackson.databind.ObjectMapper and org.springframework.boot.web.client.RestTemplateBuilder and is compiled against Boot 4.2. Separately, the build asks for spring-boot-starter-aop.

PriceClient.java (3.5 style) · compiled on Boot 4.2runs offline
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.client.RestTemplate;

public PriceClient(RestTemplateBuilder builder, ObjectMapper mapper) {
    this.rest = builder.rootUri("http://menu.internal").build();
    this.mapper = mapper;
}

Make the invisible visible: Compile it and ask Maven for the old AOP starter.

mvn compile · Boot 4.2 (code/e22-spring-in-depth/E/, trimmed)runs offline
[WARNING] com/quickbite/legacy/PriceClient.java:[10,19] org.springframework.web.client.RestTemplate i...
[ERROR] com/quickbite/legacy/PriceClient.java:[3,38] package com.fasterxml.jackson.databind does not ...
[ERROR] com/quickbite/legacy/PriceClient.java:[4,43] package org.springframework.boot.web.client does...
[ERROR] com/quickbite/legacy/PriceClient.java:[11,19] cannot find symbol
  symbol:   class ObjectMapper
  location: class com.quickbite.legacy.PriceClient
[ERROR] com/quickbite/legacy/PriceClient.java:[13,24] cannot find symbol
  symbol:   class RestTemplateBuilder
[ERROR] com/quickbite/legacy/PriceClient.java:[13,53] cannot find symbol
[ERROR]   symbol:   class ObjectMapper
[ERROR]   location: class com.quickbite.legacy.PriceClient
[ERROR]   symbol:   class RestTemplateBuilder

# dependency spring-boot-starter-aop:4.2.0
he following artifacts could not be resolved: org.springframework.boot:spring-boot-starter-aop:jar:4....

What you see: One deprecation warning (RestTemplate ... deprecated and marked for removal) and a list of errors, each naming a missing package or symbol. The AOP starter is simply not found, so the build fails before any code is compiled.

Why: Moved packages and renamed artifacts fail loudly. The silent changes are the dangerous ones (JSON shape, defaults), and those need tests, not the compiler.

Boot 3.5 imports

Old packages and starters.

PriceClient.javaruns offline
import com.fasterxml.jackson
    .databind.ObjectMapper;
import org.springframework.boot
    .web.client.RestTemplateBuilder;

Boot 4.2 imports

New packages; RestClient instead of the template.

PriceClient.javaruns offline
import tools.jackson
    .databind.json.JsonMapper;
import org.springframework.web
    .client.RestClient;

The shift: Most breaks are renames; read the compiler's list top to bottom.

Land it Boot 4 breaks starters (aop, web), Jackson imports, RestTemplate and mock annotations loudly at build time, and JSON and defaults quietly at run time.

Likely follow-ups
"What is the safest order to upgrade a 3.5 service?"

In small steps. First update to the latest 3.5.x patch so you are on the last release of the old line and see every deprecation warning. Fix those warnings while still on 3.5, because they are the same APIs that 4.0 removes. Then switch the parent to 4.0 (or straight to 4.2) with the properties migrator on the classpath and fix compile errors. Run the full test suite, then compare behaviour: JSON output of key endpoints, start-up time, metrics names and logs.

Deploy to a staging environment that mirrors production, run contract and smoke tests, and canary a single pod. Keep the 3.5 build deployable until the new one has run a week. Remove the properties migrator at the end.

This is the checklist in section 11, and the plan in Q98 applies it to many services.

"Why is spring-boot-starter-aop gone, and what replaces it?"

The old starter pulled spring-aop and AspectJ's weaver. In the modular Boot 4 design, a starter's name should say which technology it brings. spring-boot-starter-aspectj brings AspectJ (the @Aspect annotations and the weaver that Spring AOP uses to parse pointcut expressions). Spring AOP's core is part of spring-context already, so plain proxies for @Transactional and @Cacheable do not need an extra starter; you need the AspectJ starter when you write @Aspect classes (section 02).

The measured resolution: spring-boot-starter-aop:4.2.0 was reported "absent" in Maven Central. Replace the dependency name, nothing else changes in your aspect code.

"What replaces @MockBean?"

@MockitoBean (and @MockitoSpyBean), from Spring Framework's test module (spring-test 7.1), which have been available since Framework 6.2. The behaviour is the same: replace a bean in the application context with a Mockito mock for the test. They can be placed on a field or on the test class with a types attribute, and are cached with the context like other test settings.

The Boot-specific @MockBean and @SpyBean were deprecated in 3.4 and removed in 4.0. If a test class fails with "cannot find symbol MockBean", replace the import and the annotation name; the code in the test usually stays the same.

For a Spring-wide mock without Mockito you can also use @TestBean, which uses a factory method in the test class to supply the replacement.

"Is Java 17 still enough for Boot 4?"

Yes. The baseline for Spring Framework 7 and Boot 4 is Java 17, and they support up to the current LTS and newer releases (this chapter ran on Java 25). If you are still on Java 11, the Java upgrade comes first; Boot 3 already required 17.

If you move to Java 21 or 25 you get virtual threads and the newer language features (E21); Boot 4 runs well on them. Note that bytecode compiled for a newer Java than your runtime fails at start (UnsupportedClassVersionError), so keep the build and runtime JDKs aligned.

Check library versions too: a very old third-party library may not support the newer JDK or Jakarta EE 11, and that is often the real blocker.

Q93. "Why were the starters split into modules, and what changes in your pom?"

Reveal answer

Strong answer Before Boot 4, Spring Boot's auto-configuration lived in one large jar, spring-boot-autoconfigure, which contained the classes for hundreds of technologies, and a starter such as spring-boot-starter-web pulled in a bundle of libraries. The jar was big, scanning its auto-configuration list took time at start, and a starter's content did not say clearly what it provided.

Boot 4.0 splits the code into modules, one per technology: Spring MVC, Flyway, Jackson, data JPA and so on, each with its own jar containing its auto-configuration, properties and classes, in its own package (for example org.springframework.boot.flyway.autoconfigure). The starters are renamed to match, and each technology gets a matching test starter.

What it buys you: smaller classpaths (fewer unused classes), clearer dependencies (a starter name equals a technology), faster and more predictable auto-configuration (fewer conditions evaluated), and easier maintenance for the Boot team and for third parties.

What changes in your pom:

  • spring-boot-starter-web becomes spring-boot-starter-webmvc (the old name still resolves in 4.2.0 but is deprecated; spring-boot-starter-classic also exists as a migration aid).
  • spring-boot-starter-aop becomes spring-boot-starter-aspectj.
  • spring-boot-starter-test is split: you add spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test, spring-boot-starter-validation-test and so on for what you use. In the base project of this chapter each feature starter has its -test partner.
  • Flyway comes through spring-boot-starter-flyway, which is also what makes Flyway auto-configuration available at all; in 3.5 the Flyway library alone was enough.
  • Imports of Boot classes move to module packages (RestTemplateBuilder to org.springframework.boot.restclient).

An easy trap: a library on the classpath without its Boot module no longer triggers auto-configuration. If a feature "stopped working" after the upgrade (no Flyway run, no Jackson customisation), check that you have the matching starter, not only the library.

Picture it

The setup: The base project of this chapter, a Boot 4.2 pom with the modular starters, set against the 3.5 equivalent.

Boot 3.5

Few starters, one big test starter.

pom.xml (3.5)runs offline
spring-boot-starter-web
spring-boot-starter-aop
spring-boot-starter-data-jpa
flyway-core
spring-boot-starter-test

Boot 4.2

One starter per technology, each with a test partner.

pom.xml (4.2)runs offline
spring-boot-starter-webmvc
spring-boot-starter-aspectj
spring-boot-starter-data-jpa
spring-boot-starter-flyway
spring-boot-starter-webmvc-test
spring-boot-starter-data-jpa-test

The shift: A starter name now states a technology, and tests bring their own starter.

Make the invisible visible: The real dependency block of the course's Boot 4.2 base project (excerpt).

pom.xml · Boot 4.2 (code/e22-spring-in-depth/base/)runs offline
<dependency><artifactId>spring-boot-starter-webmvc</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-aspectj</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-flyway</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-validation</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-cache</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-actuator</artifactId></dependency>
<!-- test scope -->
<dependency><artifactId>spring-boot-starter-webmvc-test</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-data-jpa-test</artifactId></dependency>
<dependency><artifactId>spring-boot-starter-flyway-test</artifactId></dependency>
<!-- groupId org.springframework.boot omitted for width; trimmed -->

What you see: Every technology appears twice: once to use it and once, in test scope, to test it. That symmetry is the practical face of the modular design.

Why: Splitting by technology lets each module declare exactly what it needs, so the build tool can keep unused code off the classpath and the test starters can bring only the matching test support.

Land it Boot 4's modular starters name a technology each, with a test starter beside it, and a library without its starter no longer auto-configures.

Likely follow-ups
"Is spring-boot-starter-web really gone?"

Not yet in 4.2.0, but it is deprecated. The measured build resolved spring-boot-starter-web and produced a deprecation message in favour of spring-boot-starter-webmvc. Only spring-boot-starter-aop truly disappeared (its published versions stop at 4.0.0-M2). A spring-boot-starter-classic exists as a transition starter that brings the broad set of the old behaviour.

Plan to move to the new names while you do the upgrade, since a deprecated starter is a future removal. Use ./mvnw dependency:tree before and after to see what changed on the classpath: usually the tree gets smaller.

"Why must I add spring-boot-starter-flyway and not just flyway-core?"

Because the Flyway auto-configuration moved into the Flyway module that the starter brings. In 3.5, flyway-core on the classpath was enough: FlywayAutoConfiguration sat in the big autoconfigure jar and switched itself on when it found the Flyway class. In 4.x the auto-configuration is in spring-boot-flyway, and only the starter (or that module) brings it.

The symptom of forgetting it: the app starts with no error, Flyway never runs, and Hibernate fails later because the tables do not exist, or worse, ddl-auto creates them. The same pattern applies to every technology: the library alone is not enough, add the starter.

To verify that auto-configuration is active, use the conditions report (--debug) and look for the module's auto-configuration under positive matches.

"How do the test starters change how I write tests?"

Mostly nothing in the test code, but you must add the right test starter for the slice you use. @WebMvcTest needs spring-boot-starter-webmvc-test, @DataJpaTest needs spring-boot-starter-data-jpa-test, @JsonTest needs the JSON test support, and so on. A single catch-all spring-boot-starter-test still exists for the basics (JUnit, AssertJ, Mockito), but the slice annotations come from the technology's test starter.

Typical failure: "cannot find symbol WebMvcTest" or a missing MockMvc auto-configuration after upgrading. The fix is a missing -test dependency.

Benefits: test classpaths contain only what your tests use, and the slices are documented with their technology.

"What does "modular" mean for my own library or starter?"

If you publish an auto-configuration (Q69), the model is the same: @AutoConfiguration classes listed in the .imports file. Boot 4's own modules now follow the pattern of one module per technology, which you can copy for a large internal platform: an -autoconfigure jar with the code and a thin starter pom.

What changed for authors: some Boot classes you extended or referenced moved package, and a few conditions or test utilities live in the new module jars. Compile your starter against 4.x and read the errors.

Test with ApplicationContextRunner (Q70) on both Boot lines if you support 3.5 and 4.x for a while, and publish separate versions if the APIs diverge.

Q94 · Scenario. "After upgrading to Boot 4, JSON output changed and a client broke. Why?"

Reveal answer

Strong answer Boot 4 uses Jackson 3 (tools.jackson.*) by default, not Jackson 2.x (com.fasterxml.jackson.*), and Jackson 3 changed several defaults on purpose. A client that parsed the old shape exactly, or a test that compared JSON strings, sees a different document. The service did not "break"; the serialisation rules changed.

I compared the two with the same record in the measured demo. A JsonMapper from Jackson 3 and a plain Jackson 2.17.3 ObjectMapper with the date module, serialising an order with a date, an instant, a decimal and a null:

  • Dates and instants. Jackson 2 wrote the LocalDate as an array ([2026,12,2]) and the Instant as a decimal number of seconds (1796206530.000000000), unless you disabled WRITE_DATES_AS_TIMESTAMPS. Jackson 3 writes ISO text: "2026-12-02" and "2026-12-02T10:15:30Z".
  • Property order. Jackson 3 sorts properties alphabetically by default (customer, id, note, paidAt...); Jackson 2 used declaration order (id, status, placedOn...). Order does not matter to a real JSON parser but breaks tests that compare strings and clients that parse by position.
  • Unknown properties. A bare Jackson 2 mapper threw UnrecognizedPropertyException on an unknown field; the Jackson 3 mapper (and Boot's) accepted it. That is more tolerant for you as a receiver, and a silent change if you relied on rejection for validation.

Boot's own JsonMapper bean gave the same output as the bare Jackson 3 builder in this run, so most of the change is Jackson 3's, not Boot customisation.

How to handle it: find the difference with a contract test that serialises your real responses, decide whether the new format is acceptable (ISO dates are what most clients want) and tell clients, or pin the old behaviour with explicit mapper settings (a JsonMapperBuilderCustomizer or properties such as spring.jackson.serialization.write-dates-as-timestamps, check the names for your version) until clients migrate.

Prevention: never rely on defaults for public JSON. Use explicit formats (@JsonFormat on important fields), contract tests (Spring Cloud Contract, Pact) or snapshot tests of responses, and release the upgrade behind the API versioning from Q95 if a break is unavoidable.

Picture it

The setup: One Order record with an id, status, a LocalDate, an Instant, a BigDecimal, a null note and a customer. It is serialised by Jackson 2.17.3 (with the Java time module), by a bare Jackson 3 mapper and by Boot's auto-configured mapper. Unknown-property handling is tested separately.

Make the invisible visible: Print the same object three ways.

run --demo=jackson · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
J2: {"id":42,"status":"PLACED","placedOn":[2026,12,2],"paidAt":1796206530.000000000,"total":499.00,"note":null,"customer":"asha"}
J3: {"customer":"asha","id":42,"note":null,"paidAt":"2026-12-02T10:15:30Z","placedOn":"2026-12-02","status":"PLACED","total":499.00}
Boot: {"customer":"asha","id":42,"note":null,"paidAt":"2026-12-02T10:15:30Z","placedOn":"2026-12-02","status":"PLACED","total":499.00}
J2 unknown property: UnrecognizedPropertyException
J3 unknown property: accepted (id=1)
Boot unknown property: accepted

What you see: Jackson 2 prints the date as [2026,12,2] and the instant as a decimal; Jackson 3 and Boot print "2026-12-02" and "2026-12-02T10:15:30Z" and sort the keys alphabetically. Jackson 2 rejected an unknown property; Jackson 3 and Boot accepted it.

Why: Jackson 3 changed defaults to what most APIs wanted all along. A default is part of your public contract the day a client depends on it.

Jackson 2 output

Arrays, decimals, declaration order.

responseruns offline
{"id":42,"status":"PLACED",
 "placedOn":[2026,12,2],
 "paidAt":1796206530.0}

Jackson 3 output

ISO text, alphabetical keys.

responseruns offline
{"customer":"asha","id":42,
 "paidAt":"2026-12-02T10:15:30Z",
 "placedOn":"2026-12-02"}

The shift: Defaults changed; make the formats you promise explicit.

Land it Jackson 3 changed date, ordering and unknown-property defaults, so I diff real responses with a contract test and make public formats explicit.

Likely follow-ups
"How do I keep the old Jackson 2 behaviour during the migration?"

Two options. Keep Jackson 2 for a while: Boot 4 can still support Jackson 2 through compatibility modules (spring-boot-jackson2) so that code using com.fasterxml.jackson keeps working, and you migrate class by class. Check the Boot 4 migration guide for the exact module and properties of your version.

Or stay on Jackson 3 and set the old formats explicitly: serialise dates as timestamps (spring.jackson.serialization.write-dates-as-timestamps=true), configure @JsonPropertyOrder for fields that need a fixed order, and spring.jackson.deserialization.fail-on-unknown-properties set to true to restore rejection. Verify each property name against the 4.2 metadata, because they were reorganised.

Treat both as bridges. The goal is to move clients to the ISO formats and stop depending on defaults.

"What is the difference in package names and annotations?"

Jackson 3 moved the core packages from com.fasterxml.jackson.* to tools.jackson.*: ObjectMapper is still there but the usual way to build one is JsonMapper.builder(), and mappers are immutable once built (configure them on the builder). The annotations (@JsonProperty, @JsonIgnore, @JsonFormat) stay in com.fasterxml.jackson.annotation, so your model classes mostly compile unchanged.

The exceptions changed too: Jackson 3 uses unchecked exceptions (JacksonException), so a lot of throws clauses and try/catch blocks can be removed.

The measured compile error showed the first symptom: "package com.fasterxml.jackson.databind does not exist". Third-party libraries that expose Jackson 2 types in their API need versions that support Jackson 3.

"How do I test that my API output did not change?"

With a contract or snapshot test. The simplest: call your controller with MockMvc or RestTestClient, compare the response body with a stored JSON file using JSONAssert or JsonUnit in strict mode, and commit the file. After the upgrade, a diff in the snapshot is a visible, reviewable change.

Better for APIs with consumers: consumer-driven contracts (Pact or Spring Cloud Contract), where each client publishes what it expects, and the provider's build verifies it. Then "the client broke" is caught by the build before release.

Run the test on the old and the new version side by side during the upgrade; keep the stored snapshot as the baseline and review every difference.

"Does Jackson 3 change anything for my database or Redis serialisation?"

Anything that stores Jackson-serialised data now has two formats to worry about: the old data (written by Jackson 2) and the new data. A cache or a JSON column that holds LocalDate as an array in old rows will not parse as ISO text without extra handling. Jackson 3 can read some legacy forms if configured; test with real stored samples.

The practical advice: for Redis caches, change the key prefix or version so old entries are simply ignored and rebuilt; for database JSON columns, run a migration or write a tolerant deserialiser during the transition. The same applies to messages already in Kafka topics with old JSON: consumers must read both.

This is the same compatibility discipline as for any schema change: expand (accept both), migrate, contract (accept the new only).

Q95. "How does API versioning work in Spring Framework 7 and Boot 4?"

Reveal answer

Strong answer A public API must change without breaking existing clients, so you keep two versions alive for a while. Spring Framework 7 builds this into Spring MVC. You put a version attribute on a mapping, and the framework decides which method serves a request by the version the client asked for.

Two parts. In code:

OrderVersionController.java · Boot 4.2runs offline
@GetMapping(path = "/orders/{id}", version = "1")
Map<String, Object> v1(@PathVariable long id) { /* total: 499.0 */ }

@GetMapping(path = "/orders/{id}", version = "2")
Map<String, Object> v2(@PathVariable long id) { /* total: {amount, currency} */ }

In configuration, you tell Spring where the client puts the version. The strategies are a request header, a query parameter, a path segment (/v2/orders) or a media-type parameter. In Boot the properties are under spring.mvc.apiversion:

application.properties · Boot 4.2runs offline
spring.mvc.apiversion.use.header=API-Version
spring.mvc.apiversion.supported=1,2
spring.mvc.apiversion.default=1

The measured run: with no header the default version 1 answered ("total":499.0); API-Version: 1 gave the same; API-Version: 2 gave the new nested total ({"amount":499.0,"currency":"INR"}); and API-Version: 3, not in the supported list, got HTTP 400 Bad Request.

Design points to state. A default version keeps old clients that send nothing working, and you decide how long it stays 1. A list of supported versions turns an unknown version into a clear error instead of a silent fall-back.

Versions can be ranges with a baseline (version = "1.2+"), so a method serves that version and later ones until a newer mapping takes over; check the reference for the exact syntax of your Framework version. Deprecation can be signalled with response headers (Deprecation, Sunset) from a deprecation handler.

Choice of strategy: a header keeps URLs stable and is easy for machine clients; a path segment is visible and cacheable and easy to try in a browser; a media type is the most "REST-pure" and the least convenient. Whatever you choose, version the contract, not each endpoint without reason, and set a policy: how many versions you support and how long.

Idiom: API versioning with the version attribute.

Picture it

The setup: Two methods map the same path with version = "1" and version = "2": v1 returns total as a number, v2 returns it as an object. The version is read from the API-Version header, with supported versions 1 and 2 and default 1.

Make the invisible visible: Call it with no header and with versions 1, 2 and 3.

curl · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
$ curl -si localhost:18082/orders/7
HTTP/1.1 200 

{"id":7,"total":499.0}
$ curl -si -H 'API-Version: 1' localhost:18082/orders/7
HTTP/1.1 200 

{"id":7,"total":499.0}
$ curl -si -H 'API-Version: 2' localhost:18082/orders/7
HTTP/1.1 200 

{"id":7,"total":{"amount":499.0,"currency":"INR"}}
$ curl -si -H 'API-Version: 3' localhost:18082/orders/7
HTTP/1.1 400 

{"timestamp":"2026-12-01T19:14:54.166Z","status":400,"error":"Bad Request","path":"/orders/7"}

What you see: No header and version 1 give the same old shape. Version 2 gives the new shape. Version 3 is rejected with a 400 error body.

Why: Spring builds a version resolver from the properties, parses the requested version, and the mapping condition matches only the method whose version fits.

Version in every path by hand

Two controllers and copies of the rules.

Controllers.javaruns offline
@GetMapping("/v1/orders/{id}")
Order v1(...) { ... }

@GetMapping("/v2/orders/{id}")
OrderV2 v2(...) { ... }

The version attribute

One path, versions chosen by the framework.

Controller.javaruns offline
@GetMapping(path = "/orders/{id}",
            version = "1")
Order v1(...) { ... }

@GetMapping(path = "/orders/{id}",
            version = "2")
OrderV2 v2(...) { ... }

The shift: Let the framework route by version and keep the path stable.

Land it I give each contract change a version attribute, resolve it from a header, support a stated list, default old clients, and announce sunsets.

Likely follow-ups
"How do I deprecate and finally remove version 1?"

Announce first. Add response headers on v1 (Deprecation: true and Sunset: <date>, optionally a Link to the migration guide) so that clients and gateways can see it in their logs. Measure usage: a metric tagged with the resolved version shows which clients still call v1; contact the owners of the remaining traffic.

When usage is zero (or the sunset date has passed), remove v1 from the supported list. Clients that still send API-Version: 1 then get a 400, which is a clear signal. Only afterwards delete the code.

Set the policy in advance ("we support the current and the previous version, for at least six months after the new one ships") so that it is not renegotiated for every release.

"Which versioning strategy should I choose: header, path, query parameter or media type?"

Header (API-Version: 2): clean URLs, easy for programmatic clients, invisible in a browser and in logs unless you record it. Path (/v2/orders): obvious, easy to test with a link, easy to route and cache at a gateway; it changes the URL of the resource. Query parameter (?version=2): simple, but caches and logs may drop it. Media type (Accept: application/vnd.quickbite.v2+json): the purist's option for content negotiation, harder to use and document.

My default for internal and partner APIs is a header, since URLs identify resources and the version is a property of the representation. For public APIs used by many developers, a path segment is friendlier. Pick one and keep it the same across all your services.

Whatever you choose, record the version in logs and metrics.

"Do I need a new version for every change?"

No. Only for breaking changes: removing or renaming a field, changing its type or meaning, tightening validation, changing status codes. Adding an optional field, a new endpoint or a new optional parameter is backward compatible and needs no new version, provided clients ignore unknown fields (the Jackson 3 default accepts them on the server side; clients need the same tolerance).

Aim for few versions. A good API design (additive changes, expand and contract) means a major version every couple of years, not every quarter. If you find yourself versioning often, the real problem is in how the contract is designed and communicated.

Write a compatibility rule down for reviewers: "adding is fine; changing or removing needs a version". See E6.

"How do I test the versioned endpoints?"

Write a test per version and one for the failure case, using MockMvc or RestTestClient and the API-Version header: version 1 returns the old shape, version 2 the new shape, no header returns the default, and an unsupported version returns 400. Set the properties in the test (@SpringBootTest(properties = ...)) so the test does not depend on the main configuration.

Keep golden JSON files for each version and compare. This also protects against the quiet breakage from Q94: a Jackson upgrade changing the shape of version 1.

Add a test that fails when someone adds a new supported version without a mapping for it, so the configuration and the code cannot drift apart.

Q96. "What did Spring Boot 4.1 and 4.2 add?"

Reveal answer

Strong answer Boot 4.0 was the big reset (Framework 7, modular starters, Jackson 3). The two releases after it are smaller, and for each I give what I verified and mark what I only read.

Boot 4.1 (June 2026). The main addition is gRPC auto-configuration for servers and clients (Q91), built on the Spring gRPC project. It also added auto-configured Redis listener endpoints: a default RedisMessageListenerContainer is set up, so subscribing to channels needs less manual wiring. Smaller changes are in the release notes; read them for your modules.

Boot 4.2 (November 2026, on Spring Framework 7.1). The change that touches the most code: RestTemplate is deprecated in favour of RestClient. I confirmed it by compiling: RestTemplate and RestTemplateBuilder carry @Deprecated(since = "7.1", forRemoval = true) and the compiler warns (Q97). 4.2 also adds AMQP 1.0 support for RabbitMQ and other brokers, a cache for Buildpacks image builds (faster spring-boot:build-image runs) and SSL bundle support for LDAP, so LDAP connections can use the same trust and key configuration as other clients.

The baseline of 4.2.0 as it appeared on the classpath of this chapter's projects (read from the packaged jar of the Boot 4.2 demo application):

BOOT-INF/lib · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
HikariCP-7.1.0.jar
aspectjweaver-1.9.27.jar
caffeine-3.3.1.jar
flyway-core-12.11.0.jar
hibernate-core-7.4.15.Final.jar
jackson-databind-3.1.8.jar
micrometer-core-1.18.0.jar
resilience4j-circuitbreaker-2.4.0.jar
spring-boot-4.2.0.jar
spring-core-7.1.0.jar
spring-security-core-7.2.0.jar
tomcat-embed-core-11.0.27.jar

What I could not verify. I did not run gRPC, AMQP 1.0, the Redis listener auto-configuration, the Buildpacks cache or the LDAP bundles here, because the libraries or services were not available offline. Treat those four items as read from the release notes and check the Spring Boot 4.1 and 4.2 release notes and reference for names and defaults before relying on them.

How I use the information: in an upgrade, 4.1 is usually a drop-in step, and 4.2 asks for one planned piece of work (replace RestTemplate before the removal arrives). Read the "what's new" page of each release as a checklist of features you may now delete code for.

Picture it

The setup: The versions below are read from the executable jar that Maven built for a Boot 4.2.0 project, not from memory. The 4.1 and 4.2 features are listed in a table with the evidence level of this chapter.

unzip -l target/drill-0.0.1-SNAPSHOT.jar · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
HikariCP-7.1.0.jar
aspectjweaver-1.9.27.jar
caffeine-3.3.1.jar
flyway-core-12.11.0.jar
hibernate-core-7.4.15.Final.jar
jackson-databind-3.1.8.jar
micrometer-core-1.18.0.jar
resilience4j-circuitbreaker-2.4.0.jar
spring-boot-4.2.0.jar
spring-core-7.1.0.jar
spring-security-core-7.2.0.jar
tomcat-embed-core-11.0.27.jar
ReleaseAddedEvidence in this chapter
4.1 (June 2026)gRPC auto-configuration for server and clientRead from release notes, not run
4.1Auto-configured Redis listener endpointsRead from release notes, not run
4.2 (Nov 2026)RestTemplate deprecated in favour of RestClientCompiled: deprecation warning (Q97)
4.2AMQP 1.0 supportRead from release notes, not run
4.2Buildpacks image build cacheRead from release notes, not run
4.2SSL bundle support for LDAPRead from release notes, not run

What you see: The baseline matches the numbers in the section 11 table: Framework 7.1, Security 7.2, Hibernate 7.4, Jackson 3.1, Tomcat 11, Micrometer 1.18, Flyway 12.11. The table is honest about which features were run and which were only read.

Why: Release notes list features; only a build or a run proves them. Saying which is which is part of a trustworthy answer.

Boot 4.0 to 4.1

A feature release: gRPC and Redis listeners.

what to doruns offline
bump the parent version
read the 4.1 notes
adopt gRPC or Redis
listeners only if needed

Boot 4.1 to 4.2

A planning release: RestTemplate's end date.

what to doruns offline
bump the parent version
fix RestTemplate warnings
now, not at removal
adopt AMQP 1.0 if useful

The shift: 4.1 adds options; 4.2 adds a deadline.

Land it 4.1 added gRPC and Redis listener auto-configuration; 4.2 deprecated RestTemplate and added AMQP 1.0, a Buildpacks cache and LDAP SSL bundles, and I say which I ran.

Likely follow-ups
"Is it safe to jump from 4.0 straight to 4.2?"

Usually yes, if you are already on 4.0 and have fixed its deprecations, because minor releases keep compatibility and add features. Read the 4.1 and 4.2 release notes for removed deprecations: a feature deprecated in 4.0 may be removed in 4.2. The compiler warnings and the properties migrator catch most of it.

Do the jump in your usual staged way: a branch, the full test suite, staging, then a canary. Upgrade the Spring-managed dependencies together by changing only the parent version, and do not pin individual versions that Boot manages unless you must.

The one new deadline is RestTemplate in 4.2 (marked for removal). It still works in 4.2.0, so the jump does not break you, but it starts the clock.

"What is the support policy for Boot versions?"

Boot supports each minor release with bug fixes for about a year and commercial support longer; the open-source support window is shorter than most enterprise upgrade cycles. Check the Spring Boot support page for the current dates, as they change. In practice you plan to move to a new minor release at least once a year.

Use this to set a rule for your estate: no service more than one minor release behind, and a quarterly slot for dependency upgrades. Tools such as Renovate or Dependabot create pull requests for new patch and minor versions, so the work arrives in small pieces.

Remember that Spring Cloud, Spring Security and other projects follow Boot's calendar, so upgrade them together.

"How do I keep up with release notes without reading them all?"

Read the release notes of each minor release once, with a purpose: scan for Deprecated, Removed, Changed defaults and New and Noteworthy. Make a short list per service of what applies. The Boot GitHub wiki (release notes and migration guides) is the source.

Run the build with deprecation warnings visible (-Xlint:deprecation) and fail the CI on new ones in your own code. Add the properties migrator in the upgrade branch only. Subscribe to the security advisories feed for the libraries you use.

A useful habit is a short "upgrade note" in the repository after each upgrade: what broke, what you changed, what you verified.

"Which Boot 4.1 or 4.2 feature would you adopt first?"

For most services none of the new features is the first thing. The first piece of work is the migration cost: replacing RestTemplate with RestClient or HTTP interfaces, which is required anyway. After that, if you call internal services in a hot path, the gRPC support is worth a spike; if you use RabbitMQ and want the open standard protocol, the AMQP 1.0 support is worth reading about.

The Buildpacks cache helps teams that build images with spring-boot:build-image in CI: faster builds with no code change. LDAP SSL bundles matter to anyone with a secured directory.

My rule: adopt a feature when it deletes code or removes a risk you have, not because it is new.

Q97. "RestTemplate is deprecated in 4.2. What do you migrate to, and how?"

Reveal answer

Strong answer Migrate to RestClient, and for stable remote APIs go one step further to HTTP interface clients (@HttpExchange) built on it (Q86). In Boot 4.2 on Framework 7.1 both RestTemplate and Boot's RestTemplateBuilder are @Deprecated(since = "7.1", forRemoval = true): your code still compiles and runs, with warnings, and removal is announced.

I migrate in four passes, starting from the call sites that are cheapest and most common.

  1. Inventory: search for RestTemplate and RestTemplateBuilder (also test code using TestRestTemplate, which has its own replacement path), and group the call sites by remote system.
  2. Build one RestClient per remote system from the auto-configured RestClient.Builder, with a base URL, default headers, interceptors (auth, tracing) and the timeouts (spring.http.clients.connect-timeout and read-timeout, or the request factory).:
  3. Rewrite each call: getForObject(url, T.class) becomes .get().uri(url).retrieve().body(T.class); postForEntity becomes .post().uri(url).body(x).retrieve().toEntity(T.class); a custom error handler becomes .onStatus(...) or .exchange(...).
  4. Optionally turn the stable ones into @HttpExchange interfaces and register them with @ImportHttpServices, so the service code calls a Java interface that tests can mock.:

The measured demo ran the same calls on both. Both returned the same JSON map. On a 404 the old client threw NotFound; the new one let me map it to my own exception with onStatus, and read the status without any exception using exchange. A 1.5 s endpoint was cut after 504 ms by a 500 ms read timeout on the RestClient's request factory.

A transition tool exists: RestClient.create(restTemplate) builds a RestClient from an existing template, reusing its configuration (converters, interceptors, request factory), so code can move piece by piece while the old bean still exists. The demo printed RestClient.create(restTemplate) exists: true.

Check these during the move: error handling (the exception types differ in places), null responses (body() returns null for an empty body), URI template encoding, and tests (use MockRestServiceServer bound to the RestClient.Builder, or a stub server).

Do it before the removal release; do it at the pace of your tests, and never in one pull request with an upgrade of Boot.

Picture it

The setup: A service uses RestTemplate for /price and /missing. The migration adds a RestClient with a 500 ms read timeout and shows create(restTemplate) as a bridge. The numbers are from the G demo.

RestClientDemo.java (excerpt) · Boot 4.2runs offline
// before
RestTemplate rt = new RestTemplate();
Map<?, ?> a = rt.getForObject(base + "/price", Map.class);

// after
RestClient rc = RestClient.builder().baseUrl(base)
        .requestFactory(factory).build();
Map<?, ?> b = rc.get().uri("/price").retrieve().body(Map.class);

// bridge during the move
RestClient fromOld = RestClient.create(rt);

Make the invisible visible: Run both and compare errors and timeouts.

run --demo=restclient · Boot 4.2 (code/e22-spring-in-depth/G/)runs offline
RestTemplate  getForObject -> {item=biryani, paise=24900}
RestTemplate  404 -> NotFound 404 NOT_FOUND
RestClient    retrieve().body -> {item=biryani, paise=24900}
RestClient    404 handler -> no such item
RestClient    exchange() sees status without throwing -> 404 NOT_FOUND
RestClient    /slow -> ResourceAccessException after 504 ms
RestClient.create(restTemplate) exists: true

Make the invisible visible: The compiler's view of the old classes (from the Boot 4 legacy-style compile in section 11).

mvn compile · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
[WARNING] com/quickbite/legacy/PriceClient.java:[10,19] org.springframework.web.client.RestTemplate in org....

What you see: Both clients give the same data. The new one gives control of status handling and a timeout in one place. The compile warning is the signal that the old class has a removal date.

Why: RestClient is the same engine with a fluent front end. That is why the migration is mostly mechanical, and why behaviour differences cluster in error handling and configuration.

RestTemplate call

Template method; throws on 4xx and 5xx.

Price.javaruns offline
Map<?, ?> m = rt.getForObject(
    base + "/price", Map.class);

RestClient call

Fluent; status handling in the chain.

Price.javaruns offline
Map<?, ?> m = rc.get()
    .uri("/price")
    .retrieve()
    .body(Map.class);

The shift: The shape changes; the data and the transport stay the same.

Land it I build RestClient per remote system from the Boot builder with timeouts, port calls one by one with create(restTemplate) as a bridge, and promote stable APIs to HTTP interfaces.

Likely follow-ups
"What replaces TestRestTemplate in tests?"

In Boot 4 the recommended client for integration tests is RestTestClient, which was added with Spring Framework 7, together with the RestClient-based test support. It offers a fluent API similar to WebTestClient but for servlet-based and MockMvc-bound tests, and it can bind to a running server, to a MockMvc or to an application context.

Existing TestRestTemplate usage keeps working for now but follows RestTemplate's deprecation path; check the 4.2 notes for its status. For code-level tests of a client class, MockRestServiceServer bound to the RestClient.Builder remains a good approach.

Migrate tests with the main code, so the same style is used in both. Verify the exact class names and packages in the 4.2 reference.

"What is different in error handling between the two clients?"

Both throw RestClientResponseException subclasses (HttpClientErrorException, HttpServerErrorException) for 4xx and 5xx when you use retrieve() by default, so code that catches those keeps working. The demo printed NotFound 404 NOT_FOUND for the template.

The differences are the new options: onStatus(predicate, handler) lets you throw your own exception for chosen statuses, exchange(...) gives you the raw response and never throws for status codes, and a global default status handler can be set on the builder.

One trap: with exchange, you are responsible for closing and reading the response. Use the lambda form so that Spring closes it, and read the body inside the lambda.

"How do I add authentication or tracing headers to every call?"

With a ClientHttpRequestInterceptor registered on the builder (builder.requestInterceptor(...)), or a RestClientCustomizer bean that applies to all RestClient.Builder instances Boot gives out. The same interceptor idea worked for RestTemplate; the registration point is new.

Tracing needs no code if you build the client from Boot's auto-configured builder: the observation instrumentation adds the traceparent header for you, which is what keeps one trace id across services (Q76). A client you build with RestClient.builder() directly is not instrumented, a frequent reason for traces that stop at a service boundary.

For OAuth2 client credentials, Spring Security offers an interceptor that fetches and caches the token.

"What is the cheapest way to start when there are 300 RestTemplate call sites?"

Do not rewrite 300 calls. Start by finding the clients: usually there are four or five remote systems behind them. Create one RestClient bean per system, with the right base URL, timeouts and interceptors. Then move the call sites system by system, with the old RestTemplate bean left in place until the last one is gone.

Search patterns help: getForObject, postForObject, exchange( and execute(. An automated refactoring (OpenRewrite has recipes for Spring migrations) can handle the mechanical rewrites; review each change, especially error handling.

Add an ArchUnit rule that forbids new uses of RestTemplate as soon as the migration starts, so the count only goes down.

Q98 · Scenario. "Plan the migration of a 60-service estate from Boot 3.5 to 4.2."

Reveal answer

Strong answer I plan this as a programme with a pilot, a paved road and waves, not as 60 separate upgrades. The goal is that service number 60 costs a fraction of service number 1.

Phase 0 — Prepare (week 1 to 2). Inventory the 60 services: Boot version, Java version, build tool, Jackson usage, RestTemplate count, web server, test style, owner. Rank by risk (money paths, traffic) and by size. Make sure every service has tests, a pipeline and a staging deploy; a service without tests goes last, or gets tests first. Check shared libraries (internal starters, a company BOM) because they must move first.

Phase 1 — Platform first. Upgrade the internal parent POM, the BOM and every internal starter to build on Boot 4.2 (new starter names, Jackson 3, AutoConfiguration.imports) and publish them with a new major version. Services cannot upgrade until these exist.

Phase 2 — Pilot (2 to 3 services). Choose one small, one medium and one risky service. Upgrade each to the latest 3.5.x first, clear deprecation warnings, then move to 4.2 with the properties migrator. Record every change as a recipe: renamed starters, import changes, @MockitoBean, RestClient. Turn the recipes into an OpenRewrite configuration or a script and a migration guide with real before/after diffs.

Phase 3 — Waves. Group services by dependency and risk: wave 1 low-risk and low-traffic (10 services), wave 2 the middle (30), wave 3 critical (20). Run the recipe, fix the leftovers by hand, run the tests, deploy to staging, then a canary of one pod in production for a day, then the full rollout. Services that call each other are upgraded in an order that keeps their APIs compatible (consumers tolerant of unknown fields).

Phase 4 — Verify and clean up. Remove the properties migrator, replace remaining RestTemplate and old Jackson 2 usage, delete bridges.

Controls throughout. The three silent risks need explicit checks: JSON output (contract or snapshot tests, Q94), changed defaults and renamed properties (migrator output in each service's upgrade note), and behaviour under load (compare latency, memory and error rate before and after on the canary). Success measure: per wave, the percentage of services on 4.2, number of rollbacks, and time per service, so the estimate improves as you go.

Keep the rollback simple: the 3.5 artefact stays deployable, configuration is compatible with both where possible, and database migrations are forward-compatible (expand and contract) so that a rollback of code is safe.

Communicate: a calendar, a channel, an office hour, and a visible dashboard of the estate by version. A migration of 60 services is mostly a people and tracking problem; the code changes are repetitive.

Picture it

The setup: No estate was migrated here. The picture shows the plan as a table of waves, and the measured single-service evidence for the three silent risks used as the control checklist.

PhaseWhat happensExit criterion
0 PrepareInventory, ranking, tests presentEvery service has a pipeline and a staging deploy
1 PlatformParent POM, BOM, internal starters on Boot 4.2Published 4.x versions of all shared libraries
2 Pilot3 services, recipes capturedA migration guide and a script that runs on a new service
3 Waves10, then 30, then 20 services; canary eachPer wave: all services on 4.2, no open rollback
4 CleanupRemove migrator and bridgesNo RestTemplate, no Jackson 2 imports
upgrade note per service · templateruns offline
service: orders          owner: team-checkout     wave: 2
before: Boot 3.5.x, Java 21     after: Boot 4.2.0, Java 25
changed:  starter-web -> webmvc, starter-aop -> aspectj, tools.jackson imports
renamed properties (migrator): server.tomcat.redirect-context-root
JSON snapshot diff: dates now ISO text (clients notified: yes)
canary: 1 pod, 24 h, p99 +3 ms, errors unchanged
rollback: 3.5 image kept, no schema change

Make the invisible visible: Evidence that each check catches something real, from earlier answers of this chapter.

measured evidence · Boot 4.2 (code/e22-spring-in-depth/E/)runs offline
build break   : package com.fasterxml.jackson.databind does not exist
starter       : spring-boot-starter-aop:4.2.0 (absent)
property      : server.tomcat.redirect-context-root -> ...servlet.redirect-context-root
JSON          : [2026,12,2] -> "2026-12-02"

What you see: Each line is a different kind of break, found by a different control: compiler, dependency resolution, properties migrator and a response snapshot. The plan needs all four.

Why: Big migrations fail on repetition, not on difficulty. A recipe applied 60 times beats 60 clever solutions.

Service by service, ad hoc

Each team rediscovers the same breaks.

planruns offline
each team upgrades alone
60 different fixes
no shared guide
rollbacks found late

Paved road and waves

One pilot, recipes, canaries, a tracker.

planruns offline
platform libs first
pilot -> script + guide
waves of 10 / 30 / 20
canary + upgrade note

The shift: Do the thinking once, apply it many times.

Land it I upgrade the platform libraries first, pilot three services, capture recipes as a script and guide, then roll in risk-ordered waves with canaries and a tracker.

Likely follow-ups
"Why upgrade to the latest 3.5.x first, and not go straight to 4.2?"

Because it separates two kinds of problem. On the latest 3.5.x the compiler shows deprecation warnings for APIs that 4.0 removed. Those can be fixed while the application still runs on the version that production runs today, in small safe pull requests that are deployable on their own.

When you then switch to 4.2, what remains is the genuinely new: moved packages, starters, Jackson 3. A failed build has fewer possible reasons, and a failed test is easier to explain.

If you jump straight, every error is mixed with every other, and a pull request has 300 changed files. The extra week on 3.5.x saves two weeks later, and it is what the Spring team's migration guide recommends.

"How do you automate the mechanical changes?"

With OpenRewrite. It has Spring Boot migration recipes (upgrade the parent, rename starters, change imports, replace test annotations) that you run from Maven or Gradle, and you can write your own recipe for company-specific changes (your internal starter renames, a logging wrapper). The output is a normal diff that a person reviews.

Capture what the pilot teaches: every manual fix that appears twice becomes a recipe line. Keep the recipe in a repository, version it, and run it in a pipeline job that opens a pull request per service.

Automation does not replace tests: the recipe changes syntax; whether behaviour is preserved is for your tests and the JSON snapshot checks.

"How do you decide the order of the services in the waves?"

By blast radius and dependency. Low-traffic, well-tested, non-critical services go first: failures there cost little and teach a lot. Shared platform libraries and services that others depend on for contracts go early in terms of compatibility (their APIs must stay stable while consumers move), but their rollout is cautious.

Critical money paths go last, when the recipe is proven and the team is practised, and they get the longest canary and an extra review.

Avoid ordering by team convenience alone. Use the inventory: Boot version, test coverage, traffic, number of consumers, RestTemplate count. A simple score on those columns is enough to order 60 rows.

"What do you do when a few services cannot be migrated for months?"

Name them, give each an owner and a date, and isolate the risk. A service stuck on 3.5 needs a supported patch level, so check the support end date of 3.5 and plan the exception to end before it. Keep its dependencies patched for security. Make sure it does not block others: its public API stays compatible, and clients do not need Jackson 2 specifics.

Typical blockers: a library with no Jackson 3 or Framework 7 support, a team without capacity, or a service without tests. Each has its own remedy (replace the library, schedule capacity, write characterisation tests first), and the tracker shows the list weekly so it does not disappear.

If a service is going to be retired within a year, an explicit exception is fine; write it down.

Q99. "How do JSpecify null-safety annotations help in Spring Framework 7?"

Reveal answer

Strong answer NullPointerException is the most common runtime failure in Java, because the language does not say which references may be null. JSpecify is a shared, standard set of annotations (package org.jspecify.annotations) that says it, so that tools and people can check it. Spring Framework 7 and Boot 4 use JSpecify across their own APIs, replacing Spring's older @Nullable/@NonNull annotations from org.springframework.lang.

The model has two parts. @NullMarked on a package, class or module says "in this scope, every type is non-null unless marked otherwise". @Nullable marks the exceptions: a parameter, field or return type that may be null. JSpecify puts @Nullable on the type (type-use), which also covers generics (List<@Nullable String>) and arrays.

What I measured: I read the compiled classes of Spring Framework 7.1. The package org.springframework.core.env carries org.jspecify.annotations.NullMarked, and the method PropertyResolver.getProperty(String) has a type annotation @Nullable on its return type (METHOD_RETURN). So Spring says, in the bytecode, "this method can return null", and everything else in the package is non-null by default.

What it buys you:

  • IDE hints: IntelliJ and Eclipse read JSpecify and warn when you dereference a @Nullable return without a check, or pass null where non-null is expected.
  • Compile-time checks with a checker: NullAway (an Error Prone plugin) or the experimental JSpecify checkers turn violations into build errors for your own code, and use the annotations of the libraries you call, including Spring.
  • Kotlin interop: Kotlin reads JSpecify, so Spring APIs have accurate nullable and non-null types.
  • Documentation in code: a reader learns the contract from the signature, not from a comment.

In your own code: put @NullMarked on your packages (in package-info.java), mark the few places where null is allowed with @Nullable, return Optional or an empty collection where you can instead of null, and add NullAway to the build in warning mode first, then error mode for new code.

Be careful about what it does not do: the annotations do not change runtime behaviour. @NonNull does not insert a check; nulls still arrive from JSON, databases and reflection. They are a compile-time and tooling feature, which is exactly why they are cheap to adopt gradually. For input from outside (requests, messages), keep validating at the boundary (@Valid, Q61).

Picture it

The setup: Spring Framework 7.1's spring-core jar is inspected with javap: the package-info of org.springframework.core.env and the type annotations of PropertyResolver.getProperty(String). A tiny example of the annotations in application code follows.

Make the invisible visible: Ask the bytecode which annotations Spring's own API carries.

javap -v · Spring Framework 7.1 (code/e22-spring-in-depth/G/jspecify.out)runs offline
# method: PropertyResolver.getProperty(String)
    RuntimeVisibleTypeAnnotations:
      0: #12(): METHOD_RETURN
        org.jspecify.annotations.Nullable
# package: org.springframework.core.env
  #8 = Utf8               Lorg/jspecify/annotations/NullMarked;
    org.jspecify.annotations.NullMarked

What you see: The return type of getProperty is annotated org.jspecify.annotations.Nullable (a METHOD_RETURN type annotation) and the package is @NullMarked. So env.getProperty("x") may be null, and the checker will say so.

OrderLookup.java · JSpecify in application coderuns offline
@NullMarked                                   // in package-info.java
package com.quickbite.orders;

class OrderLookup {
    @Nullable Order find(long id) { return repo.byId(id); }   // may be null

    String describe(long id) {
        Order o = find(id);
        return o.summary();            // checker: o may be null
    }

    String safe(long id) {
        Order o = find(id);
        return o == null ? "unknown" : o.summary();
    }
}

Why: Nullness is part of a method's contract. A standard annotation set lets every library and tool read the same contract.

Contract in a comment

Nothing checks it.

OrderLookup.javaruns offline
/** may return null */
Order find(long id) {
    return repo.byId(id);
}
// caller forgets -> NPE in prod

Contract in the type

IDEs and checkers read it.

OrderLookup.javaruns offline
@Nullable
Order find(long id) {
    return repo.byId(id);
}
// o.summary() -> compile warning

The shift: Move the null contract from comments into types that tools can check.

Land it JSpecify makes nullness part of the signature, Spring 7 ships annotated, and I mark my packages @NullMarked and let a checker catch dereferences at build time.

Likely follow-ups
"What is the difference between @NullMarked and @NonNull?"

@NullMarked is a scope-level default: "everything here is non-null unless it carries @Nullable". You write it once per package, class or module. @NonNull marks one type as non-null explicitly, which JSpecify rarely needs because non-null is the default inside a @NullMarked scope; it is used in code that is not marked, or for unusual positions.

Compare with the older Spring annotations @NonNullApi and @NonNullFields (package-level non-null for parameters, return values and fields), which @NullMarked replaces with one more precise annotation that also covers generics and arrays.

Practical effect: the most common JSpecify code is just @NullMarked in package-info.java plus a few @Nullable on returns and fields.

"How do I enforce JSpecify in my build?"

With NullAway, an Error Prone checker. Add Error Prone and NullAway to the compiler plugins, set -XepOpt:NullAway:OnlyNullMarked=true (so that only @NullMarked code is checked, which allows gradual adoption) and JSpecifyMode=true. NullAway reports dereferences of nullable values, passing null to non-null parameters and returning null from non-null methods, as warnings or errors.

Start with the new code: mark new packages, keep old packages unmarked, and widen the marked area as you touch code. IDE inspections give instant feedback while you type; the build check keeps the guarantee for everyone.

Check the NullAway and Boot 4.2 documentation for current plugin versions and flags, as they change between releases.

"Does Spring's JSpecify annotation change how I write Spring code?"

Mostly it tells you things. When you call environment.getProperty(...), ResponseEntity.getBody() or request.getHeader(...), the nullable return types remind you to check. When you implement an interface from Spring, the parameter nullness is the contract you must accept, for example a @Nullable argument you must handle.

It also affects Kotlin users directly, since the types become nullable or non-null in the Kotlin view of the API.

In Java, if your code compiles with warnings off, nothing changes; the benefit comes when you turn the checker on.

"Should I use Optional or @Nullable?"

For a method return that may have no value, Optional<T> is the more explicit and forces the caller to deal with absence, and works in streams. @Nullable is lighter, has no allocation, and fits where an Optional would be awkward: fields, parameters, interop with frameworks that return null, and hot paths.

My rule: Optional for return values of public service methods; @Nullable for fields, parameters and framework-facing code; never Optional as a field or parameter. Do not mix both on one method (@Nullable Optional<T> is a defect).

Whichever you choose, state it once in a team guideline so APIs look alike.

Q100 · Design. "Whiteboard a production-ready Spring Boot 4.2 service for QuickBite: which starters, annotations and settings, and why."

Reveal answer

Strong answer I start from what production asks of a service, then name the starter, annotation or setting that answers each question, and I say what I would not add. This is the chapter on one page, so I walk the layers.

1. Build and starters. Parent spring-boot-starter-parent 4.2.0, Java 25 (or 21). Starters: spring-boot-starter-webmvc (HTTP), spring-boot-starter-data-jpa, spring-boot-starter-flyway (schema), spring-boot-starter-validation, spring-boot-starter-actuator, spring-boot-starter-security, spring-boot-starter-aspectj (only if I write aspects), spring-boot-starter-cache with Caffeine, and the matching -test starters. The OpenTelemetry starter for traces. Resilience4j for the payment breaker. No DevTools, no Docker Compose module in the jar (the plugin leaves them out anyway).

2. Configuration. Typed @ConfigurationProperties records, validated, with no default for anything that differs per environment (database URL, gateway URL) so a mistyped variable stops the start (precedence). Secrets as a mounted config tree, imported with spring.config.import. Profiles only for kind of environment; feature switches as properties.

3. Data. Flyway forward-only migrations, ddl-auto=none, expand and contract for compatible deploys. A connection pool sized on purpose (HikariCP), open-in-view=false. @Transactional on service methods, short, no remote calls inside.

4. Cross-cutting annotations, each with its guard. @Cacheable on MenuService.price with explicit key, Caffeine expireAfterWrite, sync = true, evict on update. @Async only with a named bounded executor, a TaskDecorator for MDC and security context, an exception handler, and a durable queue for anything that must not be lost.

@Retryable(includes = IOException.class, ...) only on idempotent calls or with an idempotency key, with a timeout first. @CircuitBreaker with a tuned open wait and a fallback that queues. @ConcurrencyLimit on slow endpoints. @PreAuthorize with @EnableMethodSecurity and tests as the wrong user. @Validated on services. @TransactionalEventListener for emails, and an outbox for must-send messages. @Scheduled with fixedDelay, a scheduler pool of 2 or more, and ShedLock for multi-pod jobs.

5. Runtime settings. spring.threads.virtual.enabled=true for blocking I/O, with limits. server.shutdown=graceful and a shutdown phase timeout shorter than the pod's grace period. Timeouts on every HTTP client (spring.http.clients.*). Health probes on (management.endpoint.health.probes.enabled=true), the management port separate and protected, exposure limited to health,info,metrics,prometheus,loggers.

6. Observability. Structured JSON logs (logging.structured.format.console=ecs), trace ids in the MDC, @Observed where useful (property enabled), cache and breaker metrics, the loggers endpoint for live level changes.

7. Delivery. A layered image from the jar, a non-root user, memory settings (-XX:MaxRAMPercentage), CI that runs the proxy tests and the module-boundary test (Spring Modulith verify()), and a runbook.

What I leave out on purpose: Eureka and Config Server on Kubernetes, RestTemplate, global lazy initialisation in production, ddl-auto=update, the allow-circular-references flag, and any @Async or @Retryable without the guard listed above.

Picture it

The setup: The drill's last demo is a small web service that starts with the production-style settings of point 5 and 6: virtual threads, graceful shutdown, health probes, ECS logs. It is started, called once, probed and stopped. No database was attached to this particular demo; the data layer is shown as configuration.

application.properties · Boot 4.2 (production-style excerpt)runs offline
spring.application.name=quickbite-orders
spring.threads.virtual.enabled=true
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=20s
spring.jpa.open-in-view=false
spring.jpa.hibernate.ddl-auto=none
spring.http.clients.connect-timeout=500ms
spring.http.clients.read-timeout=2s
logging.structured.format.console=ecs
management.server.port=9090
management.endpoint.health.probes.enabled=true
management.endpoints.web.exposure.include=health,info,metrics,prometheus,loggers
management.observations.annotations.enabled=true
spring.config.import=optional:configtree:/etc/secrets/

Make the invisible visible: Start the demo with the runtime settings, call it, read the readiness probe and stop it with SIGTERM.

run --demo=svc · Boot 4.2 (code/e22-spring-in-depth/G/, trimmed)runs offline
INFO 1807320 [main] o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 18391 (http) with context path '/'
INFO 1807320 [main] com.quickbite.svc.SvcApp                 : Started SvcApp in 4.016 seconds (process running for 4.49)
INFO 1807320 [ionShutdownHook] o.s.boot.tomcat.GracefulShutdown         : Commencing graceful shutdown. Waiting for active requests to complete
INFO 1807320 [tomcat-shutdown] o.s.boot.tomcat.GracefulShutdown         : Graceful shutdown complete

$ curl -s .../actuator/health/readiness
{"status":"UP"}

What you see: The service starts in about 4 seconds, Tomcat accepts requests, the readiness probe answers UP, and a SIGTERM produces "Commencing graceful shutdown. Waiting for active requests to complete" followed by "Graceful shutdown complete". That is what lets a rolling deploy finish in-flight requests.

Question production asksAnswer in the serviceSection
Can it fail safely?Timeouts, bounded retries with keys, breaker with fallback06
Is it correct under load?Cache with sync and TTL, bounded async, concurrency limit04, 05
Does it run once across pods?ShedLock, outbox07
Can I change and see it?Config precedence, loggers endpoint, structured logs and trace ids08, 09
Can I deploy it safely?Flyway forward-only, graceful shutdown, probes, canary09, 11
Is the structure protected?Modulith verify(), proxy tests, ArchUnit03, 10

Why: Each setting on the board is the answer to one failure story from this chapter. Naming the story is what turns a list into a design.

Defaults everywhere

Starts, but nothing is decided.

application.propertiesruns offline
# nothing set:
# no timeouts, one scheduler
# thread, unbounded async queue,
# plain text logs, no probes

Decided for production

Each setting answers a known failure.

application.propertiesruns offline
server.shutdown=graceful
spring.threads.virtual.enabled=true
spring.http.clients.read-timeout=2s
logging.structured.format.console=ecs
management.endpoint.health.probes
  .enabled=true

The shift: Production-ready means every default was either accepted on purpose or replaced.

Land it I walk from build and config through data, annotations with their guards, runtime, observability and delivery, naming the failure each choice prevents.

Likely follow-ups
"What is the first thing you would measure after the first production deploy?"

Start-up and steady-state behaviour of the settings above: time to readiness (is it under the probe's failureThreshold times its period), memory use compared with the container limit, the pool sizes in use (hikaricp.connections.active, executor.active), error rate and latency by endpoint, and the first week of logs by level.

Then the guards I added: the breaker state, cache hit ratio (cache.gets with result tags), retry counts and the rejected-task count of the async executor. A guard that never fires may be fine or may be mis-configured; one that fires constantly is a finding.

Compare with the staging numbers, and write the differences into the runbook as expected values, so an alert has a baseline.

"Which of these choices would you drop first for a small team and a small service?"

For a service with one pod and low traffic: ShedLock (no second pod, so no duplicate runs), Resilience4j (a timeout and a simple retry may do), Modulith (one module), the OpenTelemetry starter if the platform already collects request ids, and virtual threads (the default pool is enough).

I would never drop: timeouts, typed validated configuration, Flyway, graceful shutdown with probes, structured logs, tests of the proxy-dependent annotations, and @PreAuthorize tests. They are cheap and they cover the failures that cost money or customers.

Add the heavier pieces when the failure story appears: a second pod brings ShedLock, a flaky dependency brings the breaker, a second team brings Modulith.

"How would you explain this design to a new colleague in five minutes?"

I would draw the request path through the proxy (retry, cache, transaction, your aspects, method) and tell the three stories behind the annotations: the cache that never hit because of self-invocation, the email that was lost because async work is not durable, and the double charge from a retry without a key. Then I would show the config ladder, because it is what they will meet on day one when something is not the value they expect.

After that, one hands-on exercise: print the advisor chain of a bean, change a log level through the endpoint, and find the source of one property with /actuator/env. Seeing the tools work makes the rest of the page believable.

I would end with where to look next: the idiom table in the summary of this chapter, and the cheat sheet of annotations and their classic traps.

"What would change if QuickBite moved to many small services instead?"

The per-service design stays; the estate-level concerns grow. Discovery and load balancing come from Kubernetes Services; configuration from ConfigMaps and Secrets; consistent timeouts, retries and breakers get a shared platform library or a mesh for the transport part. Messaging and idempotency become central: every cross-service effect goes through an outbox and an idempotent consumer. Contracts need versioning (Q95) and consumer-driven tests. Observability needs trace propagation everywhere (Q76) and a log platform that joins by trace id.

I would also make module boundaries explicit before splitting (Modulith verify()), since the cleanest split follows an already clean module. And I would not split until a module has a different scaling, release or ownership need.

15 · RecapWhat You Can Do Now

  • You can explain that @Cacheable, @Async, @Retryable, @PreAuthorize and @Transactional are advice on one proxy, and name the three ways a call skips it: a same-class call, a private or final method, and an object made with new
  • You can draw the interceptor onion (retry, cache, transaction, your aspect, the method) and say what it means for a cache hit, a retried call and a timing aspect, and print the real advisor chain of a bean to prove it
  • You can build caching correctly: an explicit key, a TTL in the provider, sync = true against a stampede, eviction on write, and a test that proves the method is really cached
  • You can list what an @Async call silently loses (the thread's security context and MDC, the exception, the transaction, and the work itself on a deploy) and fix each with a named bounded executor, a TaskDecorator, an exception handler and a durable queue
  • You can design resilience for a flaky dependency in layers: a timeout, an idempotency key, bounded retries with backoff and jitter, a circuit breaker tuned in seconds, and a fallback that never pretends to succeed
  • You can say what fixedRate, fixedDelay and cron measure from, why two jobs block each other, how ShedLock gives one run across pods, and why an email belongs in an AFTER_COMMIT listener
  • You can find which property source won, write a starter that backs off, order the bean lifecycle callbacks, and break a dependency cycle by design instead of by flag
  • You can change a log level live, join log lines by trace id, read a Flyway checksum error and fix it with a new migration, and choose between Docker Compose support and Testcontainers
  • You can name what Boot 4.0, 4.1 and 4.2 changed (modular starters, Jackson 3, API versioning, RestTemplate deprecation) and plan a 3.5 to 4.2 migration in waves with a pilot and canaries
🧠 Flex your memory

Close the page and draw the interceptor onion from memory: retry, cache, transaction, your aspect, the target method. Then say, for each of these three calls, which layers run: a cache hit, a cache miss that fails twice and then succeeds, and a call from another method of the same class.

Then list the three ways an @Async call silently loses work, and name the fix for each. When that feels easy, go back to E4's data section for the self-invocation fixes of @Transactional, and try the interview round again with the answers collapsed.

16 · SummaryAll 30 Idioms on One Page

Every idiom in this chapter, each with the problem it solves and the solution in one line. Click an idiom name to jump to its full breakdown. The annotation cheat sheet follows.

02 · Spring AOP from zero

3 idioms.
IdiomProblemSolution
Call proceed() exactly once in @AroundAn around advice that forgets to return pjp.proceed() makes the method return null, and one that swallows the exception makes callers see success.Return the result of proceed() once, let exceptions pass (or rethrow after logging), and time or log around it.
Annotation-driven pointcutA pointcut written with package names breaks when classes move and advises more than you meant.Define your own annotation (@Audited) and select it with @annotation(...), so the advice follows the marker.
Call through another beanA method that calls another annotated method of the same class skips the proxy, so cache, async, security and transaction are ignored.Move the callee to another bean (or, as a last resort, use AopContext.currentProxy()).

03 · The interceptor chain

2 idioms.
IdiomProblemSolution
Retry outside the transactionRetrying inside one transaction reuses a transaction that is already marked rollback-only.Use Framework 7 @Retryable, which always wraps the transaction and the cache, so each attempt gets a fresh transaction.
Print the advisor chainNobody can say which annotations really apply to a bean or in what order.Cast the bean to Advised and print getAdvisors() at start-up or in a test.

04 · Caching with @Cacheable

4 idioms.
IdiomProblemSolution
Explicit cache keysA mutable object without equals/hashCode as the default key never hits, or hits the wrong entry.Write the key with SpEL from stable values (#item + ':' + #city) or a KeyGenerator.
Cache with sync = trueMany threads miss the same key at once and all hit the database (a stampede).Set sync = true so one thread loads the value and the others wait for it.
TTL lives in the provider@Cacheable has no expiry, so values go stale and memory grows.Set size and TTL in Caffeine (spring.cache.caffeine.spec) or Redis (spring.cache.redis.time-to-live).
Evict on writeA price update leaves the old value in the cache.Put @CacheEvict or @CachePut on the method that writes, with the same key.

05 · @Async

4 idioms.
IdiomProblemSolution
Named, bounded executorsOne shared default pool lets a slow workload starve the others, and its queue is unbounded.Give each workload an executor bean with a bounded queue and a rejection policy, and name it in @Async("mail").
Async exception handlerAn exception in a void @Async method is only logged and nobody is told.Register an AsyncUncaughtExceptionHandler through AsyncConfigurer (or return CompletableFuture).
TaskDecorator for contextThe worker thread has no security context and no MDC, so audit shows "anonymous".Copy the MDC and security context with a TaskDecorator or a delegating executor.
Async is not durableQueued in-memory work is lost on a crash or deploy.Send must-happen work to a durable queue or an outbox, and keep @Async for optional work.

06 · Retry, concurrency limits and circuit breakers

3 idioms.
IdiomProblemSolution
Retry only idempotent callsA retried non-idempotent call, such as a charge, runs twice.Retry only safe operations, or send an idempotency key so the server returns the first result.
Circuit breaker with a fallbackA failing dependency ties up every thread on timeouts.Wrap the call in a breaker with a tuned open wait and a fallback that queues or serves a cached value.
Concurrency limitToo many callers reach a slow resource at once.Use @ConcurrencyLimit(n) so at most n calls are in flight.

07 · Scheduling, events, security and validation

4 idioms.
IdiomProblemSolution
fixedDelay for pollingfixedRate jobs that overrun run back to back, or overlap on virtual threads.Use fixedDelay so every run is followed by a rest and runs never overlap or pile up.
ShedLock for one run across podsA scheduled job runs once per pod.Add @SchedulerLock with a shared lock table and lockAtMostFor above the longest run.
AFTER_COMMIT event listenerA side effect sent inside the transaction escapes a rollback.Publish an event and handle it with @TransactionalEventListener at AFTER_COMMIT.
@Validated serviceConstraints on service parameters are ignored when the caller is not a controller.Put @Validated on the service class so the proxy checks every outside call.

08 · Profiles, property precedence, starters, lifecycle and cycles

3 idioms.
IdiomProblemSolution
Know the property ladderNobody can say which property source wins, so a typo lets a weaker default win.Remember the order, print sources with /actuator/env, and make important settings required and validated.
Back-off starterA shared starter collides with the application's own bean.Use @AutoConfiguration, conditions, @ConditionalOnMissingBean and the .imports file.
Break the cycle by designConstructor cycles stop the start-up, and flags only hide them.Extract the shared part or publish an event; use @Lazy or setter injection only as a debt.

09 · Logging, database migrations and developer experience

3 idioms.
IdiomProblemSolution
Structured JSON logsPlain text logs cannot be joined by request across pods.Set logging.structured.format.console=ecs and put request fields in the MDC.
Change log levels liveYou need DEBUG for one package now, without a redeploy.Use the protected loggers endpoint, then reset the level to null.
Forward-only migrationsEditing an applied migration breaks the checksum on the next deploy.Never edit applied files; add a new version, and repair only for tooling accidents.

10 · Web extras, messaging, batch and the Spring ecosystem

2 idioms.
IdiomProblemSolution
SseEmitter for one-way pushPolling every second wastes most requests.Return an SseEmitter with a timeout and a heartbeat comment.
HTTP interface clientHand-written RestTemplate code repeats URLs and is deprecated.Declare an @HttpExchange interface on RestClient and set timeouts in configuration.

11 · What changed in Spring Boot 4.0, 4.1 and 4.2

2 idioms.
IdiomProblemSolution
Properties migrator during upgradesRenamed or removed properties are silently ignored after an upgrade.Add spring-boot-properties-migrator temporarily, read its warnings, then remove it.
Version attribute for API versionsA breaking change forces every client to move at once.Use version = "2" on mappings with a resolver in spring.mvc.apiversion.*.

Annotation cheat sheet

Each row says how to switch the annotation on, what it does, the trap that surprises people and where it is taught. Every annotation except the last is advice on a proxy, so the self-invocation trap applies to all of them.

22 annotations.
AnnotationEnable withWhat it doesClassic trapSection
@Aspect / @Aroundspring-boot-starter-aspectjRuns your advice around chosen methodsForgetting to return proceed(); self-invocation02
@OrderOn the aspect classSets the order of aspects (lower runs first)Does not reorder Spring's own cache, transaction or retry advisors03
@Cacheable@EnableCaching and a providerReturns a stored value instead of calling the methodDefault key, no TTL, stampede, same-class call04
@CachePut@EnableCachingAlways runs the method and stores the resultUsing a different key than the read04
@CacheEvict@EnableCachingRemoves one or all entriesEvicting before a failed write; evicting only on one pod04
@Async@EnableAsyncRuns the method on an executor threadLost context, lost exception, lost work on deploy, same-class call05
@Retryable (Framework 7)@EnableResilientMethodsRetries a failing method with backoffNon-idempotent calls; maxRetries counts retries, not attempts06
@ConcurrencyLimit@EnableResilientMethodsCaps concurrent calls to a methodWaiting callers still hold threads06
@CircuitBreaker (Resilience4j)resilience4j-spring-boot4Stops calls to a failing dependency; calls a fallbackOpen wait too long; breaker never sees failures a fallback swallows06
@Scheduled@EnableSchedulingCalls a method on a timerOne scheduler thread; runs on every pod07
@SchedulerLock@EnableSchedulerLock and a lock providerLets one pod run each ticklockAtMostFor shorter than the job07
@EventListenerNothing (built in)Calls a method when an event is publishedRuns inside the publisher's transaction, so a rollback does not unsend its work07
@TransactionalEventListenerNothing (built in)Calls a method at a transaction phaseSilent when there is no transaction; writes need REQUIRES_NEW07
@PreAuthorize@EnableMethodSecurityChecks a SpEL rule before the callNot enabled; hasRole prefix; same-class call07
@ValidatedValidation starterChecks constraints on method argumentsIgnored without the class annotation; private and final methods07
@Observedmanagement.observations.annotations.enabled=trueMakes a metric and a span for a methodRecords nothing until the property is set07
@TimedA TimedAspect beanRecords a timer for a methodSilent without the aspect bean07
@LazyNothing (built in)Delays creating a bean, or injects a lazy proxyOn an injection point alone the bean is still created at start-up07
@Profilespring.profiles.activeCreates a bean only in some environmentsUsing it for a single feature flag08
@ConditionalOnPropertyBoot auto-configuration supportCreates a bean when a property has a valueEvaluated once at start-up; a typo reads as "off"08
@ConfigurationProperties@EnableConfigurationProperties or scanningBinds a property group to a typed objectNo validation unless @Validated; no live refresh08
@Transactional@EnableTransactionManagement (Boot does it)Wraps the method in a transactionSame-class call; checked exceptions do not roll back; see E4E4 data