Spring Boot — Primer + 150-Question Drill
"Every Java shop runs on Spring Boot. Almost nobody on the team can say what happens between main() and the first request. The senior round asks exactly that."
01 · Why this primer existsYou Ship Spring Boot Daily — Nobody Ever Showed You the Machine
Spring Boot is a container that builds your objects for you, plus a large set of recipes that configure themselves when the conditions are right. Almost every production surprise comes from a recipe you did not know had applied, or a proxy you did not know was there.
You have typed @SpringBootApplication, @RestController, and @Transactional more times than you can count. You know what they do.
The senior interview asks what they are: which object actually calls your controller method, why a @Transactional method called from the same class silently runs without a transaction, how Boot decided to create a connection pool you never declared, and what, in order, you would check when a service that used to start in 8 seconds now takes 90.
None of these are trick questions.
They test whether you understand the framework that owns your process, and they are all answerable from a handful of mechanisms this primer teaches in plain words: the bean container, the proxy, the auto-configuration report, the servlet thread pool, and the connection pool.
The stakes are concrete. A wrong pool size is the difference between a service that survives a traffic spike and one that pages you at 3 a.m. with "HikariPool-1 – Connection is not available, request timed out after 30000ms".
A missing @Transactional proxy is a data corruption bug that passes every unit test. An eager @PostConstruct that makes a network call is a 90-second startup that fails every Kubernetes readiness probe.
Interviewers at the companies you are targeting have all been burned by these, and they want to hear that you have been too, and that you know why.
The page has two halves.
- The primer (sections 02–06) explains how Boot works underneath.
- The inversion-of-control container and auto-configuration.
- The web request path.
- Data access and transaction proxies.
- Configuration, testing, security and observability.
- Production behaviour: startup, memory, graceful shutdown, resilience, and messaging.
- The drill (sections 07–10) is 150 senior-level questions in three kinds.
- Knowledge questions that ask "why".
- Production scenarios you answer in diagnosis order.
- Design prompts where you state assumptions, propose, and defend.
Say your answer aloud first, then reveal. If your answer was shorter than the strong answer, that gap is your study list.
Versions, as of August 2026: Spring Boot 4.0 shipped in November 2025 on Spring Framework 7.0, and the 4.1 line is the current stable one.
Spring Boot 3.5 (on Spring Framework 6.2) reached open-source end of life on 30 June 2026; its final open-source patch was 3.5.16, and it lives on only under commercial support.
Everything on this page is written for Boot 3.5 and 4.x, which means Java 17 or newer as the floor, Java 21 or 25 in practice, and the jakarta.* namespaces, never javax.*. Where 3.x and 4.x differ, the page says so.
Hibernate and JPA internals get only a light touch here, because they have their own page in Chapter E5; the database engine underneath is Chapter E8; the Java language and JVM drill is Chapter E3.
02 · The primerWhat Boot Actually Does: The Container, Beans & Auto-Configuration
The container is a registry that builds every object your service needs, in dependency order, before the first request arrives. Auto-configuration is a set of recipes that only apply when their conditions hold — which is why the same code behaves differently when a dependency appears.
Start with a number. A typical Boot service with a web starter, JPA, security, and Actuator holds somewhere between 400 and 900 beans when it starts. A bean is simply an object whose creation and wiring the framework performs for you, instead of you calling new. You wrote perhaps 40 of those beans. The framework created the other several hundred, and it decided to create them by looking at what was on your classpath. Understanding that decision process is most of understanding Boot.
Bridge: you already know dependency injection, you just did it by hand
Dependency injection is wiring objects together, and you have already done it by hand.
Every non-trivial program has a wiring problem. OrderService needs a PaymentClient, which needs an HttpClient, which needs a connection pool and a timeout setting.
Without a framework, you write a main() that builds these bottom-up and passes each into the next constructor.
That approach is correct and honest. It stops scaling at about fifty objects, when nobody can change a constructor without editing the wiring file.
Inversion of control (IoC) is the name for handing that wiring job to a container. You declare what each class needs, and the container figures out the order and builds everything.
Dependency injection (DI) is the mechanism the container uses to hand each object its dependencies.
In modern Spring that means constructor injection almost exclusively: a single constructor with the dependencies as parameters. No @Autowired is needed, because Spring assumes the sole constructor is the one to use.
The container, in plain words
The container is a Java object called the ApplicationContext. It is a registry that works in two phases: first it collects recipes, then it builds objects from them.
Step-by-step breakdown
- Definition phase: collect the recipes. A recipe is a bean definition. It says, for example, "there should be a bean named
orderServiceof classOrderService, scope singleton, built by calling this constructor". Recipes come from three sources.- Component scanning: walks your packages for classes annotated
@Component(or@Service,@Repository,@RestController). - @Configuration classes: each
@Beanmethod is a recipe, and the method body is the instructions. - Auto-configuration: recipes shipped inside Boot's jars, filtered by conditions (covered next).
- Component scanning: walks your packages for classes annotated
- Instantiation phase: build each singleton in dependency order. For every bean the container walks a fixed lifecycle.
- Constructor: called with the dependencies already resolved.
- Field and setter injection: applied after construction.
- Aware callbacks: hand the bean things like its own name or the context.
- BeanPostProcessor "before initialisation": every registered post-processor runs.
@PostConstruct: your own start-up hook.- BeanPostProcessor "after initialisation": a post-processor may swap your object for a proxy here.
- Register: the finished object goes into the singleton map.
@Service
class OrderService {
private final PaymentClient payments;
OrderService(PaymentClient payments) { // 1. constructor, dependency resolved
this.payments = payments;
}
@PostConstruct
void warmUp() { // 2. runs before the proxy swap
// ❌ TRAP: a network call here delays startup and fails readiness probes.
}
@Transactional
public void place(String sku) { /* ... */ } // 3. post-processor wraps this bean
}
// Result: the object stored under "orderService" is a generated subclass that wraps
// the OrderService built above. Callers get the wrapper, not your instance.
Make the invisible visible: what the registry holds under the name orderService, before and after the post-processor step.
# illustrative output
# after @PostConstruct, before the post-processor step
orderService -> OrderService@1a2b3c
# after the post-processor step (what everyone else gets injected)
orderService -> OrderService$$SpringCGLIB$$0@7c9d4e (a subclass; the real OrderService@1a2b3c sits inside it)
What you see when the @PostConstruct trap fires, a network call that takes 90 seconds:
# illustrative output
INFO Starting DemoApplication ...
(90 seconds of silence: warmUp() is waiting on the network)
INFO Started DemoApplication in 90.4 seconds
# Kubernetes: the readiness probe fails until startup finishes
Why: singletons are built one after another at startup, so one slow @PostConstruct delays the whole application. The fix: do the call lazily on first use, or in an ApplicationReadyEvent listener, so startup does not wait for it. What you see now: Started DemoApplication in 8.1 seconds (illustrative).
That last point is the whole story of the proxy topic later in this section. The object registered under orderService may not be an OrderService at all; it may be a generated subclass that wraps one.
- Interview takeaway: "The container first collects bean definitions, then builds singletons in dependency order. Post-processors run after initialisation, and that is where a proxy replaces your object."
Auto-configuration: recipes that only apply when conditions hold
This is the piece that makes Boot feel magical, and the one interviews probe hardest. Boot ships hundreds of @Configuration classes called auto-configurations, each guarded by conditions. The design philosophy fits in one sentence: Boot supplies a sensible default, and backs off the moment you supply your own.
DataSourceAutoConfiguration says, roughly: "if the class javax.sql.DataSource is on the classpath, and the user has not declared their own DataSource bean, then create a HikariCP pool from the spring.datasource.* properties".
The guards are annotations:
@ConditionalOnClass: a class is loadable.@ConditionalOnMissingBean: the user did not supply one.@ConditionalOnProperty: a property has a value.@ConditionalOnWebApplication, and a few more.
@AutoConfiguration
@ConditionalOnClass(DataSource.class) // guard 1: the class is on the classpath
class MyPoolAutoConfiguration {
@Bean
@ConditionalOnMissingBean(DataSource.class) // guard 2: back off if the user has one
DataSource dataSource() { return /* default Hikari pool */ null; }
}
// In your own application:
@Configuration
class MyConfig {
@Bean
DataSource dataSource() { return /* your pool */ null; } // ✅ yours wins
}
// Result: with MyConfig present, the auto-configured dataSource() is skipped.
// Remove MyConfig and the default pool appears again.
What you see: the same decision in the condition evaluation report, before and after you define your own bean.
# illustrative output
# WITHOUT MyConfig
Positive matches:
DataSourceAutoConfiguration matched:
- @ConditionalOnClass found required classes 'javax.sql.DataSource' ...
- @ConditionalOnMissingBean ... did not find any beans <- Boot builds the pool
# WITH MyConfig
Negative matches:
DataSourceAutoConfiguration ... Did not match:
- @ConditionalOnMissingBean ... found bean 'dataSource' <- Boot backs off
How Boot finds auto-configurations
Boot does not scan, because scanning every jar would be slow. It follows this path.
- Each jar lists its classes: in a plain text file,
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, one fully-qualified class name per line. Boot 2.7 introduced that file and Boot 3.0 removed the older mechanism, a key inMETA-INF/spring.factories, for auto-configurations. (spring.factoriesstill exists for other extension points, such asEnvironmentPostProcessor.) - Read every file: the
@EnableAutoConfigurationhalf of@SpringBootApplicationreads every such file on the classpath. - Sort: classes are ordered by their declared
@AutoConfiguration(before=…, after=…). - Evaluate conditions: classes whose conditions fail are dropped.
- Import the survivors: they become ordinary configuration classes.
A starter, such as spring-boot-starter-data-jpa, is nothing more than an empty jar whose only job is to pull in the right dependencies so that the right @ConditionalOnClass guards become true.
Boot 4 also split the old monolithic spring-boot-autoconfigure jar into per-technology modules, so a Boot 4 application only carries the auto-configuration code for what it actually uses; the mechanism is unchanged.
The ordering rule that makes back-off work
Your own @Configuration classes are always processed before auto-configurations. That is what makes @ConditionalOnMissingBean reliable: when the auto-configuration asks "is there already a DataSource?", your answer has already been registered.
If you write your own auto-configuration in a shared library, register it via the imports file and not through component scanning.
- Works: imports file. It runs after the application's configuration, so the consumer can override it.
- Fails: component scanning. Scanned configuration runs first and can never yield to the consuming application.
- Interview takeaway: "Boot backs off because your configuration is registered before auto-configuration runs, so
@ConditionalOnMissingBeanalready sees your bean."
See it: the condition evaluation report
Step-by-step: what application.yml and the debug run do, in plain English
debug: truetells Boot to print the condition evaluation report at startup: for every auto-configuration, which conditions matched and which did not.spring.main.lazy-initialization: falseis the default, spelled out so you can flip it later when experimenting with startup time; lazy mode builds beans on first use instead of at startup.spring.datasource.urlpoints at an in-memory H2 database, so the example runs offline; Boot infers the driver class from the URL.management.endpoints.web.exposure.include: conditions,beans,envexposes three Actuator endpoints over HTTP;/actuator/conditionsis the same report as JSON, available while the service is running.- The shell command runs the packaged jar; the pipe keeps only the lines for the two auto-configurations we care about, so the output stays readable.
# application.yml — Boot 3.5 / 4.x
debug: true
spring:
main:
lazy-initialization: false
datasource:
url: jdbc:h2:mem:demo
username: sa
password: ""
management:
endpoints:
web:
exposure:
include: conditions,beans,env
# run.sh
# ./mvnw -q package -DskipTests
# java -jar target/demo-0.0.1-SNAPSHOT.jar 2>&1 | grep -E 'DataSourceAutoConfiguration|JacksonAutoConfiguration'
Read the output. The report has three headings. Under Positive matches you will see DataSourceAutoConfiguration matched: @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType', followed by a line saying @ConditionalOnMissingBean (types: javax.sql.DataSource …) did not find any beans. That second line is Boot telling you it created the pool because you did not. Under Negative matches you will see entries like MongoAutoConfiguration: Did not match: @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient', which is Boot declining a recipe because the jar is absent. Under Exclusions you see anything you turned off explicitly with @SpringBootApplication(exclude = …) or spring.autoconfigure.exclude. When a bean "mysteriously" exists, or mysteriously does not, this report is the first thing to read, and saying so in an interview is worth more than any amount of theory.
Scopes, laziness, and the two kinds of proxy
A bean's scope says how many instances exist and how long each one lives. Almost every bean is a singleton: one instance per container, shared by everyone, built at startup. Setting spring.main.lazy-initialization=true delays that build until the bean is first used.
- singleton (default): one shared instance per container.
- prototype: a new instance on each injection or lookup.
- request and session: one instance per HTTP request or per user session.
The trap: a short-lived bean inside a singleton
A singleton is built once, so its constructor parameters are resolved once. If one of them is request-scoped, the singleton would keep that single instance forever. Spring solves this with a scoped proxy: a stand-in object that looks up the real current instance on every method call.
// ❌ TRAP: without proxyMode, injecting this into a singleton fails at startup.
// No request is active while the singleton is being built.
// ✅ FIX: proxyMode makes Spring inject a proxy instead of a real instance.
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
class RequestContext {
String userId;
}
@Service
class AuditService { // singleton, built once
private final RequestContext ctx; // this is a proxy, not a RequestContext
AuditService(RequestContext ctx) { this.ctx = ctx; }
void log(String action) {
// The proxy finds the RequestContext of the current request here.
System.out.println(ctx.userId + " did " + action);
}
}
// Result: every call to log() sees the userId of the request that is running now.
What you see without the proxy: the application does not start.
# illustrative output
BeanCreationException: Error creating bean with name 'scopedTarget.requestContext':
Scope 'request' is not active for the current thread; consider defining a scoped
proxy for this bean if you intend to refer to it from a singleton
Make the invisible visible: what AuditService.ctx points at, and what happens on each call.
AuditService.ctx -> RequestContext$$SpringCGLIB$$0 (a stand-in; it holds no userId itself)
request 1, thread http-nio-8080-exec-1:
log("export") ──► ctx.userId ──► stand-in asks the container: "current request?"
└─► RequestContext@aa11 (userId=alice)
request 2, thread http-nio-8080-exec-2:
log("export") ──► ctx.userId ──► stand-in asks the container: "current request?"
└─► RequestContext@bb22 (userId=bob)
What you see now:
# illustrative output
alice did export
bob did export
- Interview takeaway: "A singleton cannot hold a request-scoped bean directly, because it is built once. A scoped proxy looks up the current instance on every call."
ScopedProxyMode.TARGET_CLASS means the stand-in is a CGLIB proxy. That brings us to the two proxy technologies Spring uses everywhere: for scoped beans, for @Transactional, and for @Configuration classes.
One shared setup for both proxy kinds
Both scenarios below use the same two types. Only the proxy technology changes.
interface OrderService {
void placeOrder();
}
@Service
class OrderServiceImpl implements OrderService {
@Transactional
public void placeOrder() { /* needs a transaction */ }
// Not on the interface. final.
public final void validateOrder() { /* ... */ }
}
@RestController
class CheckoutController {
private final OrderService orders; // ✅ or OrderServiceImpl? That is the question.
CheckoutController(OrderService orders) { this.orders = orders; }
}
Make the invisible visible: the two classes Spring can generate for this bean, written out as simplified pseudo-Java.
// Scenario A: JDK dynamic proxy. A sibling of OrderServiceImpl, not a subclass.
final class $Proxy57 implements OrderService {
private final OrderServiceImpl target;
public void placeOrder() {
txManager.begin();
try { target.placeOrder(); txManager.commit(); }
catch (RuntimeException e) { txManager.rollback(); throw e; }
}
// no validateOrder(): it is not on the interface
}
// Scenario B: CGLIB proxy. A subclass of OrderServiceImpl.
class OrderServiceImpl$$SpringCGLIB$$0 extends OrderServiceImpl {
private OrderServiceImpl target;
@Override public void placeOrder() { /* same begin / call target / commit */ }
// validateOrder() is final, so there is no override: the inherited code runs, with no advice
}
Scenario A: JDK dynamic proxy (spring.aop.proxy-target-class=false)
A JDK dynamic proxy is generated by the JDK at runtime. It can only implement interfaces, so it works when the bean is injected by its interface type.
How it works
- Decide: in the "after initialisation" step, a post-processor sees that the bean needs advice (for example it has
@Transactional). - Generate: the JDK builds a class that implements the same interfaces as your bean. It is a sibling of your class, not a subclass.
- Intercept: each call on the proxy runs the advice (start the transaction), then calls your real object, then runs the advice again (commit or roll back).
- Register: the proxy is stored under the bean name. Your real object is hidden inside it.
The trap: the proxy is not an OrderServiceImpl. Anything that asks for the concrete class cannot receive it.
// Runtime class of the bean: jdk.proxy2.$Proxy57, which implements OrderService.
@RestController
class CheckoutController {
// ✅ Works: the proxy implements OrderService.
CheckoutController(OrderService orders) { ... }
// ❌ TRAP: the proxy is not an OrderServiceImpl.
// CheckoutController(OrderServiceImpl orders) { ... }
}
// Result: placeOrder() goes through the proxy and is transactional.
// validateOrder() is not on the interface, so it cannot be called through the proxy.
What you see if the controller asks for OrderServiceImpl under a JDK proxy:
# illustrative output (usually wrapped in a creation exception for CheckoutController)
BeanNotOfRequiredTypeException: Bean named 'orderServiceImpl' is expected to be of type
'OrderServiceImpl' but was actually of type 'jdk.proxy2.$Proxy57'
Why: the object in the registry is a $Proxy57, and a $Proxy57 is not an OrderServiceImpl. The fix: inject OrderService. What you see now: the application starts and orders.getClass() prints jdk.proxy2.$Proxy57 (illustrative).
- Works:
@Autowired OrderService s;(inject by interface). - Fails:
@Autowired OrderServiceImpl s;fails withBeanNotOfRequiredTypeException, because the bean is a proxy that does not extend that class. - Interview takeaway: "With JDK proxies the bean is an interface-only stand-in, so injection by the concrete class fails. Spring Boot avoids that by defaulting to CGLIB."
Scenario B: CGLIB proxy (Boot default)
A CGLIB proxy is a generated subclass of your concrete class. It needs no interface, and it can be injected by the concrete type.
How it works
- Decide: the same post-processor step decides the bean needs advice.
- Generate: a subclass such as
OrderServiceImpl$$SpringCGLIB$$0is created, overriding every non-final public and protected method. - Intercept: each overridden method runs the advice, then calls the same method on the real object.
- Register: the subclass instance is stored under the bean name. It passes every
instanceofcheck for your class.
The constraints: a subclass cannot override what is final, and it needs a constructor it can call.
- A
finalclass cannot be subclassed, so no proxy can be built for it. - A
finalmethod cannot be overridden, so the call skips the advice. It runs without a transaction and no error is reported.
// Runtime class of the bean: OrderServiceImpl$$SpringCGLIB$$0, which extends OrderServiceImpl
// and also implements OrderService.
@RestController
class CheckoutController {
// ✅ Works: the proxy is an OrderService...
CheckoutController(OrderService orders) { ... }
// ✅ Works: ...and also an OrderServiceImpl.
// CheckoutController(OrderServiceImpl orders) { ... }
void checkout(OrderServiceImpl orders) {
orders.placeOrder(); // ✅ intercepted: runs inside a transaction
orders.validateOrder(); // ❌ TRAP: final, so it runs without any advice
}
}
// Result: placeOrder() is transactional; validateOrder() silently is not.
// ✅ FIX: remove final from validateOrder().
The trace: imagine validateOrder() carried @Transactional too.
CheckoutController ──► proxy.placeOrder() ✓ advice runs: transaction begins
└─► target.placeOrder()
CheckoutController ──► proxy.validateOrder() ✗ not overridden: inherited code runs
(no advice, no transaction, and it runs on the proxy object, not the target)
What you see with logging.level.org.springframework.transaction.interceptor=TRACE:
# illustrative output
Getting transaction for [OrderServiceImpl.placeOrder]
Completing transaction for [OrderServiceImpl.placeOrder]
<- nothing at all for validateOrder
The same blindness appears in a same-class call. If placeOrder() calls this.validateOrder(), the call is made on the real object:
CheckoutController ──► proxy.placeOrder() ✓ advice runs
└─► target.placeOrder()
└─► this.validateOrder() ✗ direct call on the real object, proxy never sees it
The fix: move validateOrder() into another bean and inject it, so the call goes through that bean's proxy. What you see now: a second Getting transaction for [...] line appears for the call.
- Works:
@Autowired OrderService s;and@Autowired OrderServiceImpl s;. - Fails: a
final class OrderServiceImplwith@Transactionalcannot be proxied at all. Afinalmethod on a proxied class loses its annotations silently. - Interview takeaway: "CGLIB proxies are subclasses, so injection by class or interface both work. The price is that final classes cannot be proxied and final methods silently skip the advice."
| Action | JDK dynamic proxy | CGLIB proxy |
|---|---|---|
| Generated runtime class | $Proxy class implementing OrderService | OrderServiceImpl$$SpringCGLIB$$0, extending OrderServiceImpl |
Inject OrderService | Works | Works |
Inject OrderServiceImpl | Fails: BeanNotOfRequiredTypeException | Works |
Make the class final | Works (nothing is subclassed) | Fails: the proxy cannot be created |
Make placeOrder() final | Works (the interface method is intercepted) | Silently not applied: no transaction |
| Spring Boot default | No (needs spring.aop.proxy-target-class=false) | Yes (spring.aop.proxy-target-class=true) |
Why did the designers make CGLIB the Boot default?
With JDK proxies, whether your code compiles-and-starts depends on how a bean is injected. Adding @Transactional to a class could break a constructor that asked for the concrete type, far from the change. Class-based proxies remove that surprise: injection by class and by interface both work. Boot therefore sets spring.aop.proxy-target-class=true.
The practical rules:
- Never mark a Spring bean class, or its transactional methods,
final. - Expect the object you receive to be a generated subclass whose class name contains
$$SpringCGLIB$$. - Both proxy kinds only intercept calls that arrive through the proxy. A method that calls another method on
thisbypasses the advice, which is why a same-class@Transactionalcall runs without a transaction.
Before reading on: a colleague adds a @Bean public DataSource dataSource() method to a @Configuration class that also has @Bean methods for two JdbcTemplates, each of which calls dataSource() directly as a plain Java method call. How many connection pools exist at runtime, and what would the answer be if the class were annotated @Configuration(proxyBeanMethods = false)?
Reveal the answer
With a normal @Configuration, exactly one pool. Spring subclasses the configuration class with CGLIB so that every call to a @Bean method, even a direct one from a sibling method, is intercepted and routed to the container, which returns the already-registered singleton.
That interception is the entire reason @Configuration classes are proxied.
With proxyBeanMethods = false, the class is not subclassed, so the two direct calls to dataSource() each run the method body and create a fresh pool, and the container has a third one registered under the bean name: three pools, two of them invisible to Actuator.
Boot's own auto-configurations use proxyBeanMethods = false for startup speed and pass dependencies as method parameters instead of calling sibling methods, which is the pattern to copy: inject what a @Bean method needs as a parameter, and never call another @Bean method directly.
Make the invisible visible: which calls reach the container in the Brain power question above.
@Configuration (default): the class is a CGLIB subclass
jdbcA() ──► dataSource() ──► intercepted ──► container returns the registered singleton
jdbcB() ──► dataSource() ──► intercepted ──► same singleton
pools created: 1
@Configuration(proxyBeanMethods = false): plain class
container ──► dataSource() ✓ registered bean: pool 1
jdbcA() ──► dataSource() ✗ plain Java call, body runs again: pool 2
jdbcB() ──► dataSource() ✗ plain Java call, body runs again: pool 3
pools created: 3 (only pool 1 is visible in /actuator/beans)
The fix: pass the dependency as a parameter, jdbcA(DataSource ds), as in the DbConfig example later in this section. What you see now: pools created: 1 in both modes.
Actuator: the container's own instrumentation
Actuator is the starter that turns the container inside out for operators. It registers HTTP endpoints under /actuator.
| Endpoint | What it shows or does |
|---|---|
health | Up or down, with separate liveness and readiness groups for Kubernetes |
info | Application information |
metrics, prometheus | Metrics, via Micrometer |
env, configprops | Resolved properties |
beans, conditions | The container's beans and the auto-configuration report |
loggers | Change a log level at runtime, no restart |
threaddump, heapdump | Thread and memory snapshots |
By default only health is exposed over the web. Everything else must be opted in with management.endpoints.web.exposure.include.
Why did the designers make this choice? Because env and heapdump leak secrets and memory contents. A default that exposed them would put every new service one forgotten setting away from a leak.
management:
server:
port: 8081 # ✅ FIX: separate port, not routed from the internet
endpoints:
web:
exposure:
include: health,info,metrics,prometheus,loggers
# ❌ TRAP: adding heapdump or env here without authentication leaks secrets
# and memory contents.
# Result: /actuator/health and the listed endpoints answer on port 8081 only.
# Put heapdump, env and shutdown behind authentication or leave them off.
What you see: the same URLs before and after someone adds endpoints to include.
# illustrative output
# default: only health is exposed
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/actuator/env
404
$ curl localhost:8080/actuator/health
{"status":"UP"}
# after include: env,heapdump on the public port
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:8080/actuator/env
200 <- anyone who can reach the port can read it
$ curl -O localhost:8080/actuator/heapdump <- downloads a snapshot of every object in memory
The fix is the YAML above: a separate management port that is not routed from the internet. What you see now: localhost:8080/actuator/env returns 404, and /actuator/health answers on port 8081 only.
| Choose… | When… | Because… |
|---|---|---|
@Component + constructor injection | The class is yours and has one obvious way to build it | Zero ceremony, the class documents its own dependencies, tests can call the constructor directly |
@Configuration + @Bean | The class is third-party, or building it needs logic or several variants | The method body is the recipe; you can read properties, choose implementations, and name the bean |
@Configuration(proxyBeanMethods = false) | You write a library or care about startup time, and no @Bean method calls another | Skips the CGLIB subclass; pass dependencies as method parameters instead |
Auto-configuration via AutoConfiguration.imports | You ship a shared library used by many services and want consumers to be able to override | Runs after user config, so @ConditionalOnMissingBean lets the consumer win |
| Do NOT use component scanning in a library | Ever, for shared jars | Scanned beans run before auto-config, cannot be conditionally backed off, and leak into every consumer's package layout |
Row by row: the rule, the why, and an example
Rule: use @Component with constructor injection for your own classes. Why: the constructor documents the dependencies, and a test can call it directly.
@Component
class PriceCalculator {
private final TaxRates rates;
PriceCalculator(TaxRates rates) { this.rates = rates; } // no @Autowired needed
}
// In a test: new PriceCalculator(fakeRates), with no Spring at all.
Rule: use @Configuration with @Bean for third-party classes or for logic. Why: you cannot annotate a class you do not own, and the method body can read properties and choose an implementation.
@Configuration
class ClientConfig {
@Bean
RestClient paymentsClient(@Value("${payments.url}") String url) {
return RestClient.builder().baseUrl(url).build(); // third-party class, our recipe
}
}
Rule: use @Configuration(proxyBeanMethods = false) when no @Bean method calls another. Why: it skips the CGLIB subclass, which is faster to start. Pass dependencies as parameters instead.
@Configuration(proxyBeanMethods = false)
class DbConfig {
@Bean
JdbcTemplate jdbc(DataSource ds) { // ✅ dependency arrives as a parameter
return new JdbcTemplate(ds);
// ❌ TRAP: new JdbcTemplate(dataSource()) would run the method body again
// and build a second pool, because nothing intercepts the call.
}
}
Rule: ship shared-library beans as auto-configuration through AutoConfiguration.imports. Why: it runs after the application's own configuration, so @ConditionalOnMissingBean lets the consumer win.
Rule: never use component scanning in a shared jar. Why: scanned beans run before auto-configuration and cannot be conditionally backed off. They also leak into every consumer's package layout.
// File: src/main/resources/META-INF/spring/
// org.springframework.boot.autoconfigure.AutoConfiguration.imports
// Content, one class per line:
// com.acme.lib.AcmeAutoConfiguration
@AutoConfiguration
class AcmeAutoConfiguration {
@Bean
@ConditionalOnMissingBean // ✅ the consuming app can supply its own AcmeClient
AcmeClient acmeClient() { return new AcmeClient(); }
}
// ❌ TRAP: the same class as a plain @Configuration picked up by component scanning.
// It is processed with the application's own configuration, before auto-configuration,
// and cannot be backed off. Every consumer must also scan the library's package.
Quick reference — The container and auto-configuration
- ApplicationContext
- The registry. Holds bean definitions (recipes) and singletons (built instances). Everything is built in dependency order at startup, before the first request.
- Auto-configuration
- Recipes that apply only when their
@Conditionaltests pass. Found throughMETA-INF/spring/...AutoConfiguration.imports, not by scanning. - Ordering rule
- Your own
@Configurationbeans are registered before auto-configuration runs, which is why@ConditionalOnMissingBeanlets you override anything. - The debugging tool
--debug, or/actuator/conditions. Positive matches, negative matches, exclusions — this answers “why is this bean here?” faster than reading any code.- The two proxies
- JDK dynamic proxy: interfaces only. CGLIB subclass: concrete classes, and the reason
finalmethods silently lose their annotations. - Actuator
- Turns the container inside out for operators: health, metrics, env, conditions, heapdump, threaddump.
03 · The primerThe Web Layer: From Socket to Controller and Back
A request arrives on a socket, a thread is taken from a fixed pool to carry it, and one servlet routes it to your method. That pool size is a ceiling on concurrency, and it is where most capacity problems live.
Capacity in a Boot service is a chain of limits. Think of a bank: the door lets people in, the queue holds them, and only as many people are served at once as there are tellers. Each actor in the chain has one limit.
The actors and their limits
- OS accept queue: connections waiting for Tomcat to take them.
server.tomcat.accept-count, default 100. - Tomcat connections: connections Tomcat holds open at once.
server.tomcat.max-connections, default 8192. - Worker threads: threads that run your code, one per request.
server.tomcat.threads.max, default 200. Embedded Tomcat is the default server behindspring-boot-starter-web. - HikariCP pool: database connections shared by all threads.
spring.datasource.hikari.maximum-pool-size, default 10. - CPU and heap: the hardware ceiling under everything above.
The formula
Max requests per second per instance is about worker threads ÷ average response time in seconds.
- Example A, fast responses: 10 ms each. 200 ÷ 0.01 = 20,000 requests per second in theory. In practice the CPU caps it far lower, because 200 busy threads need cores.
- Example B, slow downstream: 2 s each. 200 ÷ 2 = 100 requests per second. Request 101 in the same second finds no free thread. Tomcat still accepts the connection, and the request waits for a thread until the caller times out. Meanwhile the CPU is nearly idle, because every thread is just waiting.
- The 500 ms case: if every request takes 500 milliseconds waiting on a slow downstream call, your service tops out at 400 requests per second per instance no matter how fast your code is. Request 201 in a burst is not refused: its connection is accepted and it waits for a free thread. Refusal at the TCP level only starts when
max-connections(8192) are open and the accept queue of 100 behind them is also full.
Every latency incident in a Boot service is, at bottom, a question about who is holding those 200 threads and why. This chapter walks the path one request takes so that you can answer that.
Make the invisible visible: the pool as numbers over three moments, for one instance with threads.max=200 and accept-count=100.
# illustrative output
1 normal, 20 ms responses: workers busy 12 / 200 queue 0 / 100 client sees ~20 ms
2 slow downstream, 2 s: workers busy 200 / 200 queue 37 / 100 client sees 2 s plus the wait; CPU about 5%
3 exhausted: workers busy 200 / 200 queue 100 / 100 new connections refused or time out
What you see in a thread dump at moment 3: every worker is parked, none is working.
# illustrative output
"http-nio-8080-exec-17" WAITING java.net.SocketInputStream.socketRead0 <- waiting on the downstream
"http-nio-8080-exec-18" WAITING java.net.SocketInputStream.socketRead0
... 198 more like these
Why: a thread is held for the whole request, so slow downstream calls pin all 200. The fixes are in the scenarios below.
Bridge: a servlet container is a thread pool with a socket in front
A servlet container is a thread pool with a socket in front. You have written servlets, or at least read one.
A servlet container (Tomcat, Jetty, Undertow) accepts TCP connections and parses HTTP. It hands each request to a worker thread that calls a servlet's service() method.
Spring MVC registers exactly one servlet, the DispatcherServlet, mapped to /.
Everything you think of as "Spring web" happens inside that single servlet's handling of the request, on the Tomcat worker thread. That means controller lookup, argument binding, JSON conversion, and exception handling.
Nothing about Spring changes the threading model. It is one request, one thread, held for the full duration, unless you deliberately go asynchronous or reactive.
The request path, in plain words
Follow one POST /orders from the socket to the response.
Step-by-step breakdown
- Accept and parse (Tomcat):
- Acceptor thread: takes the connection and hands it to a poller.
- Worker thread: when bytes are ready, a thread from the pool parses the request. It carries the request until the response is written.
- Filter chain (before Spring MVC): a list of
jakarta.servlet.Filterobjects registered with the container. Each may inspect, modify, short-circuit, or pass the request along.- Who is a filter: Spring Security (one
FilterChainProxythat holds an ordered list of security filters), request logging, CORS, and compression. - What they see: raw servlet objects. They cannot tell which controller will handle the request.
- Who is a filter: Spring Security (one
- DispatcherServlet picks a handler: it asks its HandlerMappings "which handler serves POST /orders?". The annotation-based mapping returns your
@PostMappingmethod plus the ordered list of HandlerInterceptors that apply. - Interceptors (inside Spring): like a filter, but they know the target handler. They have three hooks.
preHandle: before the controller.postHandle: after the controller, before the view.afterCompletion: after everything, including exceptions.
- HandlerAdapter invokes your method: it first resolves the parameters.
@PathVariable: from the URL template.@RequestParam: from the query string.@RequestBody: the body goes through an HttpMessageConverter. Jackson handles JSON; Boot 4 moved to Jackson 3, whose packages start withtools.jacksoninstead ofcom.fasterxml.jackson.@Valid: the Jakarta Bean Validation provider (Hibernate Validator) checks the bound object before your method sees it.
- Response unwinds: your method returns an object and the same converter machinery serialises it. Then the interceptors'
afterCompletionruns, the filters unwind in reverse order, Tomcat writes the bytes, and the thread returns to the pool.
Make the invisible visible: one POST /orders, one line per hop, with the thread that runs it.
# illustrative output
[http-nio-8080-Acceptor] accept socket 10.0.0.5:51234 ──► hand to poller
[http-nio-8080-exec-3] parse HTTP request (worker thread taken from the pool)
[http-nio-8080-exec-3] Filter chain: CORS ──► Security ──► logging (raw servlet objects)
[http-nio-8080-exec-3] DispatcherServlet ──► HandlerMapping: OrderController.create
[http-nio-8080-exec-3] interceptors.preHandle
[http-nio-8080-exec-3] HandlerAdapter ──► HttpMessageConverter (JSON ──► CreateOrder) ──► @Valid
[http-nio-8080-exec-3] OrderController.create(...) (thread is held, even while waiting on I/O)
[http-nio-8080-exec-3] HttpMessageConverter (OrderView ──► JSON) ──► afterCompletion ──► filters unwind
[http-nio-8080-exec-3] write response ──► thread returns to the pool
Exceptions: where they are caught decides who can handle them
The diagram's warning-coloured path is the one interviewers care about. Where an exception is thrown decides who can handle it.
Step-by-step breakdown
- The controller throws: the DispatcherServlet catches the exception.
- Resolvers are consulted: it asks its HandlerExceptionResolvers. The one you use is
@ControllerAdvice(or@RestControllerAdvice), a class whose@ExceptionHandlermethods map exception types to responses. - The body is a ProblemDetail: since Spring 6 the recommended response body is ProblemDetail, the RFC 9457 "problem details" JSON shape with
type,title,status,detail, andinstancefields. Enable it for Spring's own exceptions withspring.mvc.problemdetails.enabled=true.
The trap: an exception thrown in a filter, most commonly a Spring Security authentication failure, never enters the DispatcherServlet. @ControllerAdvice never sees it.
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(OutOfStockException.class)
ProblemDetail outOfStock(OutOfStockException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage());
}
}
@RestController
class OrderController {
@PostMapping("/orders")
void create() {
throw new OutOfStockException("sku-1"); // ✅ inside the DispatcherServlet
}
}
// Result: 409 with a ProblemDetail body, produced by ApiErrors.
// A bad JWT is rejected in a Security filter.
// ❌ TRAP: ApiErrors is never consulted for that 401.
// ✅ FIX: configure an AuthenticationEntryPoint on the security filter chain.
The trace: the same application, two failures, two different catchers.
POST /orders (thread exec-3)
Filter chain ✓ ──► DispatcherServlet ──► OrderController.create() throws OutOfStockException
└─► HandlerExceptionResolver ──► ApiErrors.outOfStock() ✓ caught
POST /orders with a bad JWT (thread exec-4)
Filter chain: Security filter ✗ token invalid
└─► Security's AuthenticationEntryPoint ──► 401
DispatcherServlet never reached, ApiErrors never consulted
What you see: two different responses for the client.
# illustrative output
HTTP/1.1 409
Content-Type: application/problem+json
{"type":"about:blank","title":"Cannot fulfil order","status":409,"detail":"out of stock: sku-1"}
HTTP/1.1 401
(Security's default 401 response, not the ProblemDetail JSON above)
The fix: an AuthenticationEntryPoint that writes the body you want. What you see now: the 401 carries the same application/problem+json shape as the 409 (when the entry point delegates to the same advice or writes it itself).
- Works: a controller or service throws
OutOfStockException, and@ExceptionHandlermaps it. - Fails: an authentication failure in a filter is not handled by
@ControllerAdvice. - Interview takeaway: "
@ControllerAdviceonly sees exceptions thrown inside the DispatcherServlet. Filter failures, such as a bad JWT, are handled by Security'sAuthenticationEntryPoint."
| Thrown in… | Default handler | How to override |
|---|---|---|
| Controller or service | DispatcherServlet's HandlerExceptionResolvers | @RestControllerAdvice with @ExceptionHandler methods |
| Security filter (authentication) | Security's AuthenticationEntryPoint | Configure your own entry point on the security filter chain |
| Security filter (authorisation) | Security's AccessDeniedHandler | Configure your own handler on the security filter chain |
| Any other filter | The container's error page mapping to Boot's /error endpoint (BasicErrorController) | Replace or customise the error controller, or catch inside the filter |
Validation and a complete controller
Step-by-step: what OrderController.java does, in plain English
- The
CreateOrderrecord is the request body; thejakarta.validationconstraints declare thatskumust be non-blank andquantitymust be between 1 and 100. A record is used because request bodies should be immutable data. @RestControllermarks the class as a bean whose methods return response bodies rather than view names;@RequestMapping("/orders")sets the URL prefix.- The constructor takes an
OrderService; Spring injects it because it is the only constructor. No@Autowiredis needed. createis bound toPOST /orders.@Valid @RequestBodymeans: deserialise JSON into the record, then run the validator; on failure Spring throwsMethodArgumentNotValidExceptionbefore the method body runs.- The method delegates to the service and returns HTTP 201 with a
Locationheader pointing at the new resource, usingResponseEntityso the status and headers are explicit. @RestControllerAdviceonApiErrorsmakes its handlers apply to every controller. The handler for validation failures builds aProblemDetailwith status 400 and lists each failed field, so clients get a machine-readable error instead of a stack trace.- The second handler maps the domain exception
OutOfStockExceptionto HTTP 409 Conflict. The service layer throws domain exceptions and knows nothing about HTTP; the advice class does the translation in one place.
package demo.orders;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.util.List;
record CreateOrder(@NotBlank String sku, @Min(1) @Max(100) int quantity) {}
record OrderView(long id, String sku, int quantity) {}
class OutOfStockException extends RuntimeException {
OutOfStockException(String sku) { super("out of stock: " + sku); }
}
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService orders;
OrderController(OrderService orders) { this.orders = orders; }
@PostMapping
ResponseEntity<OrderView> create(@Valid @RequestBody CreateOrder body) {
OrderView created = orders.place(body.sku(), body.quantity());
return ResponseEntity.created(URI.create("/orders/" + created.id())).body(created);
}
@GetMapping("/{id}")
OrderView get(@PathVariable long id) { return orders.find(id); }
}
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
pd.setTitle("Validation failed");
List<String> fields = ex.getBindingResult().getFieldErrors().stream()
.map(f -> f.getField() + ": " + f.getDefaultMessage()).toList();
pd.setProperty("errors", fields);
return pd;
}
@ExceptionHandler(OutOfStockException.class)
ProblemDetail outOfStock(OutOfStockException ex) {
ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.CONFLICT);
pd.setTitle("Cannot fulfil order");
pd.setDetail(ex.getMessage());
return pd;
}
}
Read the output of a bad request. curl -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{"sku":"","quantity":500}' returns status 400 with Content-Type: application/problem+json and a body like {"type":"about:blank","title":"Validation failed","status":400,"errors":["sku: must not be blank","quantity: must be less than or equal to 100"]}. Two things to notice. The controller method never ran, which is what makes validation at the boundary safe: nothing downstream ever sees the bad values. And the response is structured: a client can render errors field by field, and a log pipeline can group on title. That is the difference between a validation story an interviewer nods at and one they probe.
The trace: where the request stops.
POST /orders {"sku":"","quantity":500} (thread exec-5)
Filter chain ✓ ──► DispatcherServlet ──► HandlerAdapter
bind JSON to CreateOrder ✓
@Valid ✗ 2 violations ──► MethodArgumentNotValidException
OrderController.create(...) not called
└─► ApiErrors.invalid() ──► ProblemDetail 400
HTTP/1.1 400
Content-Type: application/problem+json
{"type":"about:blank","title":"Validation failed","status":400,
"errors":["sku: must not be blank","quantity: must be less than or equal to 100"]}
WebMVC, WebFlux, or virtual threads?
The thread-per-request model breaks when requests spend most of their time waiting. Two answers exist.
WebFlux: make nothing block
WebFlux is Spring's reactive stack. A small number of event-loop threads (Netty by default) serve every request, and no thread blocks while waiting.
- Return a promise-like type: every operation returns a
Mono(zero or one value) or aFlux(many values). - Free the thread while waiting: the event-loop thread moves on to other requests and comes back when the data arrives.
The cost: your whole stack must be non-blocking, including database access (R2DBC, not JDBC). One blocking call on an event-loop thread makes things worse for everyone.
Virtual threads: keep your code, change the thread
Since Java 21, virtual threads give the same scalability benefit without changing your code. A virtual thread is a cheap thread managed by the JVM. It unmounts from its carrier operating-system thread whenever it blocks, so you can have a million of them.
spring:
threads:
virtual:
enabled: true # Boot 3.2+: Tomcat, @Async and scheduling use virtual threads
# Result: the 200-thread ceiling disappears.
# The limit becomes what you actually wait on, usually the connection pool.
# ❌ TRAP: 10,000 concurrent requests still share a 10-connection Hikari pool.
What you see now: the same three moments with virtual threads, and where the wait moves to.
# illustrative output
1 normal: requests in flight 12 Hikari active 2/10 waiting 0
2 slow HTTP downstream, 2 s: requests in flight 3,000 carrier threads mostly idle CPU low (no limit hit)
3 slow database: requests in flight 3,000 Hikari active 10/10 waiting 2,990
after 30000ms: "Connection is not available, request timed out"
What changes for I/O-bound requests:
- A request blocks on a JDBC or HTTP call.
- The blocked virtual thread releases its carrier thread, which immediately serves another request.
- Thread count stops being the limit. The connection pool becomes the limit.
What does not change: CPU-bound work. It still needs a core for the whole time it runs, so virtual threads add nothing there.
The caveats that separate a senior answer
- Only waiting work benefits: virtual threads help when threads are waiting. CPU-bound work gains nothing.
- Pinning (before JDK 24): a virtual thread that blocked inside a
synchronizedblock got pinned to its carrier and could not unmount. Older libraries with synchronised I/O could exhaust the small carrier pool. JDK 24 fixed pinning forsynchronized(JEP 491), so on Java 25 this concern is mostly historical, but you should still know it. - Thread-locals: they still work on virtual threads, but a million threads each holding a large thread-local is a memory problem. Spring's
SecurityContextHolderand MDC logging context both use thread-locals, which is fine per request but not something to cache large objects in.
| Choose… | When… | Watch out for… |
|---|---|---|
| WebMVC, platform threads (the default) | Moderate concurrency, CPU-mixed work, JDBC everywhere, team knows servlets | 200-thread ceiling; size server.tomcat.threads.max to the downstream pool, not to hope |
WebMVC + spring.threads.virtual.enabled=true (Java 21+) | High concurrency dominated by waiting on I/O, existing blocking code you do not want to rewrite | Pinning on pre-JDK-24 synchronized; connection pool becomes the real limit; do not pool virtual threads |
| WebFlux | Streaming responses, server-sent events, very high fan-out to other non-blocking services, backpressure needed end to end | One blocking call on the event loop stalls everyone; R2DBC not JDBC; harder stack traces and debugging |
| Do NOT pick WebFlux | Just because it is "faster"; when the database driver is JDBC; when the team has not used reactive types | Throughput at moderate load is the same as MVC, and the complexity cost is permanent |
Scenario 1: tune the configuration
Symptom: latency is high, CPU is low. Why: threads are blocked waiting on a downstream call or the database, not working. Example: a thread dump shows 200 threads parked in socket reads, the CPU graph is flat, and logs show HikariPool-1 - Connection is not available, request timed out after 30000ms. Fix: size threads and the pool to match what the downstream can really serve, set timeouts on downstream calls, or switch to virtual threads.
server:
tomcat:
threads:
max: 200 # worker threads (default)
accept-count: 100 # queue behind them (default)
max-connections: 8192 # open connections (default)
spring:
datasource:
hikari:
maximum-pool-size: 10 # ❌ TRAP: 200 threads sharing 10 connections just move the wait
# from the thread pool to the connection pool.
# ✅ FIX: size threads.max against the pool and the downstream, or enable virtual threads.
Scenario 2: add instances
Symptom: CPU or heap is exhausted. Why: the machine is the limit, not the thread count. Example: CPU sits at 100 percent with 200 busy threads. Fix: add instances. More threads on the same machine make it worse, because they compete for the same cores and each one needs memory for its stack.
Warning: adding instances multiplies database connections. 10 instances with a pool of 10 each is 100 connections, so check that the database allows instances × pool size.
- Interview takeaway: "Max throughput is roughly threads divided by response time. If CPU is idle, the threads are waiting, so I tune pools or use virtual threads. If CPU or heap is exhausted, I add instances and check instances times pool size against the database limit."
| Symptom | Root cause | Action |
|---|---|---|
| High latency, low CPU, all worker threads busy | Threads blocked on a slow downstream or database call | Add downstream timeouts, size threads and pool together, or enable spring.threads.virtual.enabled=true |
Connection is not available, request timed out after 30000ms | More concurrent requests than pool connections, or connections held too long | Find slow queries and long transactions first; raise maximum-pool-size only if the database can take it |
| CPU near 100 percent | CPU-bound work; more threads or virtual threads cannot help | Optimise the hot path or add instances |
| Heap or GC pressure | Memory is the limit; each extra thread also needs stack memory | Fix the memory use or add instances; do not raise threads.max |
| Database refuses connections after scale-out | Instances × pool size exceeds the database limit | Lower the pool size per instance, or raise the database limit |
| Streaming, server-sent events, huge non-blocking fan-out | Thread-per-request is the wrong model | Use WebFlux, with R2DBC rather than JDBC |
There are no dumb questions
- Filter or interceptor: which do I write for request logging with the user id?
- An interceptor, because it runs after Spring Security's filter has populated the security context, so the user id is available, and because it knows which handler method is being invoked, so you can log the controller name. Use a filter only when you need to act before Spring sees the request at all, such as adding a correlation id header, wrapping the request body so it can be read twice, or rejecting oversized payloads early.
- Why does my
@ControllerAdvicenot catch the 401 from a bad JWT? - Because the JWT is checked in a Security filter, which runs before the DispatcherServlet, and the advice lives inside the DispatcherServlet. Configure an
AuthenticationEntryPointon the security filter chain to produce the response you want; a common pattern is to have that entry point delegate to aHandlerExceptionResolverso the same advice code formats it. - Is
@Validenough, or do I also validate in the service? @Validon the controller checks the shape of the input: required fields, ranges, formats. Business rules that need data, such as "this customer's credit limit allows this order", belong in the service, because the controller cannot know them and because the service may be called from a Kafka listener or a scheduled job where no controller runs. Keep both, and keep them different.- Does Spring Boot 4 change any of this?
- The request path is the same. What changed: Jackson 3 (new
tools.jacksonpackage, some default behaviour changes such as failing on unknown properties being off and dates written as ISO strings), Tomcat 11 on the Jakarta Servlet 6.1 API, first-class API versioning with@RequestMapping(version = "1.1")and aspring.mvc.apiversion.*property family, and the JSpecify null-safety annotations across the framework so your IDE flags nullable parameters. Boot 4 also offers the more precisely namedspring-boot-starter-webmvc; the oldspring-boot-starter-webname keeps working.
Quick reference — The web layer
- The thread model
- One thread per request, from a fixed pool. Tomcat's default is 200. That number is a hard concurrency ceiling.
- The request path
- Acceptor → poller → worker thread →
DispatcherServlet→HandlerMapping→ your controller →HttpMessageConverter→ response. - Where exceptions are caught
- Inside the dispatcher,
@ControllerAdvicesees it. Outside — in a filter — it does not, and you get the container's default error page instead. - Virtual threads vs WebFlux
- Virtual threads help when threads are waiting. They do nothing for CPU-bound work, and they remove a throttle you may have been relying on.
04 · The primerData & Transactions: The Proxy You Never See
@Transactional does nothing by itself. Spring wraps your bean in a proxy,
and the proxy opens the transaction. Every surprising behaviour in this section follows from
that one fact — including why calling your own method skips it entirely.
Here is the bug that appears in more Boot codebases than any other, and that the senior round loves. A service class has a public method importAll() that loops over a file and calls its own @Transactional method saveOne(row) for each line. A row fails halfway.
@Service
public class ImportService {
// fields: RowRepository rows, AuditRepository audit (constructor injection)
public void importAll(List<String> lines) { // no @Transactional on the entry point
for (String line : lines) {
saveOne(line); // ❌ TRAP: same as this.saveOne(line), a plain Java call on the real object.
// The proxy is bypassed, so no transaction is opened.
}
}
@Transactional // never seen on the path above
public void saveOne(String line) {
rows.save(parse(line)); // statement 1: committed immediately (autocommit)
audit.save(new RowAudit(line)); // statement 2: assume this throws on row 5
}
}
// Result: rows 1-4 are saved and committed, one statement at a time.
// Row 5 has its first insert committed but no audit row (half-written). Rows 6+ never run.
// Nothing rolls back, because there never was a transaction.
Nothing rolls back. Every earlier row is committed, and the failed one is half-written. The unit tests pass, because they mock the repository. The annotation is there, the method is public, the exception is a RuntimeException.
What went wrong is that there was never a transaction, and the reason is the proxy from section 02.
What you see: the statements as they reach the database, and the tables afterwards.
# illustrative output: autocommit, so every statement commits on its own
INSERT row (line 1) COMMIT
INSERT audit (line 1) COMMIT
... same pair for lines 2, 3, 4 ...
INSERT row (line 5) COMMIT
INSERT audit (line 5) ✗ throws: nothing to roll back, the loop stops
# illustrative output
line | table row | table audit
-----+-----------+------------
1 | present | present
2 | present | present
3 | present | present
4 | present | present
5 | present | MISSING <- half-written
6+ | missing | missing <- never processed
Why: no BEGIN was ever sent, so there was no transaction to roll back.
Bridge: what @Transactional actually expands to
You know what a transaction is from Chapter E8: a group of statements applied as one unit. Spring's @Transactional does not add transaction code to your method. Instead, at startup, a BeanPostProcessor notices the annotation and wraps your bean in a proxy. The proxy runs the transaction logic around each call.
Step-by-step breakdown of what the proxy does:
- Start the transaction (before your code runs). The proxy asks the PlatformTransactionManager for one. For JPA, that means:
- Grab a connection: borrows one from HikariCP.
- Disable auto-commit:
connection.setAutoCommit(false). - Create the persistence context: opens an
EntityManager. - Bind to the thread: stores both in a
ThreadLocal(TransactionSynchronizationManager). This is how downstream repository calls find and reuse the same transaction without the connection being passed as a parameter.
- Call your real method. The proxy invokes the method on the wrapped object.
- Handle the outcome.
- Normal return: flush, commit, then clean up (close the
EntityManager, clear theThreadLocal, return the connection to the pool). - Unchecked exception (
RuntimeExceptionorError, such asIllegalStateExceptionorDataIntegrityViolationException): roll back. - Checked exception (such as
IOExceptionor your ownPaymentGatewayException): commit anyway, unless you saidrollbackFor.
- Normal return: flush, commit, then clean up (close the
The proxy's version of your method looks roughly like this:
// Simplified. The real code lives in Spring's TransactionInterceptor.
public void saveOne(String line) throws Throwable {
TransactionStatus tx = txManager.getTransaction(definition); // 1. begin: connection, auto-commit off, bind to thread
try {
target.saveOne(line); // 2. your real method
} catch (Throwable ex) {
if (txAttribute.rollbackOn(ex)) { // default: RuntimeException or Error
txManager.rollback(tx); // 3a. unchecked: roll back
} else {
txManager.commit(tx); // 3b. checked: commit anyway
}
throw ex; // the caller still sees the exception
}
txManager.commit(tx); // 3c. normal return: flush and commit
}
Make the invisible visible: this is what the thread holds while your method runs.
# illustrative
Thread http-nio-8080-exec-3
└─ ThreadLocal (TransactionSynchronizationManager)
├─ connection #4, autoCommit=false
└─ EntityManager (the persistence context)
repository call on exec-3 -> reads the ThreadLocal -> reuses connection #4
commit or rollback -> ThreadLocal cleared, connection #4 back in the pool
The checked-exception trap
That last rule surprises people: checked exceptions do not roll back by default.
class PaymentGatewayException extends Exception {} // checked
@Service
public class WalletService {
// fields: WalletRepository wallets, BankGateway bank (constructor injection)
@Transactional // ❌ TRAP: rollbackFor is not set, so a checked exception still commits
public void transferMoney(long walletId, BigDecimal amount) throws PaymentGatewayException {
Wallet wallet = wallets.findById(walletId).orElseThrow();
wallet.deduct(amount); // balance changed in the persistence context
bank.send(walletId, amount); // throws PaymentGatewayException
}
}
// Result: the proxy sees a checked exception, flushes and COMMITS the deduction.
// The money left the wallet and never reached the bank. The caller still gets the exception.
What you see:
# illustrative output
UPDATE wallet SET balance = 70 WHERE id = 1
-- bank.send(...) throws PaymentGatewayException
COMMIT ✗ the checked exception does not roll back
wallet table: id | balance
before call 1 | 100
after call 1 | 70 <- money gone, bank never received it
The fix is one attribute:
@Service
public class WalletService {
// fields and constructor as above
@Transactional(rollbackFor = Exception.class) // ✅ FIX: any Exception, checked or not, rolls back
public void transferMoney(long walletId, BigDecimal amount) throws PaymentGatewayException {
Wallet wallet = wallets.findById(walletId).orElseThrow();
wallet.deduct(amount);
bank.send(walletId, amount); // throws PaymentGatewayException
}
}
// Result: the proxy rolls back. The deduction is undone and the balance is unchanged.
What you see now:
# illustrative output
UPDATE wallet SET balance = 70 WHERE id = 1
-- bank.send(...) throws PaymentGatewayException
ROLLBACK ✅ rollbackFor = Exception.class
wallet table: id | balance
before call 1 | 100
after call 1 | 100 <- unchanged
- Fails:
bank.send(...)throwsPaymentGatewayExceptionwithoutrollbackFor. The deduction is committed. - Works: the same line with
rollbackFor = Exception.class. The proxy rolls back and the balance stays unchanged.
Why did the designers make this choice? The rule is inherited from EJB, where checked exceptions were treated as recoverable business outcomes and unchecked ones as system failures. Take a login method that commits an audit row, then throws a checked InvalidPasswordException. The audit row was meant to survive. Spring kept the same default.
| Method outcome | Default proxy action | How to override |
|---|---|---|
| Returns normally | Flush and commit | None needed |
RuntimeException or Error | Roll back | noRollbackFor |
| Checked exception | Flush and commit | rollbackFor = Exception.class |
Rule, why and example for each row of the cheat sheet:
- Returns normally. Rule: flush and commit. Why: no failure means keep the work. Example:
saveOne()returns and the row is in the database. RuntimeExceptionorError. Rule: roll back. Why: an unchecked exception is a bug or system failure. Example:IllegalStateExceptionin the middle of a write undoes the earlier statements. Override withnoRollbackForif one specific exception is harmless.- Checked exception. Rule: commit. Why: the EJB heritage above. Example:
PaymentGatewayExceptioncommits the deduction. Override withrollbackFor = Exception.class.
Think of the proxy as a receptionist: every visitor who comes through the front desk is logged, but two colleagues talking to each other inside the office never pass the desk.
- Interview takeaway: "
@Transactionalis a proxy that begins before my method and commits or rolls back after it. By default only unchecked exceptions roll back, so I setrollbackFor = Exception.classwhen a checked exception should undo the work."
The self-invocation trap, spelled out
Now picture it, using the same ImportService. The setup is the class above, called from OrderController.
Make the invisible visible: at runtime there are two objects, not one. Spring generates the first.
// generated by Spring at startup (pseudo-Java)
class ImportService$$SpringCGLIB$$0 extends ImportService {
ImportService target; // the real object
@Override void importAll(List<String> lines) {
target.importAll(lines); // no @Transactional on importAll: no advice, plain delegate
}
@Override void saveOne(String line) {
begin(); // transaction advice lives here only
try { target.saveOne(line); commit(); } catch (RuntimeException e) { rollback(); throw e; }
}
}
// the object you wrote
class ImportService {
void importAll(List<String> lines) {
for (String line : lines) {
this.saveOne(line); // `this` is the target object, so this lands on the REAL saveOne,
} // not on the proxy's override above
}
@Transactional void saveOne(String line) { /* rows.save(...); audit.save(...) */ }
}
The trace:
Controller ──► proxy.importAll() no @Transactional here -> no transaction
└─► target.importAll()
└─► this.saveOne(row 5) ✗ direct call on the real object;
the proxy's saveOne() is never entered
What you see: with logging.level.org.springframework.transaction.interceptor=TRACE the proxy announces every transaction it opens. Here it is silent.
# illustrative output
(no "Getting transaction for [ImportService.saveOne]" lines at all)
(no "Completing transaction for ..." lines either)
Why: only a call that enters the proxy can start a transaction. this.saveOne() skips the proxy.
The same trap applies to every proxy-based annotation: @Cacheable, @Async, @Retryable, and method security.
The fixes, in order of preference:
Fix 1: move saveOne into a separate bean
@Service
public class ImportService {
private final RowWriter writer;
public ImportService(RowWriter writer) { this.writer = writer; }
public void importAll(List<String> lines) {
for (String line : lines) {
writer.saveOne(line); // ✅ FIX: another bean, so the call crosses RowWriter's proxy
}
}
}
@Service
public class RowWriter {
// fields: RowRepository rows, AuditRepository audit (constructor injection)
@Transactional
public void saveOne(String line) { // the proxy now opens one transaction per row
rows.save(parse(line));
audit.save(new RowAudit(line));
}
}
// Result: if row 5 fails, row 5 rolls back completely. Rows 1-4 stay committed.
What you see now:
# illustrative output
BEGIN INSERT row(1) INSERT audit(1) COMMIT <- one transaction per line, lines 1-4
BEGIN INSERT row(5) INSERT audit(5) ✗ throws ROLLBACK
line | table row | table audit
1-4| present | present
5 | missing | missing <- rolled back as a unit
6+ | missing | missing <- the exception stopped the loop
Fix 2: annotate the outer method, if one big transaction is what you want
@Service
public class ImportService {
// fields: RowRepository rows, AuditRepository audit (constructor injection)
@Transactional // ✅ FIX: the controller's call goes through the proxy, which opens ONE transaction
public void importAll(List<String> lines) {
for (String line : lines) {
saveOne(line); // still a plain this-call, but it no longer matters: we are already inside the transaction
}
}
void saveOne(String line) {
rows.save(parse(line));
audit.save(new RowAudit(line));
}
}
// Result: all or nothing. If row 5 fails, rows 1-4 roll back too.
// Cost: one long transaction holds one connection for the whole import.
What you see now:
# illustrative output
BEGIN
INSERT row(1) INSERT audit(1) ... INSERT row(5) INSERT audit(5) ✗ throws
ROLLBACK <- one transaction around the whole loop
line | table row | table audit
1-5| missing | missing <- all or nothing
Fix 3, last resort: inject the bean into itself with @Lazy
@Service
public class ImportService {
private final ImportService self; // a proxy of this very bean
public ImportService(@Lazy ImportService self) { // @Lazy avoids the circular-dependency failure at startup
this.self = self;
}
public void importAll(List<String> lines) {
for (String line : lines) {
self.saveOne(line); // ✅ goes through the proxy, so @Transactional applies
}
}
@Transactional
public void saveOne(String line) { /* ... */ }
}
// Result: it works, but the class now depends on itself. Prefer Fix 1.
What you see now: the same picture as Fix 1, one transaction per row, because self is the proxy.
- Fails:
this.saveOne(line)or a baresaveOne(line)inside the same class. Spring raises no exception; the annotation is silently ignored. - Works:
writer.saveOne(line)on another bean, an annotation on the outer method, orself.saveOne(line)through a self-injected proxy.
Do not use AopContext.currentProxy() unless you enjoy explaining it in code review.
this.saveOne() call does not, so the transaction is never opened.| What the code does | Transaction opened? | Why |
|---|---|---|
Controller calls service.saveOne() | Works | The controller holds the proxy, so the call is intercepted. |
importAll() calls this.saveOne() | Silently not applied | this is the real object, not the proxy. |
importAll() calls otherBean.saveOne() | Works | The call crosses another bean's proxy. |
importAll() is annotated, calls this.saveOne() | Works (one transaction) | The outer call came through the proxy; the inner call joins it. |
@Transactional on a private method | Silently not applied | A proxy cannot intercept a private method. |
@Transactional on a final method | Silently not applied | A CGLIB proxy works by subclassing and cannot override a final method. |
- Interview takeaway: "The annotation only works on calls that enter through the proxy. A call from inside the class skips it, so I move the method to another bean or annotate the entry point."
Propagation and isolation, in one paragraph each
Propagation answers one question: "what happens when a transactional method calls another one?"
| Mode | What it does | Use it / avoid it |
|---|---|---|
REQUIREDthe default | Joins the existing transaction, or starts one if none exists. | This is why a RuntimeException thrown three calls deep marks the whole transaction rollback-only — and why the outer method then gets UnexpectedRollbackException on commit if it swallowed the inner exception. |
REQUIRES_NEW | Suspends the current transaction and opens a fresh one, on a second connection. | Right for "write an audit row even if the business operation fails". Wrong when the pool is small — each nesting level holds one more connection. |
NESTED | Uses a JDBC savepoint on the same connection, so the inner part can roll back alone. | Plain JDBC supports it. JPA does not. |
SUPPORTS, NOT_SUPPORTED, MANDATORY, NEVER | Assertion-style options. | Name them to show you know they exist. |
Rule, why and example for each row of the table:
REQUIRED. Rule: join if one exists. Why: one business operation should be one unit of work. Example:placeOrder()callsaudit.record()and both share one commit.REQUIRES_NEW. Rule: always suspend and start fresh. Why: some writes must outlive the caller's failure. Example: the audit row below.NESTED. Rule: a savepoint inside the current transaction. Why: roll back only the inner part. Example: a batch import that skips one bad row, on plain JDBC.- The assertion-style modes. Rule: they check or suspend the transaction instead of creating one. Why: they stop code running in, or outside, a transaction by mistake. Example:
MANDATORYon a method that must never be called without a transaction.
Both examples below use the same pair of classes. Only the propagation on AuditService.record() changes.
REQUIRED: one shared transaction
@Service
public class OrderService {
// fields: OrderRepository orders, AuditService audit (constructor injection)
@Transactional // transaction T1 starts here
public void placeOrder(Order order, boolean chargeFails) {
orders.save(order);
audit.record("order placed " + order.id()); // separate bean, so the proxy applies
if (chargeFails) {
throw new IllegalStateException("charge failed");
}
}
}
@Service
public class AuditService {
// field: AuditRepository audits (constructor injection)
@Transactional // default REQUIRED: joins T1, starts nothing
public void record(String event) {
audits.save(new AuditRow(event));
}
}
// chargeFails = false: T1 commits. Database: order row + audit row.
// chargeFails = true: T1 rolls back. Database: nothing. The audit row is lost with the order.
//
// ❌ TRAP: if record() itself throws a RuntimeException and placeOrder() catches and ignores it,
// the proxy has already marked T1 rollback-only. The commit then throws
// UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
// Database: nothing.
- Works: the exception propagates out of
placeOrder(). Everything rolls back and the caller seesIllegalStateException. - Fails: a swallowed inner exception. The outer commit throws
UnexpectedRollbackException.
The trace for the swallowed exception. The flag is set where the inner proxy sees the exception, not where the outer commit fails.
OrderService proxy.placeOrder() T1 begins on connection #1
└─► target.placeOrder()
└─► AuditService proxy.record() REQUIRED: joins T1
└─► target.record() throws IllegalStateException
◄── proxy sees a RuntimeException -> T1 marked rollback-only ✗ flag set here
catch (RuntimeException e) { } swallowed, placeOrder() carries on
orders.save(order)
◄── proxy: method returned normally -> tries to commit
T1 is rollback-only -> ROLLBACK, then throws UnexpectedRollbackException
What you see: what each REQUIRED case leaves in the database.
# illustrative output
case | order | audit
charge ok | yes | yes
charge fails (exception escapes) | - | -
record() fails, caller swallows | - | - + UnexpectedRollbackException
REQUIRES_NEW: an independent transaction on a second connection
// OrderService is unchanged.
@Service
public class AuditService {
// field: AuditRepository audits (constructor injection)
@Transactional(propagation = Propagation.REQUIRES_NEW) // suspends T1, starts T2 on a second connection
public void record(String event) {
audits.save(new AuditRow(event));
} // T2 commits here, before placeOrder() continues
}
// chargeFails = false: T2 commits, then T1 commits. Database: order row + audit row.
// chargeFails = true: T2 already committed; T1 rolls back. Database: audit row only. ✅ the audit survives.
//
// If record() throws and placeOrder() ignores it: only T2 rolls back. T1 commits.
// Database: order row, no audit row. No UnexpectedRollbackException.
//
// ❌ TRAP: while record() runs, this thread holds TWO connections (T1 suspended, T2 active).
// With a pool of 10 and 10 concurrent placeOrder() calls, every thread holds one connection
// and waits for a second. All of them wait until connection-timeout.
- Works: the audit row is committed before the charge fails, so the later rollback cannot touch it.
- Fails: a small pool under load. Requests wait for a second connection until Hikari throws
SQLTransientConnectionException(connection is not available).
The trace: two transactions, two connections, overlapping in time.
# illustrative
time ──────────────────────────────────────────────►
connection #1: [T1 BEGIN INSERT order ... suspended ........ resumed ROLLBACK] <- charge fails
connection #2: [T2 BEGIN INSERT audit COMMIT]
^ record() runs here
# illustrative output
case | order | audit
charge ok | yes | yes
charge fails (exception escapes) | - | yes <- audit survives
record() fails, caller swallows | yes | - <- only T2 rolled back, no UnexpectedRollbackException
What you see when the pool is small. Ten requests arrive at once, and the pool has ten connections:
# illustrative
HikariPool-1 (total=10, active=10, idle=0, waiting=10)
exec-1 holds connection #1 waits for a 2nd (record(), REQUIRES_NEW)
exec-2 holds connection #2 waits for a 2nd
...
exec-10 holds connection #10 waits for a 2nd
nobody can finish, so nobody releases a connection ... after 30 s:
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
- Interview takeaway: REQUIRED means one shared fate, so a swallowed inner exception still rolls everything back and throws
UnexpectedRollbackException. REQUIRES_NEW buys independence at the price of a second connection per nesting level.
Isolation is the database dial from Chapter E8. @Transactional(isolation = Isolation.SERIALIZABLE) sets it per transaction, on the connection.
The default, DEFAULT, means "whatever the database's default is":
- REPEATABLE READ on MySQL.
- READ COMMITTED on PostgreSQL.
Those are different, and the difference is yours to know.
One Spring-specific fact is worth memorising: readOnly = true is a hint,
not a guard. It lets Hibernate skip dirty checking, and lets some drivers route to a
replica. It will not stop a stray UPDATE on every database.
@Transactional(isolation = Isolation.SERIALIZABLE) // set on the connection for this transaction
public void closeBooks() { /* ... */ }
@Transactional(readOnly = true)
public void report(long id) {
Account a = accounts.findById(id).orElseThrow();
a.setNote("touched"); // ❌ TRAP: readOnly is a hint. Hibernate skips dirty checking,
// but on some databases an explicit UPDATE would still run.
}
// Result: do not rely on readOnly to protect data. Do not write in a read-only method.
What you see: the statements for the report() call above.
# illustrative output
readOnly = false: select account ... (flush at commit) update account set note='touched' COMMIT
readOnly = true : select account ... COMMIT <- Hibernate skips the flush, so no UPDATE from dirty checking
# an explicit update statement you write yourself is not blocked by the hint on every database
- Interview takeaway: "Isolation
DEFAULTmeans the database's own default, which differs between MySQL and PostgreSQL.readOnly = trueis an optimisation hint, not protection."
HikariCP: the pool that decides your ceiling
Start with the actors and each one's limit:
| Actor | Limit | Default |
|---|---|---|
| Tomcat worker threads | How many requests run at once | 200 threads |
| HikariCP pool | spring.datasource.hikari.maximum-pool-size | 10 connections |
| Waiting for a connection | spring.datasource.hikari.connection-timeout | 30 seconds |
| The database | Its own maximum number of connections, for all instances together | Set on the database server |
Think of ten checkout tills in a shop with 200 people in the queue: one customer who takes ten minutes blocks a till for everyone behind them.
Boot's default JDBC pool is HikariCP, with a default maximum of 10 connections (spring.datasource.hikari.maximum-pool-size) and a 30-second connection-timeout.
The arithmetic every senior should be able to do aloud. Ten connections, and a request that holds one on average for:
- 20 milliseconds: the pool serves 500 requests per second.
- 200 milliseconds (a slow query): the same pool serves 50 per second.
- Above that: requests queue for up to 30 seconds, then fail with the famous "Connection is not available".
Meanwhile Tomcat's 200 threads are all sitting in that queue.
That is the coupling to understand: the connection pool, not the thread pool, is usually the real capacity limit, and a slow query turns a healthy service into a 30-second-timeout service without anything crashing.
Size the pool from the formula HikariCP's author recommends, connections ≈ CPU cores × 2 + effective spindle count, on the database host, then divide by the number of application instances.
Twenty instances with 30 connections each is 600 connections against a database that is happiest with about 50. The fix is a smaller pool per instance, not a bigger one.
Worked example of the total-connections rule, step by step:
- Pool per instance: 10 connections (the default).
- Instances: 4 pods, so 4 × 10 = 40 connections in total. That fits a database that is happiest with about 50.
- Autoscale to 20 pods: 20 × 10 = 200 connections. The database now refuses new connections, even though no single instance changed.
- Rule: instances × pool size must stay under the database's connection limit, including headroom for migrations and admin sessions.
Step-by-step: what application-db.yml sets, in plain English
maximum-pool-size: 8andminimum-idle: 8make a fixed-size pool. Hikari's author recommends a fixed size in production so the pool never pays connection-creation latency under a burst.connection-timeout: 3000caps how long a thread waits for a connection at 3 seconds instead of 30. Failing fast frees the Tomcat thread and lets the caller retry or shed load; a 30-second wait just turns one slow query into a thread-pool outage.max-lifetime: 1500000(25 minutes) retires connections before any network device or database idle timeout can silently kill them; it must be a few minutes shorter than the database's ownwait_timeoutoridle_session_timeout.leak-detection-threshold: 20000logs a stack trace for any connection checked out longer than 20 seconds, which is how you find the code path that forgot to close or the transaction that spans an HTTP call.spring.jpa.open-in-view: falseturns off the Open Session In View pattern, which otherwise keeps the JPA session and its connection open for the entire HTTP request, including the time spent rendering JSON, so the connection is held far longer than the transaction.spring.transaction.default-timeout: 10makes every@Transactionalwithout an explicit timeout give up after 10 seconds, which bounds how long a stuck transaction can hold a connection.
spring:
datasource:
url: jdbc:postgresql://db:5432/orders
username: ${DB_USER}
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 8
minimum-idle: 8
connection-timeout: 3000
max-lifetime: 1500000
leak-detection-threshold: 20000
pool-name: orders-pool
jpa:
open-in-view: false
properties:
hibernate:
jdbc:
batch_size: 50
order_inserts: true
transaction:
default-timeout: 10
management:
metrics:
enable:
hikaricp: true
Read the metrics this exposes. With Actuator and Micrometer, three of them tell the story:
| Metric | What it tells you |
|---|---|
/actuator/metrics/hikaricp.connections.active | How many connections are checked out right now. |
hikaricp.connections.pending | How many threads are waiting for one. |
hikaricp.connections.usage | A timer of how long each checkout lasted. |
The single most useful production dashboard line for a Boot service is pending. When it is above zero for more than a few seconds, you are pool-bound. The next question is the cause, and there are three shapes:
- Slow query:
usagerises. - Leak:
activeclimbs and never falls. - Plain load:
usageflat,activepinned at max.
Those three shapes are the three branches of the "Hikari pool exhausted" scenario in the drill.
Make the invisible visible: the pool at three moments.
# illustrative output
time query time hikari active/max pending Tomcat busy threads
10:00 20 ms 3 / 10 0 6
10:05 200 ms 10 / 10 14 60 <- slow query, pool full
10:06 200 ms 10 / 10 190 200 <- every worker waits for a connection
What you see: in the log, and as the client.
# illustrative output
DEBUG HikariPool-1 - Pool stats (total=10, active=10, idle=0, waiting=23)
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 30000ms.
# client: waits about 30 seconds, then receives an error response
Symptom, why, example, fix
- Symptom: requests hang for about 30 seconds, then fail with "Connection is not available".
- Why: all connections are checked out, and each waiting thread gives up after
connection-timeout. - Example: a report query goes from 20 ms to 200 ms. The pool's capacity falls from 500 to 50 requests per second, and the queue grows until requests time out.
- Fix: find the cause with the metrics above, cap the wait at 3 seconds, and keep the total connections under the database limit.
| Symptom | Root cause | Action |
|---|---|---|
pending above zero, usage rising | A slow query holds connections longer. | Fix or index the query; set spring.transaction.default-timeout. |
pending above zero, active climbing and never falling | A leak: a connection is never returned, or a transaction spans an HTTP call. | Set leak-detection-threshold and read the logged stack trace. |
pending above zero, usage flat, active at max | Plain load above the pool's capacity. | Add instances, but only while instances × pool size stays under the database limit. |
| The database refuses connections after scaling out | Too many instances × too large a pool. | Reduce the pool size per instance. |
- Interview takeaway: "The connection pool, not the thread pool, is usually the real limit. I cap the wait at 3 seconds, watch
hikaricp.connections.pending, and keep instances × pool size under the database limit."
Spring Data repositories, lightly
Spring Data JPA generates the implementation of your repository interface at startup, so you write only the interface. Step-by-step breakdown:
- Parse the method name.
findByStatusAndCreatedAfter(Status s, Instant t)is turned into a JPQL query by its name. - Generate a proxy. The generated proxy (another proxy!) executes that query when you call the method.
- Wrap every method in a transaction.
- Read methods get
readOnly = true. - Save and delete methods get a plain read-write transaction.
- Read methods get
That default is why calling repo.save() outside any @Transactional still works, and why calling it three times outside a transaction is three transactions.
public interface OrderRepository extends JpaRepository<Order, Long> {
// Derived query: fine for a simple lookup. Spring parses the name into JPQL.
List<Order> findByStatusAndCreatedAfter(Status status, Instant created);
// ✅ Explicit @Query: anything with a join or a projection, so the query is reviewable
@Query("select o from Order o join fetch o.customer where o.status = :status")
List<Order> findWithCustomer(@Param("status") Status status);
}
// In a caller with no @Transactional:
// repo.save(a); repo.save(b); repo.save(c);
// Result: three separate transactions. If c fails, a and b stay committed.
# illustrative output: repo.save(a); repo.save(b); repo.save(c); with no @Transactional on the caller
BEGIN INSERT a COMMIT
BEGIN INSERT b COMMIT
BEGIN INSERT c ✗ fails ROLLBACK <- a and b are already committed
The two things to say in an interview. First, derived query names are for simple lookups, and anything with a join or a projection should be an explicit @Query so the SQL is reviewable.
Second, N+1 selects are the number-one performance bug. It is the pattern where loading 100 orders, then touching each order's customer, fires 101 queries. Diagnose it by turning on spring.jpa.show-sql in a test and counting.
// Assume Order.customer is LAZY and there are 100 orders.
List<Order> orders = orderRepo.findAll(); // 1 query
for (Order o : orders) {
String name = o.getCustomer().getName(); // ❌ TRAP: one extra SELECT per order
}
// Result: 101 queries.
List<Order> fixed = orderRepo.findWithCustomer(Status.OPEN); // ✅ FIX: join fetch
// Result: 1 query.
# illustrative output (spring.jpa.show-sql=true)
select o.* from orders o <- 1 query
select c.* from customer c where c.id=? <- repeated 100 times, once per order
=> 101 statements
# after findWithCustomer(Status.OPEN)
select o.*, c.* from orders o join customer c on c.id = o.customer_id where o.status=?
=> 1 statement
How Hibernate's persistence context, dirty checking, and fetch strategies actually work is the subject of Chapter E5.
- Interview takeaway: "Repository methods are transactional by default, so three
save()calls outside a transaction are three transactions. I use@Querywith a join fetch to avoid N+1, and I count queries to prove it."
When a product leader asks why the checkout service "fell over at 2,000 users when the load test passed at 5,000", the honest sentence is: "The load test used fast queries; production hit one slow query, and our database connection pool of ten turned that one slow query into a thirty-second stall for every request behind it.
" The fix costs a day: cap the pool wait at three seconds, set a transaction timeout, stop holding connections while rendering responses, and alert on the pool's pending count.
The return: the failure mode changes from "everything hangs for thirty seconds and the site looks down" to "a few requests get a fast, retryable error while the rest keep flowing", which is the difference between a P1 incident with a public post-mortem and a line item in a weekly report.
Elevator version: "We are making the service fail small and fast instead of large and slow, and we will see it coming on a dashboard."
Quick reference — Data and transactions
- What @Transactional really is
- A proxy around your bean. The proxy opens and commits the transaction; your method never sees it.
- The self-invocation trap
this.method()bypasses the proxy entirely, so the annotation does nothing. The call must come from outside the bean.- Rollback default
- Runtime exceptions roll back. Checked exceptions do not, unless you say
rollbackFor. - REQUIRED vs REQUIRES_NEW
- REQUIRED joins. REQUIRES_NEW suspends and takes a second connection — which is how a small pool deadlocks.
- readOnly = true
- A hint, not a guard. Skips dirty checking; will not stop an UPDATE.
- HikariCP default
- 10 connections. This, not CPU, is usually the real ceiling. Watch
hikaricp.connections.pending.
05 · The primerConfiguration, Testing, Security & Observability
Settings come from seventeen ordered sources, tests are slow unless you use slices, security is a chain of filters, and observability is one vocabulary across metrics, traces and logs.
A Boot service reads its settings from, by Boot's own documentation, seventeen ordered sources. Later sources win. The main ones, from lowest to highest priority:
- Default properties.
application.ymlinside the jar.- Profile-specific files inside the jar.
- The same files outside the jar.
- OS environment variables.
- Java system properties.
- Command-line arguments.
- A few more.
The practical consequence: the value your service actually uses is the one from the highest-priority source. "But it says 8 in application.yml" is not evidence of anything until you have checked that no environment variable or Kubernetes ConfigMap overrides it.
The Actuator /actuator/env endpoint shows every source and which one won for each key, which is the first stop when "the config is not being picked up".
- Interview takeaway: "The value that wins is from the highest-priority source, so I check
/actuator/envbefore I trust what application.yml says."
Bridge: environment variables are just another property source
You already run twelve-factor style: configuration comes from the environment, not from the build. Boot maps environment variables onto properties with relaxed binding.
The property spring.datasource.hikari.maximum-pool-size is set by the environment variable SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE. The rules:
- Dots become underscores.
- Dashes are dropped.
- Case is ignored.
# application.yml inside the jar
spring:
datasource:
hikari:
maximum-pool-size: 8
# Kubernetes ConfigMap / container environment
# SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE=20
#
# Result: the pool is 20. The environment variable outranks the file inside the jar,
# so "but it says 8 in application.yml" proves nothing.
What you see: the same key in three sources, and the value that wins.
# illustrative
application.yml (inside jar) 8
application-prod.yml (inside jar) 12
environment variable 20 <- highest of the three, wins
command-line argument (not set)
effective value: 20
Profiles are named sets of overrides. With SPRING_PROFILES_ACTIVE=prod:
- Boot also loads
application-prod.ymlafterapplication.yml. - Any bean marked
@Profile("prod")is registered. - Beans marked
@Profile("!prod")are not.
The senior discipline is to keep profiles few (local, test, prod) and to put per-environment values in the environment, not in a dozen profile files that drift.
@ConfigurationProperties: typed, validated settings
Reading settings one @Value("${...}") at a time scatters string keys across the codebase and fails at first use rather than at startup. @ConfigurationProperties binds a whole prefix onto a class. Since Boot 2.6 a Java record with @ConfigurationProperties is the idiomatic shape: immutable and constructor-bound.
Add @Validated and Jakarta constraints and it is validated at startup. A typo in a property name then fails the boot, with a message naming the property, before the service takes a single request.
// ❌ TRAP: scattered string keys, checked only when this bean is first used
@Value("${payment.retries}") int retries;
// ✅ FIX: one typed, validated record for the whole prefix
@Validated
@ConfigurationProperties(prefix = "payment")
record PaymentProperties(@Min(0) @Max(5) int retries) {}
// Result: payment.retries=9 stops startup with a report naming the property.
Step-by-step: what PaymentProperties.java does, in plain English
- The record declares three settings under the prefix
payment: the gateway URL, a per-call timeout as aDuration, and a retry count. Boot converts2sorPT2Sin YAML into aDurationautomatically. @Validatedplus@NotBlank,@DurationMin, and@Maxmake Boot run validation during binding; an invalid value stops startup with a report of which property failed and why.@ConfigurationPropertiesScanon the application class tells Boot to find and register every@ConfigurationPropertiestype in the package, so the record becomes an injectable bean with no further ceremony.- The
PaymentClientbean receives the record by constructor injection, and builds Spring'sRestClient, the synchronous HTTP client introduced in Spring 6.1 that replacesRestTemplatefor new code, with the configured base URL. - The YAML snippet shows the matching keys; the environment variable comment shows how the same value is overridden in production without touching the file.
package demo.payment;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.convert.DurationMin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestClient;
import java.time.Duration;
@Validated
@ConfigurationProperties(prefix = "payment")
record PaymentProperties(
@NotBlank String gatewayUrl,
@DurationMin(millis = 100) Duration timeout,
@Min(0) @Max(5) int retries) {}
@Configuration(proxyBeanMethods = false)
class PaymentConfig {
@Bean
RestClient paymentRestClient(PaymentProperties props, RestClient.Builder builder) {
return builder.baseUrl(props.gatewayUrl()).build();
}
}
@SpringBootApplication
@ConfigurationPropertiesScan
class PaymentApplication {
public static void main(String[] args) {
org.springframework.boot.SpringApplication.run(PaymentApplication.class, args);
}
}
// application.yml
// payment:
// gateway-url: https://sandbox.gateway.example
// timeout: 2s
// retries: 3
//
// production override, no file change:
// PAYMENT_GATEWAYURL=https://gateway.example PAYMENT_TIMEOUT=800ms
Read what happens on a mistake. Set PAYMENT_RETRIES=9 and start the service:
// PAYMENT_RETRIES=9 java -jar app.jar
//
// Binding to target demo.payment.PaymentProperties failed:
// Property: payment.retries
// Value: "9"
// Origin: System Environment Property "PAYMENT_RETRIES"
// Reason: must be less than or equal to 5
//
// Result: the service exits before taking a single request.
The Origin line is the part to point at in an interview. Boot tells you not just that the value is wrong but which of the seventeen sources it came from, which is precisely what you need at 3 a.m.
Secrets follow the same path:
- Kubernetes mounts them as environment variables or files.
- Boot's
spring.config.import=configtree:/run/secrets/reads a directory of one-file-per-secret into properties. - Vault or a cloud secrets manager plugs in through the same
spring.config.importmechanism.
Three rules: never put a secret in application.yml; never log the /actuator/env output; and remember that Actuator masks keys containing password, secret, key, and token by default, but not your creatively named gatewayCredential.
- Interview takeaway: "I bind settings to a validated record with
@ConfigurationProperties, so a bad value stops startup and the error names which source it came from."
Testing: slices, containers, and the context cache
@SpringBootTest starts the whole container, and a whole container with JPA and security takes 5 to 20 seconds. Two hundred test classes each starting one is an hour-long build.
Boot's answer is test slices. Each one starts only one layer:
@WebMvcTest(OrderController.class)starts only the web layer (controllers, advice, filters, Jackson) and gives youMockMvcto fire requests without a socket.@DataJpaTeststarts only JPA with an embedded database and wraps each test in a rolled-back transaction.@JsonTest,@RestClientTest, and@WebFluxTestfollow the same idea.
What the slice does not start, you replace with @MockitoBean (Spring Framework 6.2 and later; the older @MockBean was deprecated in Boot 3.4 and removed in Boot 4).
@WebMvcTest(OrderController.class) // only the web layer starts: about one second
class OrderControllerTest {
@Autowired MockMvc mvc; // fires requests with no real socket
@MockitoBean OrderService service; // ✅ the slice has no service bean, so replace it
@Test
void unknownOrderReturns404() throws Exception {
when(service.find(99L)).thenReturn(Optional.empty());
mvc.perform(get("/orders/99"))
.andExpect(status().isNotFound());
// Result: tests routing, status code and JSON. No database, no Tomcat.
}
}
Spring also caches contexts across test classes, keyed on their configuration. Every @MockitoBean or @TestPropertySource change creates a new key and a new startup, which is the usual reason a test suite "suddenly got slow".
@SpringBootTest
class ClassA { @MockitoBean PaymentClient client; } // context #1: pays for one startup
@SpringBootTest
class ClassB { @MockitoBean PaymentClient client; } // same configuration: reuses context #1
@SpringBootTest
class ClassC { @MockitoBean OrderService service; } // ❌ TRAP: different mock set = new key = a second startup
// Result: ten classes with identical annotations pay for one startup; one odd class pays for another.
For anything touching a real database or broker, Testcontainers starts a real PostgreSQL or Kafka in Docker for the test run, and Boot 3.1 and later wire it in with one annotation: a @Bean @ServiceConnection PostgreSQLContainer in a test configuration class makes Boot derive spring.datasource.* from the running container, no property juggling. The senior position on testing pyramids: unit tests for domain logic with no Spring at all, sliced tests for the web and persistence edges, and a small number of full @SpringBootTest with Testcontainers that prove the real wiring, migrations, and SQL work together.
What you see: the cache at work.
# illustrative output
ClassA context #1 MISS started in 6.2 s
ClassB context #1 HIT started in 0 s
ClassC context #2 MISS started in 5.8 s ✗ different mock set, new context
- Interview takeaway: "Plain unit tests for logic, slices for the web and persistence edges, and a few
@SpringBootTestwith Testcontainers. Identical test configuration keeps the context cache working."
Security: one filter chain, many filters
Spring Security registers a single servlet filter, FilterChainProxy. For each request it does the following:
- Select one chain. It picks one SecurityFilterChain based on URL patterns.
- Run that chain's ordered filters. There are about fifteen:
- CSRF
- session management
- authentication (form, basic, bearer token)
- exception translation
- finally
AuthorizationFilter, which checks the request against the rules you wrote
In Boot 3 and 4 you configure it as a bean, @Bean SecurityFilterChain, using the lambda DSL. The old WebSecurityConfigurerAdapter is gone.
For a stateless API the shape is fixed:
- Disable CSRF. It protects browser sessions, and you have no session.
- Set
SessionCreationPolicy.STATELESS. - Configure the OAuth2 resource server with
oauth2ResourceServer(o -> o.jwt(...)). It validates incoming JWTs against the issuer's published keys (spring.security.oauth2.resourceserver.jwt.issuer-uri) and populates the security context with the token's claims.
Method security, @PreAuthorize("hasAuthority('SCOPE_orders:write')"), is, once again, a proxy, with the same self-invocation caveat as @Transactional.
Step-by-step: what ApiSecurityConfig.java does, in plain English
@EnableMethodSecurityturns on@PreAuthorizechecks on service methods, so authorisation can live next to the business rule it protects.- The
SecurityFilterChainbean is the whole HTTP security configuration.csrf(AbstractHttpConfigurer::disable)removes CSRF protection because the API has no browser session to protect. sessionManagementwithSTATELESStells Security never to create an HTTP session, so every request must carry its own token and nothing is cached server-side.authorizeHttpRequestsdeclares the rules in order: Actuator health and the OpenAPI docs are public, everything under/ordersrequires theorders:readscope, and anything else needs an authenticated caller.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))enables JWT bearer authentication; the issuer URI in properties lets Boot fetch the signing keys and validate signature, expiry, and issuer on every request.- The property snippet shows the one setting the JWT decoder needs; Boot builds the decoder from the issuer's discovery document.
package demo.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@Configuration(proxyBeanMethods = false)
@EnableMethodSecurity
class ApiSecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/actuator/health/**", "/v3/api-docs/**").permitAll()
.requestMatchers("/orders/**").hasAuthority("SCOPE_orders:read")
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
return http.build();
}
}
// application.yml
// spring:
// security:
// oauth2:
// resourceserver:
// jwt:
// issuer-uri: https://auth.example.com/realms/shop
Read what a request sees. Each outcome comes from a different place in the chain:
- Fails, no token:
GET /orders/1returns 401 with aWWW-Authenticate: Bearerheader. It is produced by theBearerTokenAuthenticationEntryPointinside the filter chain, before the DispatcherServlet is ever involved. - Fails, valid token without the scope: 403 from the
AuthorizationFilter. - Works, valid token and scope: the request reaches the controller.
SecurityContextHolder.getContext().getAuthentication()holds aJwtAuthenticationTokenwhose authorities are the scopes prefixed withSCOPE_.
Make the invisible visible: the chain is an ordered list, and a request walks it from the top.
# the chain the ApiSecurityConfig above builds, in order
1. CSRF disabled
2. session management stateless
3. BearerTokenAuthenticationFilter reads the Authorization header, validates the JWT
4. ExceptionTranslationFilter turns "denied" into 401 or 403
5. AuthorizationFilter applies your authorizeHttpRequests rules
The trace: the same URL, three requests.
GET /orders/1 no token
chain "api" -> BearerTokenAuthenticationFilter (nothing to read) -> AuthorizationFilter ✗ not authenticated
ExceptionTranslationFilter -> BearerTokenAuthenticationEntryPoint
response: 401, WWW-Authenticate: Bearer (DispatcherServlet never reached)
GET /orders/1 valid token, scope orders:write only
... -> AuthorizationFilter ✗ authenticated, but lacks SCOPE_orders:read
response: 403 (DispatcherServlet never reached)
GET /orders/1 valid token, scope orders:read
... -> AuthorizationFilter passes -> DispatcherServlet -> OrderController
response: 200
The 401 and 403 never pass through your @ControllerAdvice, which is the point made in section 03 and a frequent interview follow-up.
- Interview takeaway: "Security is one filter chain that runs before the DispatcherServlet, so 401 and 403 never reach my
@ControllerAdvice. Method security is a proxy with the same self-invocation trap."
Observability: metrics, traces, logs, with one vocabulary
Micrometer is to metrics what SLF4J is to logging: a facade your code and Boot's auto-configuration write to, with a backend (Prometheus, OpenTelemetry, Datadog) chosen by dependency.
- Metrics, with no code. Boot registers JVM, Tomcat, Hikari, HTTP server (
http.server.requests, tagged by URI template, method, status, and outcome), and HTTP client metrics. - Traces, through one abstraction. Since Boot 3, tracing goes through Micrometer Observation. An
Observationis one unit of work that produces both a timer metric and a trace span, so the same@Observedannotation orobservationRegistry.observe(...)call feeds both systems. - Propagation. Boot propagates the W3C
traceparentheader throughRestClient,WebClient, and Kafka. - Logs, joined to traces. Boot stamps
traceIdandspanIdinto the logging MDC so every log line can be joined to its trace.
The properties to know are management.tracing.sampling.probability (default 0.1, meaning 10 percent of requests are traced) and management.otlp.tracing.endpoint for the collector. Boot 3.4 and later also emit structured JSON logs with logging.structured.format.console=ecs (or logstash, or gelf), which is what log pipelines want.
management:
tracing:
sampling:
probability: 0.1 # default: 10 percent of requests get a trace
otlp:
tracing:
endpoint: http://otel-collector:4318/v1/traces # where spans are sent
logging:
structured:
format:
console: ecs # Boot 3.4+: one JSON object per log line (or logstash, gelf)
What you see: one request, three places.
# illustrative output
log INFO [orders,6f1c2a9b8d3e4f50a1b2c3d4e5f60718,a3b4c5d6e7f80912] placing order 42
metric http.server.requests{uri=/orders/{id}, method=POST, status=200, outcome=SUCCESS} count +1
span traceId=6f1c2a9b8d3e4f50a1b2c3d4e5f60718 spanId=a3b4c5d6e7f80912 (sent to the collector)
# the same traceId in the log line and the span is what joins them
- Interview takeaway: "Micrometer is the one vocabulary. An Observation gives me a metric and a trace span together, and the
traceIdin the logs joins the three."
| Choose… | When proving… | Cost and caveat |
|---|---|---|
| Plain JUnit, no Spring | Domain logic, calculations, state machines | Milliseconds. If a class cannot be tested this way, its dependencies are probably too tangled |
@WebMvcTest + MockMvc + @MockitoBean service | Routing, validation, JSON shape, status codes, security rules on URLs | About one second; does not test the service or database, and does not start real Tomcat |
@DataJpaTest | Repository queries, mappings, constraints | Uses an embedded database unless you add @AutoConfigureTestDatabase(replace = NONE) and Testcontainers; H2 SQL differs from PostgreSQL SQL |
@SpringBootTest + Testcontainers + @ServiceConnection | Real wiring: migrations, transactions, security plus data, Kafka listeners | 5 to 20 seconds per context; keep the configuration identical across classes so the context cache works |
Do NOT use @SpringBootTest | For a single controller's validation or one query's behaviour | You pay full startup to test one layer, and the suite stops being something people run locally |
Rule, why and example for each row:
- Plain JUnit. Rule: no Spring for domain logic. Why: it runs in milliseconds. Example: a pricing calculation.
@WebMvcTest. Rule: test the web layer with a mocked service. Why: it proves routing and status codes without a database. Example: unknown order returns 404.@DataJpaTest. Rule: test queries against a database. Why: mappings and constraints only fail against real SQL. Example: a derived query with a unique constraint; use Testcontainers when H2's SQL differs from PostgreSQL's.@SpringBootTest+ Testcontainers. Rule: a few tests of the real wiring. Why: only they prove migrations, transactions and security work together. Example: place an order end to end.
06 · The primerProduction Behaviour: Startup, Shutdown, Memory & Resilience
What the service does before the first request and after the last one: how the seconds of startup are spent, how to drain connections without dropping them, why memory climbs after each deploy, and how to fail without taking the caller down with you.
A Boot service on the JVM typically starts in 3 to 10 seconds, uses 300 to 600 megabytes of heap at rest for a mid-sized application, and takes 30 seconds to drain when Kubernetes asks it to stop. Each of those numbers is a lever, and each has a failure mode that interviewers use as a scenario: the service that takes 90 seconds to start and fails its readiness probe, the memory that grows after each deploy until the container is killed, the in-flight requests dropped during a rolling update. This chapter is the mechanics behind those three numbers, then the resilience and messaging features that stop one slow dependency from becoming your outage.
Startup: what the 8 seconds are spent on
Startup is, in order:
- JVM start and class loading. About 1 second.
- Read configuration and evaluate conditions. Well under a second.
- Create the several hundred beans. Dominated by whatever heavy work happens in constructors and
@PostConstruct. - Hibernate builds its metamodel. If you let it, it also validates the schema against the database.
- Flyway or Liquibase runs migrations.
- Tomcat binds the port.
Boot fires ApplicationStartedEvent when the context is up and ApplicationReadyEvent after every ApplicationRunner has finished. The second one flips the Actuator readiness state to ACCEPTING_TRAFFIC.
So a 90-second startup almost always means one of:
- An
ApplicationRunneror@PostConstructdoing a network call that is timing out. - A migration tool running a large migration.
spring.jpa.hibernate.ddl-auto=validateagainst a slow database.- A classpath so large that scanning and condition evaluation crawl.
@SpringBootApplication
class OrdersApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(OrdersApplication.class);
app.setApplicationStartup(new BufferingApplicationStartup(2048)); // record startup steps
app.run(args);
}
}
// Then open /actuator/startup (the startup endpoint must be exposed).
// Result: a timeline of every bean's instantiation with durations.
// The slow @PostConstruct or migration is the longest bar: a five-minute diagnosis.
What you see: the timeline, with one step standing out.
# illustrative output, milliseconds
jvm + class loading ## 1000
config + conditions # 300
bean creation (~400 beans) #### 2200
inventoryWarmup @PostConstruct (HTTP call timing out) ########################## 60000 ✗
hibernate metamodel ## 900
flyway migration ## 1100
tomcat binds port
The --debug flag plus this startup tracking turns the "90 seconds to start" scenario into that five-minute diagnosis.
If the ceiling is the JVM itself, two options exist.
| Option | How it works | Cost | Choose it for |
|---|---|---|---|
| Class Data Sharing / AOT cache | Records the loaded classes from a training run and reloads them from an archive. On Java 24 and later this is the AOT cache (JEP 483, ahead-of-time class loading and linking). Typically cuts startup by 30 to 50 percent. Boot's layered jars and the -XX:AOTCache flag make it a two-line Dockerfile change. | A training run. | Long-running services where throughput dominates. |
| GraalVM native image | Compiles the application ahead of time into a native executable that starts in about 50 milliseconds and uses a fraction of the memory. Boot supports it through ./mvnw -Pnative native:compile and the Spring AOT engine, which pre-computes bean definitions and proxies at build time. | A several-minute build; no runtime reflection or proxy generation without hints; lower peak throughput than a warmed-up JIT. | Serverless functions and CLI tools where startup and memory dominate. |
| Symptom | Root cause | Action |
|---|---|---|
| Readiness probe fails after about 90 seconds; a network call appears in the log | An ApplicationRunner or @PostConstruct calls a dependency that is timing out. | Move the call out of startup or give it a short timeout. |
| A long gap while a migration runs | A large Flyway or Liquibase migration. | Split the migration, or run it as a separate step before the deploy. |
| Slow right after Hibernate starts | ddl-auto=validate against a slow database. | Check database latency. |
| Slow before any bean is created | A very large classpath. | Remove unused dependencies; use the AOT cache. |
| Cause unknown | Not yet measured. | Read /actuator/startup and find the longest bean. |
- Interview takeaway: "I would not guess. I turn on startup tracking, read
/actuator/startup, and the longest bean or migration is usually the answer."
Layered jars, in one paragraph
A Boot fat jar bundles your classes with every dependency. Boot's layered jar support splits it into ordered layers, so that a Dockerfile can copy each layer as its own image layer.
- Split into layers. By default:
dependencies,spring-boot-loader,snapshot-dependencies, andapplication. - Copy each layer separately in the Dockerfile. Each becomes its own image layer.
- Ship only what changed. Only the
applicationlayer changes between builds, so image pushes and pulls move a few hundred kilobytes instead of 80 megabytes, and the dependency layer stays cached on every node.
# illustrative
fat jar: 1 layer 80 MB pushed
layered jar: dependencies 0 MB (cached on the node)
spring-boot-loader 0 MB (cached)
application 0.3 MB pushed
The command java -Djarmode=tools -jar app.jar extract --layers --destination out (Boot 3.3 and later; older versions used -Djarmode=layertools) does the split. How Docker uses those layers is the subject of Chapter E9.
Shutdown: draining without dropping
When Kubernetes deletes a pod it sends SIGTERM, waits terminationGracePeriodSeconds (default 30), then sends SIGKILL. Boot's graceful shutdown makes the embedded server stop accepting new connections and wait for in-flight requests to complete before the context closes.
Step-by-step breakdown of the order that works:
- Stop being routable. Readiness goes down.
- Since Boot 2.3 the Actuator readiness probe can flip to
REFUSING_TRAFFICfirst, so the endpoint controller removes the pod before the server closes. - The other standard fix is a
preStophook that sleeps 5 seconds.
- Since Boot 2.3 the Actuator readiness probe can flip to
- Wait for the load balancers. The gap is the few hundred milliseconds between the pod being marked terminating and every load balancer noticing.
- Drain.
server.shutdown=gracefulrefuses new connections and lets in-flight requests finish, for up tospring.lifecycle.timeout-per-shutdown-phase. - Close. The context closes, the pool closes, the JVM exits.
server:
shutdown: graceful # Boot 4: already the default. Boot 3.x: you must set it.
spring:
lifecycle:
timeout-per-shutdown-phase: 20s # drain budget
# pod spec (Kubernetes), shown as comments:
# terminationGracePeriodSeconds: 30 # the SIGKILL deadline
# lifecycle.preStop: sleep 5 # 5s for the balancer to notice
#
# Budget: 5s preStop + 20s drain = 25s, under the 30s kill deadline.
# ❌ TRAP: a 30s drain timeout here would be cut off by SIGKILL mid-request.
What you see: the same rolling update, with and without graceful shutdown.
# illustrative
WITHOUT graceful shutdown
t=0s SIGTERM -> server stops right away
t=0s in-flight GET /orders/42 (needs 2 s) ✗ cut off: client sees a connection error
WITH graceful shutdown + readiness
t=0s SIGTERM, readiness -> REFUSING_TRAFFIC
t=0-5s preStop sleep: the balancer removes the pod, new requests go elsewhere
t=5s server.shutdown=graceful: no new connections; GET /orders/42 finishes -> client sees 200
t=7s nothing in flight -> context closes, pool closes, JVM exits (0 requests dropped)
| Symptom | Root cause | Action |
|---|---|---|
| Connection errors for a moment when a pod stops | The balancer still routes to the pod for a few hundred milliseconds. | Let readiness go down first, or add a 5-second preStop sleep. |
| In-flight requests cut off | Graceful shutdown is not enabled on Boot 3.x. | Set server.shutdown=graceful. |
| Pod killed before the drain finishes | preStop plus timeout-per-shutdown-phase is longer than terminationGracePeriodSeconds. | Keep 5s + 20s under the 30s deadline, or raise the deadline. |
- Interview takeaway: "Stop being routable, let the balancer notice, drain, close, all inside the kill deadline."
Memory that grows after each deploy
Two different mechanisms produce "memory climbs after every release", and they have different evidence and different fixes.
| Cause | Where the memory is | Evidence | Next tool |
|---|---|---|---|
| Heap leak | Inside the heap. | One class's instance count climbs; jvm.memory.used for the heap climbs. | Heap histogram or heap dump |
| Native growth | Outside the heap: metaspace, thread stacks, direct buffers, the JIT code cache. | Heap is flat while the container's working set climbs. | -XX:NativeMemoryTracking=summary |
The first is inside the heap, and it is a real leak. Four usual suspects:
- A static
Mapused as a cache, with no eviction. - A
ThreadLocalthat is set and never removed, on a pooled thread. - Listeners registered on every request and never unregistered.
- A Hibernate persistence context held open by a long transaction.
final class TenantContext {
private static final ThreadLocal<String> TENANT = new ThreadLocal<>();
static void run(String tenant, Runnable work) {
TENANT.set(tenant);
work.run();
// ❌ TRAP: never removed. Tomcat reuses this thread for the next request,
// so the value stays reachable (and leaks into the next caller).
}
static void runSafely(String tenant, Runnable work) {
TENANT.set(tenant);
try {
work.run();
} finally {
TENANT.remove(); // ✅ FIX: always clear on a pooled thread
}
}
}
// Result of the trap: heap grows by one value per pooled thread, and tenant data can bleed between requests.
# illustrative
http-nio-8080-exec-1 TENANT = "acme" <- never removed
http-nio-8080-exec-2 TENANT = "globex"
next request on exec-1, no set() call: TENANT.get() -> "acme" ✗ stale value from the last caller
The evidence is a heap histogram (jcmd <pid> GC.class_histogram) or a heap
dump from /actuator/heapdump, showing one class's instance count climbing.
The second is outside the heap. The container's memory limit covers heap plus metaspace, thread stacks, direct buffers and the JIT's code cache. So a JVM whose heap is fixed at 75 percent of the container can still be OOM-killed as native memory grows.
The evidence here is the opposite shape: jvm.memory.used for the heap is flat
while the container's working set climbs. -XX:NativeMemoryTracking=summary tells
you which native area is responsible.
One sizing rule follows from all of this. Since JDK 10 the JVM is container-aware, and
-XX:MaxRAMPercentage=75 is the right way to size the heap. A hard -Xmx
ignores what the container actually has.
The cross-check with Chapter E3's garbage-collection questions is deliberate.
What you see: the numbers across three deploys, for each cause. The container limit is 1024 MB.
# illustrative output
heap used container working set
heap leak
deploy 1 300 MB 650 MB
deploy 2 520 MB 870 MB <- both climb, class histogram shows one class growing
deploy 3 760 MB 1020 MB -> OOM-killed
native growth
deploy 1 300 MB 650 MB
deploy 2 300 MB 820 MB <- heap flat, working set climbs
deploy 3 300 MB 1020 MB -> OOM-killed (use NativeMemoryTracking)
| Symptom | Root cause | Action |
|---|---|---|
| Heap used climbs after each deploy; one class's count keeps rising | A heap leak: static map, un-removed ThreadLocal, unregistered listener, long transaction. | Take a class histogram or /actuator/heapdump; fix the owner of the objects. |
| Heap flat, container working set climbs, then OOM-kill | Native memory growth: metaspace, thread stacks, direct buffers, code cache. | Run with -XX:NativeMemoryTracking=summary and read the area that grows. |
| Container killed although heap is below its maximum | A hard -Xmx ignores the container's other memory. | Use -XX:MaxRAMPercentage=75. |
- Interview takeaway: "First decide whether the growth is inside the heap or outside it. The heap histogram and native memory tracking answer that."
Resilience, scheduling, events, and messaging
A synchronous call to a slow dependency ties up one Tomcat thread and one connection for as long as the dependency takes. Resilience4j gives you four guards, each one an annotation on a bean method.
| Guard | How it works | What it protects |
|---|---|---|
| Circuit breaker | After a configured failure rate, calls short-circuit with an immediate error for a cool-down period. | A dead dependency cannot consume all your threads. |
| Time limiter | Puts a ceiling on how long one call may take. | A slow dependency cannot hold a thread indefinitely. |
| Bulkhead | Caps the number of concurrent calls to one dependency. | It cannot take more than, say, 20 of your 200 threads. |
| Rate limiter | Caps how many calls are allowed in a period. | You do not overload a dependency, or breach its quota. |
Each guard is proxied, with the same self-invocation caveat as everything else. Spring Framework 7 also brought a lightweight retry into the core: @Retryable and @ConcurrencyLimit from org.springframework.resilience.annotation, enabled with @EnableResilientMethods. It covers the simplest cases without the extra library.
@Scheduled: one thread, every instance
@Scheduled runs a method on a fixed rate or cron. Two defaults catch people out:
- It runs on a single scheduler thread (
spring.task.scheduling.pool.size=1), so one slow job delays every other job. - In a multi-instance deployment every instance runs the job. A database-touching job needs a distributed lock (ShedLock), or should be a Kubernetes CronJob instead.
@Component
class ReportJob {
@Scheduled(cron = "0 0 * * * *") // top of every hour
// ❌ TRAP: with 3 instances running, this fires 3 times an hour.
// ✅ FIX: add @SchedulerLock(name = "rebuildReport", lockAtMostFor = "PT50M")
// (ShedLock) so only one instance runs it per tick.
void rebuildReport() {
// slow work here also delays every other @Scheduled method (pool size 1)
}
}
// Result without the lock: three instances rebuild the same report at the same time.
What you see: three instances at the top of the hour.
# illustrative output
10:00:00.002 [inst-a] rebuildReport start
10:00:00.004 [inst-b] rebuildReport start
10:00:00.009 [inst-c] rebuildReport start ✗ three rebuilds at once
# with @SchedulerLock
10:00:00.003 [inst-b] rebuildReport start <- got the lock
(inst-a and inst-c skip this run)
Application events: same thread, same transaction
ApplicationEventPublisher.publishEvent(...) with @EventListener is synchronous. The handler runs in the publisher's thread and transaction by default.
@TransactionalEventListener(phase = AFTER_COMMIT) defers a handler until the surrounding transaction commits. That is how you avoid sending "order confirmed" for an order that rolled back.
record OrderConfirmed(long orderId) {}
@Service
class PlaceOrderService {
// fields and constructor injection omitted
@Transactional
public void place(Order order) {
orders.save(order);
events.publishEvent(new OrderConfirmed(order.id()));
// ❌ TRAP: a plain @EventListener runs right here, before commit.
// If the commit then fails, the customer already got the email.
}
}
@Component
class ConfirmationMailer {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) // ✅ FIX
void on(OrderConfirmed event) {
// runs only after the transaction committed
}
}
// Result: a rolled-back order publishes the event, but this handler never runs.
What you see: what the listener observes in each case.
# illustrative
plain @EventListener:
INSERT order (not committed yet)
publishEvent -> mailer runs NOW <- the order is not visible to other connections yet
COMMIT fails -> ROLLBACK ✗ customer got an email for an order that does not exist
@TransactionalEventListener(AFTER_COMMIT):
INSERT order
COMMIT
mailer runs <- the order is committed and visible
Spring Kafka: at-least-once, so be idempotent
@KafkaListenergives you a consumer per partition with at-least-once delivery. Every handler must be idempotent.- Retry and dead-letter behaviour is configured with a
DefaultErrorHandlerand aDeadLetterPublishingRecoverer. - The transactional outbox ties events and Kafka together: insert the event as a row in the same transaction as the business write, and have a relay publish it to Kafka. It belongs to Chapter E7.
What you see: the same message delivered twice.
# illustrative output
orders-0 offset 41 msg-77 INSERT processed(msg-77) -> 1 row UPDATE stock on_hand 10 -> 9 (consumer dies before the offset is committed)
orders-0 offset 41 msg-77 INSERT processed(msg-77) ON CONFLICT DO NOTHING -> 0 rows -> return
stock.on_hand = 9 <- idempotent: the second delivery changed nothing
Step-by-step: what InventoryListener.java does, in plain English
- The
KafkaErrorHandlingconfiguration declares aDefaultErrorHandlerwith a fixed backoff of 1 second and 3 attempts; after the third failure theDeadLetterPublishingRecovererpublishes the record to a topic namedorders.DLTso nothing is lost and the partition is not blocked forever. addNotRetryableExceptions(IllegalArgumentException.class)sends malformed messages straight to the dead-letter topic without three pointless retries.- The listener class receives one record at a time from the
orderstopic in the consumer groupinventory; Spring Kafka runs one thread per partition assigned to this instance. - The
@Transactionalon the handler makes the inventory update and the processed-message row one database transaction; theprocessedtable's primary key on the message id is what makes a redelivered message a no-op, giving effective exactly-once processing on top of at-least-once delivery. - The
@CircuitBreakeron the pricing call uses Resilience4j; when the pricing service fails often enough,fallbackPricesupplies a cached price instead of holding the listener thread on a dead dependency. - The YAML sets manual acknowledgement mode off (the default record mode commits the offset after the handler returns) and turns on the Resilience4j breaker's sliding window of 20 calls with a 50 percent failure threshold.
package demo.inventory;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.DeadLetterPublishingRecoverer;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.backoff.FixedBackOff;
import java.math.BigDecimal;
record OrderPlaced(String messageId, String sku, int quantity) {}
@Configuration(proxyBeanMethods = false)
class KafkaErrorHandling {
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
DefaultErrorHandler handler = new DefaultErrorHandler(
new DeadLetterPublishingRecoverer(template), new FixedBackOff(1000L, 2L));
handler.addNotRetryableExceptions(IllegalArgumentException.class);
return handler;
}
}
@Component
class InventoryListener {
private final JdbcClient db;
private final PricingClient pricing;
InventoryListener(JdbcClient db, PricingClient pricing) {
this.db = db;
this.pricing = pricing;
}
@KafkaListener(topics = "orders", groupId = "inventory")
@Transactional
public void onOrder(OrderPlaced event) {
int inserted = db.sql("INSERT INTO processed(message_id) VALUES (:id) ON CONFLICT DO NOTHING")
.param("id", event.messageId()).update();
if (inserted == 0) {
return; // duplicate delivery: already handled, offset will be committed
}
BigDecimal unitPrice = pricing.priceFor(event.sku());
db.sql("UPDATE stock SET on_hand = on_hand - :q, last_price = :p WHERE sku = :sku")
.param("q", event.quantity()).param("p", unitPrice).param("sku", event.sku()).update();
}
}
@Component
class PricingClient {
private final org.springframework.web.client.RestClient http;
private final JdbcClient db;
PricingClient(org.springframework.web.client.RestClient.Builder builder, JdbcClient db) {
this.http = builder.baseUrl("http://pricing:8080").build();
this.db = db;
}
@CircuitBreaker(name = "pricing", fallbackMethod = "fallbackPrice")
public BigDecimal priceFor(String sku) {
return http.get().uri("/prices/{sku}", sku).retrieve().body(BigDecimal.class);
}
BigDecimal fallbackPrice(String sku, Throwable cause) {
return db.sql("SELECT last_price FROM stock WHERE sku = :sku")
.param("sku", sku).query(BigDecimal.class).single();
}
}
// application-kafka.yml
// spring:
// kafka:
// bootstrap-servers: kafka:9092
// consumer:
// auto-offset-reset: earliest
// value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
// properties:
// spring.json.trusted.packages: demo.inventory
// resilience4j:
// circuitbreaker:
// instances:
// pricing:
// sliding-window-size: 20
// failure-rate-threshold: 50
// wait-duration-in-open-state: 30s
Read what the logs show under failure. Each behaviour below is declarative, and each is a proxy.
- Pricing goes down. The first ten calls in the window fail with connection errors, and the listener falls back to the last known price.
- The breaker opens. On the eleventh failure Resilience4j logs
CircuitBreaker 'pricing' changed state from CLOSED to OPEN. For the next 30 seconds every call returns the fallback in under a millisecond, without touching the network. - The breaker probes. It goes
HALF_OPEN, lets a few trial calls through, and closes again if they succeed. - A message is redelivered. The Kafka side shows a single log line and no second stock update, because the
processedinsert returned zero rows.
# illustrative
t=0.0s CLOSED calls 1-10 fail -> fallback price failures 10 in the window
t=0.5s CLOSED call 11 fails -> OPEN
t=0.5-30s OPEN 4,200 calls -> fallback in <1 ms, 0 network calls
t=30.5s HALF_OPEN a few trial calls
trial calls succeed -> CLOSED | a trial call fails -> OPEN again
The interview point: both behaviours are proxies, so a listener method calling this.priceFor() would have had no breaker at all.
Worked scenario: traffic suddenly five times normal
Phase 1: stabilise. Protect the service first, then ask why.
- Shed load with 429. A rate limiter, or a bulkhead on the heavy paths, rejects the excess immediately instead of queueing it.
- Let circuit breakers fail fast. Failing dependencies stop consuming threads and connections.
- Serve cached or degraded responses. A breaker fallback, like
fallbackPriceabove, returns a last-known value. - Scale out, checking the database. New instances add connections, so check that instances × pool size stays under the database limit.
Phase 2: find the cause. Read the metrics once the service is stable:
- Tomcat busy threads: pinned at 200 means requests are queueing or blocked.
hikaricp.connections.pending: above zero means the pool is the limit.- CPU: high CPU points to compute; low CPU with busy threads points to waiting on a dependency.
- GC: long or frequent pauses point to memory pressure.
What you see: the numbers at each phase.
# illustrative output
normal spike (5x) after phase 1
requests per second 200 1000 1000 offered, 400 served, 600 answered 429
Tomcat busy threads 40 200 (max) 90
hikari pending 0 380 0
hikari active / max 4/10 10/10 8/10
p99 latency 120 ms 28 s 350 ms
instances 3 3 4 (4 x 10 = 40 connections, under the database limit)
| Symptom | Root cause | Action |
|---|---|---|
| Every thread busy, one dependency is slow | Calls wait on the dependency with no limit. | Add a time limiter and a circuit breaker. |
| One dependency takes all 200 threads | No cap on its concurrency. | Add a bulkhead. |
Hikari pending above zero during the spike | Database paths are over the pool's capacity. | Limit concurrency in front of them and shed with 429 or 503. |
| A breaker you added never opens | The call is made with this., bypassing the proxy. | Move the call to another bean. |
- Interview takeaway: "First make it fail small and fast: shed load, open breakers, serve a degraded answer. Then use the thread, Hikari, CPU and GC metrics to find the real cause."
Before reading on: a team enables spring.threads.virtual.enabled=true on a service whose Hikari pool is the default 10, expecting higher throughput. Load goes from 400 to 4,000 concurrent requests. What happens to the p99 latency, and what is the first metric that explains it?
Reveal the answer
Throughput barely changes and p99 latency gets much worse. Virtual threads removed the 200-thread ceiling, so Tomcat now accepts all 4,000 requests at once, and 3,990 of them queue for one of the 10 connections.
The connection-timeout of 30 seconds means some of them wait the full 30 seconds and then fail. The first metric is hikaricp.connections.pending, which jumps from near zero to thousands.
Before virtual threads, the Tomcat pool was accidentally acting as a bulkhead in front of the connection pool; removing it exposed the real limit.
The fix is to size and time-bound the pool deliberately, put an explicit concurrency limit (Resilience4j bulkhead or Spring Framework 7's @ConcurrencyLimit) in front of database-heavy paths, and shed load with a fast 503 instead of a slow timeout.
Quick reference — Production behaviour
- Startup budget
- JVM and class loading ~1s, then configuration, then bean creation, then the JPA metamodel. Class Data Sharing and the AOT cache attack the first part; fewer beans attacks the rest.
- Graceful shutdown
- SIGTERM → stop accepting → drain in-flight → close. Must finish inside
terminationGracePeriodSeconds, and the readiness probe must fail before the drain starts. - Memory climbing: two causes
- Heap leak (static map, un-removed
ThreadLocal, unregistered listener) shows in a class histogram. Native growth shows as flat heap with rising working set — useNativeMemoryTracking. - Sizing the heap
-XX:MaxRAMPercentage=75, never a hard-Xmx. The JVM has been container-aware since JDK 10.- Resilience is proxies too
- So a circuit breaker on a method you call with
this.does not exist. Same trap as@Transactional.
07 · DrillContainer, Beans & Auto-Configuration — Q1–Q40
The container questions are where a senior Spring round starts, because they reveal whether you know what the framework is doing on your behalf or only what the annotations are called. These forty questions cover bean discovery and ordering, the lifecycle and its hooks, proxies and their limits, auto-configuration and how to override it, and the startup path from main() to "ready". Scenarios are answered in diagnosis order. Say the answer aloud before revealing; if you cannot say why, you do not yet know it.
This group tests whether you can explain, mechanism by mechanism, how Boot decides which beans exist, and how to make it choose differently without fighting it.
Q1. "What does @SpringBootApplication actually expand to, and what would break if you replaced it with a plain @Configuration?"
Reveal answer
The real test Whether you know the three annotations underneath and what each one contributes, rather than treating the outer one as magic.
Strong answer It is a composed annotation made of three others:
@SpringBootConfigurationis a specialised@Configuration. It marks the class as a source of bean definitions. It also lets Boot's test support find it as the root configuration.@EnableAutoConfigurationimports theAutoConfigurationImportSelector. That reads everyMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsfile on the classpath and evaluates the@Conditionalguards. It registers the auto-configuration classes that survive.@ComponentScancarries two default filters, one excluding test configurations and one excluding nested auto-configurations. It scans the package of the annotated class, and everything below it, for@Componenttypes.
Replace it with a plain @Configuration and three things break:
- No auto-configuration: no embedded server, no
DataSource, no Jackson converter. - No component scan: none of your
@Serviceand@RestControllerclasses exist. - No root configuration for tests:
@SpringBootTestcan no longer locate your configuration automatically.
The one setting worth knowing on it is scanBasePackages. The default of "this package and below" is why putting the application class in a sub-package silently drops half your beans.
Picture it The same two classes of beans, with the scan root drawn on the package tree, so you can see which ones the container ever meets.
The setup The expansion below is what the annotation stands for. The trap uses this layout: the main class in com.shop.app, the services in the sibling package com.shop.orders.
@SpringBootApplication // this one annotation...
public class OrderApplication { }
// ...is exactly these three, plus @Configuration's own meta-annotations:
@Configuration // this class may declare @Bean methods
@EnableAutoConfiguration // apply everything in AutoConfiguration.imports
@ComponentScan // scan THIS package and everything below it
public class OrderApplication { }
// ❌ TRAP: the scan root is the annotated class's package. Move the class up a package
// and you silently start scanning your dependencies' packages too.
// Move it down into a sub-package and sibling packages are silently skipped.
// ✅ FIX: keep the class at the root of your package tree, or set scanBasePackages.
// Result: scan root = package of OrderApplication, nothing above it.
Read the third line. @ComponentScan takes no argument, so its base package is the package of the class it sits on — which is why the entry-point class must live at the root of your package tree, and why moving it is never a cosmetic change.
Make the invisible visible The scan root is the package of the annotated class. Anything outside that tree is never visited.
com.shop.app <- OrderApplication lives here = scan root
└─ web.HomeController ✓ visited, becomes a bean
com.shop.orders <- sibling package, NOT below the root
├─ OrderService ✗ never visited, not a bean
└─ OrderController ✗ never visited, not a bean
What you see No error at startup unless something injects the missing class.
# illustrative output
bean registry (name -> class)
homeController -> com.shop.app.web.HomeController
(no orderService, no orderController)
# a bean that injects OrderService:
UnsatisfiedDependencyException: Error creating bean with name 'invoiceJob' ...
NoSuchBeanDefinitionException: No qualifying bean of type 'com.shop.orders.OrderService' available
# nothing injects it:
GET /orders -> 404 Not Found (no startup error at all)
Why @ComponentScan takes no argument, so its base package is the package of the class it sits on. A bean the scanner never visits is not a mistake from the container's point of view.
The fix Either move the class to the root package or name the root explicitly.
@SpringBootApplication(scanBasePackages = "com.shop") // root of the whole tree
public class OrderApplication { }
What you see now
# illustrative output
bean registry (name -> class)
homeController -> com.shop.app.web.HomeController ✓
orderService -> com.shop.orders.OrderService ✓
orderController -> com.shop.orders.OrderController ✓
GET /orders -> 200 OK
Land it The annotation is a bundle of three decisions about where beans come from, and knowing the three lets you adjust any one of them instead of abandoning Boot.
- "Why does putting the application class in a sub-package silently drop beans, and how would you notice it in production?"
@ComponentScanwith no arguments scans the package of the annotated class and every package beneath it, nothing above it. If the main class sits incom.shop.appand the services live incom.shop.orders, the scanner never visitscom.shop.orders, so those classes are simply not beans.There is no error, because an absent bean is not a mistake from the container's point of view until something injects it.
You notice it as a
NoSuchBeanDefinitionExceptionat startup if something does inject it, or as a 404 on a controller nobody registered if nothing does.The way to catch it early is a test that asserts the expected bean count or a specific bean exists, and the fix is either to move the class to the root package or to set
scanBasePackages = "com.shop"explicitly.- "Which two filters does the annotation's component scan apply, and what problem does each solve?"
The first is
TypeExcludeFilter. It is a hook that Boot's test support uses so that a slice test, such as@WebMvcTest, can scan the same packages but keep only controllers and web components out of everything the scan finds. The second isAutoConfigurationExcludeFilter.It drops any class that is both a
@Configurationand listed in an auto-configuration imports file, so an auto-configuration class that happens to live under your base package is not registered twice, once by scanning in the early phase and once by the import selector in the late phase.That second registration would break the ordering guarantee that
@ConditionalOnMissingBeanrelies on, which is why the filter exists.- "What does the
excludeattribute do, and how is it different fromspring.autoconfigure.exclude?" Both remove named auto-configuration classes from the candidate list before conditions are evaluated. The annotation attribute,
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class), is compiled into the code and applies everywhere the jar runs.The property,
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, is read from the environment, so it can differ per profile or per deployment.I use the annotation when the exclusion is a permanent architectural fact, such as a service that builds its own pools, and the property when it is an environment concern.
One trap worth stating: excluding a class that is not actually an auto-configuration fails at startup with a clear message, which is a good thing, and excluding by name with the wrong package after the Boot 4 module split is the most common way to hit that.
- "How would you verify at runtime which auto-configurations actually applied?"
I would start the service with
--debugor setdebug=truein the environment, which prints the condition evaluation report with three sections:- Positive matches: every auto-configuration that applied, and the condition that let it through.
- Negative matches: each one that did not apply, with the exact condition that failed.
- Exclusions: the classes removed on purpose.
On a running instance the same information is available from Actuator's
/actuator/conditionsendpoint if it is exposed.I read the negative-matches entry for the class I care about, because it names the missing class or the bean that already existed, and that is normally the whole diagnosis in one line.
condition evaluation report (excerpt)runs offline# illustrative output Positive matches: DataSourceAutoConfiguration matched: - @ConditionalOnClass found required classes 'javax.sql.DataSource', ... (OnClassCondition) Negative matches: MongoAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient' (OnClassCondition)
Q2. "How does Boot find auto-configuration classes without scanning the classpath, and what changed between Boot 2 and Boot 3 there?"
Reveal answer
Strong answer Scanning every jar for annotated classes would be far too slow, so Boot uses an index file instead. Each auto-configuration jar ships a plain text file, META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, listing its auto-configuration classes one per line.
At startup the import selector works through these steps:
- Read all such files with the classloader's
getResources, and merge the lists. - Exclude anything named by
spring.autoconfigure.excludeor theexcludeattribute. - Pre-filter with
META-INF/spring-autoconfigure-metadata.properties, a generated file that records each class's@ConditionalOnClassrequirements. Classes whose required types are missing are dropped without even loading them. - Sort the survivors by
@AutoConfiguration(before, after)and@AutoConfigureOrder. - Import them.
What changed between versions:
- Boot 2: the list lived under the
org.springframework.boot.autoconfigure.EnableAutoConfigurationkey inMETA-INF/spring.factories. - Boot 2.7: introduced the imports file.
- Boot 3.0: stopped reading the old key for auto-configurations.
spring.factoriesstill works for other hooks such asEnvironmentPostProcessorandApplicationListener. - Boot 4: kept the mechanism and split the single autoconfigure jar into per-technology modules, each with its own imports file.
Picture it A library jar registered the old way, what the selector reads on Boot 3, and the one-line file that fixes it.
The setup A third-party library, acme-lib.jar, still registers its auto-configuration under the old key.
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.acme.AcmeAutoConfiguration
Make the invisible visible What the selector works through, with the candidate list shrinking at each step.
# illustrative numbers
imports files found on the classpath .... 4
candidates after merge .................. 143 classes
after exclude ........................... 142
after metadata pre-filter ............... 31 (required classes missing: dropped unloaded)
after sort and conditions ............... 24 applied
The trace
AutoConfigurationImportSelector (Boot 3)
├─► read META-INF/spring/...AutoConfiguration.imports in every jar ✓ acme-lib has none
└─► read spring.factories EnableAutoConfiguration key ✗ not read since Boot 3.0
AcmeAutoConfiguration never becomes a candidate
What you see The class is silent: not applied, and not even listed as a failed match.
# illustrative output
Positive matches:
(no AcmeAutoConfiguration)
Negative matches:
(no AcmeAutoConfiguration)
Why The class was never a candidate, so no condition was ever evaluated against it.
The fix Add the imports file, one fully qualified class name per line. It can live in your own project if the library will not change.
com.acme.AcmeAutoConfiguration
What you see now
# illustrative output
Positive matches:
AcmeAutoConfiguration matched:
- @ConditionalOnClass found required class 'com.acme.AcmeClient' (OnClassCondition)
Land it If a library's auto-configuration stopped applying after a Boot upgrade, the first thing to check is whether it still registers through the old spring.factories key.
- "What exactly is in
spring-autoconfigure-metadata.properties, who writes it, and what happens if it is stale?" It is a properties file generated at compile time by the
spring-boot-autoconfigure-processorannotation processor. For each auto-configuration class it records the values of@ConditionalOnClass,@ConditionalOnBean,@AutoConfigureOrder, and the before and after ordering attributes as plain strings.At startup the import selector reads those strings and can reject a class whose required types are missing without loading the class itself, which is much cheaper than reflection on hundreds of classes.
If the file is stale, meaning the annotations changed but the processor did not run, the only consequence is a slower start, because the real annotations are still evaluated when the class is loaded.
If the file is missing entirely, as it is for a library that forgot the processor, the mechanism falls back to loading every class, which is correct but slower.
- "A library still uses the
spring.factorieskey for its auto-configuration on Boot 3 or 4. What are the options, and which do you pick?" The library's auto-configuration silently does not apply, and the condition report never mentions it. Three options. The cleanest is to upgrade the library to a release that ships the imports file.
If no such release exists, I add a file at
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsin my own project listing the library's configuration class names, which Boot merges with every other imports file.The last resort is
@ImportAutoConfiguration(SomeLibraryAutoConfiguration.class)on a configuration class, which also honours conditions and runs in the late phase.I would not use a plain
@Import, because that registers the class in the early phase and its@ConditionalOnMissingBeanguards would then fire before my own beans exist.- "How are the survivors ordered, and what happens when two auto-configurations declare conflicting
beforeandafter?" Ordering is done in
AutoConfigurationSorterin three passes. First alphabetical by class name, which gives a stable baseline. Then by@AutoConfigureOrder, an integer where lower runs first. Then a topological sort honouring@AutoConfiguration(before = …, after = …), which are edges in a graph.If those edges form a cycle, for example A after B and B after A, the sorter throws an
IllegalStateExceptionnaming the cycle at startup. That is deliberate: a cycle would make the meaning of every@ConditionalOnMissingBeanin those classes undefined.In practice the way to avoid this is to only declare
afteragainst Boot's own classes and never against a peer library you do not control.- "What did the Boot 4 module split change for someone writing their own auto-configuration?"
As of Aug 2026, Boot 4 replaced the single
spring-boot-autoconfigurejar with per-technology modules such asspring-boot-jdbc,spring-boot-jackson, andspring-boot-security, each carrying its own auto-configuration classes and imports file. Two consequences.If my auto-configuration says
@AutoConfiguration(after = DataSourceAutoConfiguration.class), that class moved package, so I need the new module as an optional dependency and the new import.And any reflective reference by string, such as in
spring.autoconfigure.excludeor a test's@ImportAutoConfigurationby name, has to be updated to the new package.The upside is that an application only carries the auto-configuration modules it needs, so the candidate list is shorter and startup is a little faster.
Q3 · Scenario. "A service fails to start with 'expected single matching bean but found 2: primaryDataSource, reportingDataSource'. The team added a second database yesterday. Walk me through it."
Reveal answer
Strong answer I would diagnose in this order:
- Symptom: an injection ambiguity. Some bean asks for a
DataSourceby type and the container has two candidates. The exception names the requesting bean further up the stack, so I read the fullUnsatisfiedDependencyExceptionchain to find who is asking. It is almost always an auto-configured bean, such as the JPAEntityManagerFactory, Flyway, or the Hikari metrics binder, that expects exactly one pool. - Evidence: the condition report with
--debugshowsDataSourceAutoConfigurationbacked off because two user beans exist.HibernateJpaAutoConfigurationandFlywayAutoConfigurationstill matched and now need a singleDataSource. - Likely causes, ranked:
- Neither pool is marked
@Primary. - The second pool was declared as a
DataSourcebean when only aJdbcTemplatefor reporting was needed. - Someone copied a configuration class that also redefined the transaction manager.
- Neither pool is marked
- Fix:
- Mark the main pool
@Primaryso every by-type injection gets it. - Inject the reporting pool by
@Qualifier("reportingDataSource")where needed. - If the reporting database also needs JPA, declare a second
EntityManagerFactoryandPlatformTransactionManagerexplicitly with@EnableJpaRepositories(basePackages, entityManagerFactoryRef, transactionManagerRef). - Bind its properties with a separate
@ConfigurationProperties("reporting.datasource").
- Mark the main pool
- Prevention: a
@SpringBootTestthat loads the context in CI would have caught this before deployment. A naming convention where the second pool's beans all carry the qualifier avoids the ambiguity by design.
Picture it The bean registry before and after, and the one question the container cannot answer.
The setup Two DataSource beans, in the code below: the broken version first, then the two fixes.
// ❌ TRAP: two candidates, no way for the container to choose.
@Bean DataSource primaryDataSource(...) { ... }
@Bean DataSource reportingDataSource(...) { ... }
// Result: NoUniqueBeanDefinitionException: expected single matching bean but found 2
// ✅ FIX 1 — name a default. Every unqualified injection point gets this one.
@Bean @Primary
DataSource primaryDataSource(...) { ... }
@Bean
DataSource reportingDataSource(...) { ... }
// ✅ FIX 2 — qualify at the injection point. Explicit, and my preference when
// neither source is genuinely "the default".
public ReportService(@Qualifier("reportingDataSource") DataSource ds) { ... }
// Result: ReportService gets reportingDataSource; everything unqualified gets the primary.
// Note the knock-on: JpaAutoConfiguration, JdbcTemplate and Flyway all
// auto-configure against the @Primary one. Without @Primary they back off too,
// so you must then declare EntityManagerFactory and TransactionManager yourself.
The knock-on is the part people miss. Adding a second DataSource does not only break injection into your own beans — it disables several auto-configurations that were themselves looking for exactly one.
Make the invisible visible The registry the container holds when an unqualified DataSource injection point is resolved.
# illustrative output
before the fix after the fix
primaryDataSource -> HikariDataSource primaryDataSource -> HikariDataSource @Primary
reportingDataSource -> HikariDataSource reportingDataSource -> HikariDataSource
The trace A user bean, here auditWriter, asks for a DataSource with no qualifier.
creating bean auditWriter
└─► constructor needs DataSource (by type, no @Qualifier)
candidates: primaryDataSource, reportingDataSource ✗ two matches, no @Primary
└─► NoUniqueBeanDefinitionException
after the fix:
└─► needs DataSource -> candidates: primaryDataSource (@Primary) ✓ picked
ReportService(@Qualifier("reportingDataSource")) ✓ reportingDataSource
What you see
# illustrative output
UnsatisfiedDependencyException: Error creating bean with name 'auditWriter' ...
NoUniqueBeanDefinitionException: expected single matching bean but found 2: primaryDataSource,reportingDataSource
--debug condition report:
DataSourceAutoConfiguration ... did not match: @ConditionalOnMissingBean found beans primaryDataSource, reportingDataSource
Why Two candidates of the same type and no declared default leave the container nothing to choose by. It refuses to guess.
The fix The existing code block above: @Primary on the main pool, @Qualifier at the injection points that want the reporting pool.
What you see now
# illustrative output
auditWriter -> primaryDataSource
reportService -> reportingDataSource
context started in 4.1 seconds
Land it Two pools means Boot's single-database assumptions stop applying, so every consumer of the pool has to be told which one it gets, starting with @Primary.
- "You marked the main pool
@Primaryand it started, but now Flyway migrates the wrong database. What happened and what next?" @Primarytells every by-type injection to take that bean, and Flyway's auto-configuration injects aDataSourceby type, so it now migrates the primary pool.If the migrations were meant for the reporting database, or both databases need their own migrations, the auto-configured single Flyway is the wrong tool.
I would define the migrations explicitly: a
Flywaybean per database built withFlyway.configure().dataSource(reportingDataSource).locations("classpath:db/reporting"), or aFlywayMigrationInitializerper pool, and setspring.flyway.enabled=falseso the auto-configured one backs off.one Flyway per databaseruns offline@Bean(initMethod = "migrate") Flyway reportingFlyway(@Qualifier("reportingDataSource") DataSource ds) { return Flyway.configure() .dataSource(ds) .locations("classpath:db/reporting") // separate migration folder .load(); }The general rule is that once there are two pools, every auto-configured consumer of a pool has to be audited: Flyway, JPA, the JDBC health indicator, the Hikari metrics binder, and Spring Batch's job repository are the usual list.
- "Why not just use
@Qualifiereverywhere and skip@Primary?" Because I do not own every injection point. Boot's auto-configurations inject
DataSourceby type with no qualifier, and so do library beans I cannot edit. Without a@Primary, every one of those fails with the same ambiguity error.@Primaryanswers the question "which pool do you mean when you do not say" for the whole application, and@Qualifieranswers it for the specific injection points that want the other one. The combination is the honest model: one default, explicit exceptions.There is also
@Fallback, added in Spring Framework 6.2, which is the inverse of@Primary: it marks a bean that should lose the argument, useful when the reporting pool should only be picked if it is named.- "How do you bind the second pool's properties, and what is different about Hikari's settings?"
I declare a
@Bean @ConfigurationProperties("reporting.datasource")method returningDataSourceProperties, then a second method that callsproperties.initializeDataSourceBuilder().type(HikariDataSource.class).build(). The catch is thatDataSourcePropertiesonly holds the URL, username, password, and driver; Hikari's own settings, such asmaximum-pool-sizeandconnection-timeout, live on theHikariDataSourceobject. So the pool method itself also carries@ConfigurationProperties("reporting.datasource.hikari"), which binds those keys onto the built pool after construction. Boot's reference documentation shows this exact two-method pattern, and forgetting the second binding is why a reporting pool silently runs with Hikari's default of 10 connections.- "How would you make sure this cannot happen again at 10× the number of services?"
Two measures. First, every service runs a
@SpringBootTestthat loads the full context in CI, ideally with Testcontainers so the real pool actually connects; an ambiguity error fails the build long before deployment.Second, for a fleet, I would put the multi-database wiring into a shared starter that takes a map of named pool configurations, creates the pools, marks the one named
primaryas@Primary, and creates the JPA and transaction manager pair per entry.Then a team adding a second database changes YAML rather than copying a configuration class, and the error class disappears because nobody hand-writes the wiring anymore.
Q4. "Why does @ConditionalOnMissingBean work reliably in Boot's auto-configurations but is documented as unsafe in your own @Configuration classes?"
Reveal answer
The real test Whether you understand that the condition is evaluated at definition time, so ordering decides its meaning.
Strong answer The condition asks "is there already a bean definition of this type?" at the moment the configuration class is processed. It does not look into the future.
In Boot's auto-configurations the answer is reliable:
- Boot guarantees that all user configuration, meaning component-scanned classes and anything reached through
@Import, is registered before any auto-configuration is processed. - It sorts auto-configurations among themselves with
@AutoConfiguration(after = …). - So when
DataSourceAutoConfigurationasks the question, every user-declaredDataSourceis already known and the answer is correct.
Inside your own component-scanned configuration there is no such guarantee:
- The scan order between two of your configuration classes depends on the file system and class name ordering.
- So a
@ConditionalOnMissingBeaninConfigAmay be evaluated beforeConfigBregisters the bean it was meant to detect. - You get two beans or none depending on the day.
The reliable ways to make your own code conditional are:
- Put it in a real auto-configuration registered via the imports file, so it runs in the late phase.
- Or use conditions that do not depend on other definitions, such as
@ConditionalOnPropertyand@ConditionalOnClass.
Picture it Two machines scan the same two classes in a different order, so the same condition gives two different answers.
The setup Two component-scanned configuration classes. The default is guarded by @ConditionalOnMissingBean.
@Configuration
class CacheConfig {
@Bean
@ConditionalOnMissingBean // ❌ TRAP: answered when CacheConfig is parsed
CacheManager simpleCacheManager() { return new ConcurrentMapCacheManager(); }
}
@Configuration
class RedisConfig {
@Bean
CacheManager redisCacheManager(RedisConnectionFactory cf) {
return RedisCacheManager.create(cf);
}
}
// Result: one CacheManager or two, depending on which class is parsed first
Make the invisible visible The registry at each step, on two machines with a different scan order.
laptop (scan order: RedisConfig, CacheConfig)
1. RedisConfig parsed registry: [redisCacheManager]
2. CacheConfig parsed @ConditionalOnMissingBean sees redisCacheManager, backs off ✓
final registry: [redisCacheManager] one bean, works
CI container (scan order: CacheConfig, RedisConfig)
1. CacheConfig parsed registry: [] -> condition passes, registers simpleCacheManager ✗
2. RedisConfig parsed registers redisCacheManager
final registry: [simpleCacheManager, redisCacheManager] two beans
What you see The laptop is quiet. The CI container fails, or, with overriding enabled, quietly uses the wrong cache.
# illustrative output
NoUniqueBeanDefinitionException: expected single matching bean but found 2: simpleCacheManager,redisCacheManager
(raised by whichever bean injects a CacheManager)
Why The condition looks only at definitions registered so far, and the scan order between your own classes is not part of any contract.
The fix Use conditions that read the Environment, which is complete before any configuration class is parsed.
@Configuration
class CacheConfig {
@Bean
@ConditionalOnProperty(name = "cache.type", havingValue = "simple", matchIfMissing = true)
CacheManager simpleCacheManager() { return new ConcurrentMapCacheManager(); }
}
@Configuration
class RedisConfig {
@Bean
@ConditionalOnProperty(name = "cache.type", havingValue = "redis")
CacheManager redisCacheManager(RedisConnectionFactory cf) { return RedisCacheManager.create(cf); }
}
What you see now The same on both machines, in either scan order.
cache.type=redis laptop: [redisCacheManager] CI: [redisCacheManager] ✓
cache.type unset laptop: [simpleCacheManager] CI: [simpleCacheManager] ✓
Land it A condition on the presence of other beans is only as good as the ordering guarantee around it, and only auto-configuration has one.
- "Give a concrete example of the ordering bug in application code and how it manifests."
Suppose
CacheConfigdeclares aCacheManagerbean guarded by@ConditionalOnMissingBean, andRedisConfigdeclares an explicit Redis-backedCacheManager. Both are component-scanned. On a developer's machine the scanner happens to visitCacheConfigafterRedisConfig, so the condition sees the Redis bean and backs off: one bean, everything works.In the CI container the file system lists the classes in a different order,
CacheConfigis processed first, sees nothing, and registers its bean; thenRedisConfigregisters a second one and the application fails with "expected single matching bean" or, worse, with bean overriding enabled, silently uses the simple cache.The failure moves with the environment, which is the signature of an ordering-dependent condition.
- "If I want a default bean in my application that a profile can replace, what is the correct tool?"
Use conditions that depend on the environment rather than on other bean definitions. The simplest is
@Profile: the default implementation carries@Profile("!redis")and the replacement carries@Profile("redis"), and exactly one exists regardless of scan order.The equivalent with a property is
@ConditionalOnProperty(name = "cache.type", havingValue = "simple", matchIfMissing = true)on the default andhavingValue = "redis"on the other.Both are evaluated against the
Environment, which is complete before any configuration class is processed, so the answer is the same no matter which class the scanner reaches first.If I genuinely need "back off if the user defined one", I move the default into a real auto-configuration in the imports file.
- "Does
@ConditionalOnBeanhave the same problem, and is there a warning?" Yes, and it is worse, because
@ConditionalOnBeanin application code usually means "only if someone else defined X", and in the early phase the answer is almost always no.The Javadoc for both annotations carries the same sentence: the condition can only match bean definitions that have been processed so far, and it is strongly recommended to use it only in auto-configuration classes. There is no runtime warning, because the container cannot know the intent.
The one check that exists is
@ConditionalOnBeanand@ConditionalOnMissingBeanare evaluated in theREGISTER_BEANconfiguration phase, which is later than@ConditionalOnClass, and Boot'sSpringBootConditionlogs the outcome at TRACE underorg.springframework.boot.autoconfigure.condition, which is how I would prove which order actually happened.- "How does Boot guarantee user configuration is processed first, mechanically?"
@EnableAutoConfigurationimportsAutoConfigurationImportSelector, which implementsDeferredImportSelectorrather than plainImportSelector.ConfigurationClassParserprocesses all normal configuration classes, component scans, and plain imports first, collecting deferred selectors in a list, and only after every non-deferred source has been parsed does it call the deferred ones.Within the deferred group, the auto-configuration classes are sorted as described in Q2 and then parsed in that order.
So the guarantee is structural: it comes from the parser's two-pass design, and anything registered through
@Import, scanning, or@Beanmethods on user classes lands in pass one.
Q5 · Design. "Design a company-wide 'platform starter' that every one of our 80 Boot services depends on: standard logging, metrics tags, security defaults, and an HTTP client. How do you build it so teams can override pieces without forking it?"
Reveal answer
Strong answer Requirements first:
- Every service gets the same defaults with zero configuration.
- Any team can replace any single piece.
- Upgrades roll out by bumping one version.
- The starter must not slow startup or leak into service packages.
Design: two artifacts, following Boot's own split.
platform-autoconfigureholds the code. It has one@AutoConfiguration(proxyBeanMethods = false)class per concern. Each is guarded by@ConditionalOnClassfor its dependency and by@ConditionalOnProperty(name = "platform.metrics.enabled", matchIfMissing = true)as a kill switch. Every@Beaninside is guarded by@ConditionalOnMissingBeanso a team's own bean wins.- Registration goes through the imports file, never component scan, so the ordering rule from Q4 holds.
- Configuration is exposed as validated
@ConfigurationProperties("platform.*")records with documented defaults. Metadata generated byspring-boot-configuration-processorlets IDEs autocomplete them. platform-starteris the empty dependency-only artifact services declare.
Customisation hooks use Boot's customizer pattern. Expose a RestClientCustomizer, a MeterRegistryCustomizer, and a SecurityFilterChain with an @Order that leaves room for a team's chain to run first.
Trade-offs: conditions add a little startup cost. Every override path is an API you must keep stable. Version the starter with the Boot line it targets, one branch per Boot major.
What I would not do:
- Put
@ComponentScanin the library. - Use
@Primaryin it. - Read properties with
@Value.
Each of those takes the override decision away from the consuming team.
Picture it One starter bean, two teams, and the two phases that decide whether the starter's default or the team's own bean wins.
The setup One concern of the starter, registered through the imports file.
@AutoConfiguration(proxyBeanMethods = false)
@ConditionalOnClass(MeterRegistry.class)
@ConditionalOnProperty(name = "platform.metrics.enabled", matchIfMissing = true)
@EnableConfigurationProperties(PlatformProperties.class)
public class PlatformMetricsAutoConfiguration {
@Bean
@ConditionalOnMissingBean(name = "platformCommonTags") // match by NAME on purpose
MeterRegistryCustomizer<MeterRegistry> platformCommonTags(PlatformProperties props) {
return registry -> registry.config().commonTags("team", props.team());
}
}
com.acme.platform.PlatformMetricsAutoConfiguration
Team B replaces just this piece in its own application:
@Configuration(proxyBeanMethods = false)
class TeamMetricsConfig {
@Bean
MeterRegistryCustomizer<MeterRegistry> platformCommonTags() {
return registry -> registry.config().commonTags("squad", "payments");
}
}
Make the invisible visible The two phases, with what the registry holds at the end of each.
start registry: []
after phase 1 (user config)
team A (no override) registry: []
team B (TeamMetricsConfig) registry: [platformCommonTags (team B's)]
after phase 2 (auto-config, from the imports file)
team A starter adds platformCommonTags (starter's) ✓ default applies
team B @ConditionalOnMissingBean sees the name, backs off ✓ team B's bean wins
What you see
# illustrative output
Negative matches:
PlatformMetricsAutoConfiguration#platformCommonTags:
Did not match:
- @ConditionalOnMissingBean (names: platformCommonTags) found bean 'platformCommonTags' (OnBeanCondition)
(logging, security and HTTP client auto-configurations: unchanged, still positive matches)
Why Phase 1 always finishes before phase 2 starts, so the starter's question is asked after every team bean exists. Matching by name keeps an unrelated second customizer from switching the whole default off.
When it goes wrong
| Symptom | Root cause | Action |
|---|---|---|
| Starter bean and the team bean both exist | Starter configuration reached through @ComponentScan or a plain @Import, so it ran in the early phase | Register it only through the imports file |
| Whole metrics default vanishes when a team adds an unrelated customizer | @ConditionalOnMissingBean matches by type | Match by bean name |
| Team cannot override a piece | Starter bean has no @ConditionalOnMissingBean, or uses @Primary | Add the guard; drop @Primary |
| Startup creeps up across 150 starter classes | CGLIB subclass per configuration class | proxyBeanMethods = false on every one |
Land it A good starter is a set of defaults that lose every argument with the application, and the imports-file ordering is what lets them lose gracefully.
- "A team wants to replace only the metrics tagging but keep everything else. Walk me through exactly what they write and what your starter does in response."
The starter's metrics auto-configuration declares a
MeterRegistryCustomizer<MeterRegistry>bean namedplatformCommonTags, guarded by@ConditionalOnMissingBean(name = "platformCommonTags"). The team writes their own@Bean MeterRegistryCustomizer platformCommonTags()in their application.Because their configuration is processed in the early phase and the starter's in the late phase, the condition sees their bean and the starter's method is never called. Nothing else changes: logging, security, and the HTTP client auto-configurations are separate classes with separate conditions.
I match on bean name rather than type on purpose, because there can legitimately be several customizers and matching on type would make the whole platform back off the moment a team added one unrelated customizer.
- "The requirement changes: security defaults must be mandatory and not overridable. How does the design change?"
Then the security piece stops being a backing-off default and becomes an enforced baseline, which is a different mechanism.
I would ship a
SecurityFilterChainat a fixed low@Orderwith a request matcher for the paths the platform owns, such as Actuator and health, so a team's chain cannot claim them, and I would drop the@ConditionalOnMissingBeanon it.For headers and session policy that must apply to every chain, I would register a
WebSecurityCustomizeror a sharedHttpSecuritycustomizer that the platform applies through aBeanPostProcessoron every chain bean.And I would add an
ApplicationRunnerthat fails startup if the expected chain is missing, so an accidental exclusion is loud. The trade-off is that mandatory pieces are no longer "lose every argument", so they must be small and well documented.- "What would you cut if you had two weeks instead of two months?"
I would cut the configuration metadata polish, the kill switches per concern, and the HTTP client piece entirely, in that order.
The metadata and kill switches are convenience, and the HTTP client is the piece most likely to be argued over per team, so it delays adoption.
I would keep the two-artifact split, the imports-file registration, and the
@ConditionalOnMissingBeanon every bean, because those are the structural decisions that cannot be retrofitted without breaking consumers.I would also keep one thing people cut first: a
@SpringBootTestin the starter's own build that boots a sample application against the starter, because without it every Boot patch release becomes a fleet-wide surprise.- "How do you version and roll this out to 80 services without a big-bang?"
The starter's version tracks the Boot line it supports, for example
platform-starter 4.1.xfor Boot 4.1, with the Boot BOM imported so teams cannot mix versions.Rollout goes through a canary list: five low-risk services adopt a new starter release first, run for a week, and only then does the version appear in the recommended parent POM or Gradle catalog.
Adoption is measured, not assumed: the starter registers an
InfoContributorthat reports its own version on/actuator/info, and a fleet dashboard scrapes it, so I can see which services are on which version.Breaking changes in the starter get a deprecation cycle of at least one minor version with a startup WARN naming the removed property or bean.
Q6. "Walk me through the bean lifecycle in order, and say which hook you would use for what."
Reveal answer
Strong answer Before any bean exists, the container runs every BeanFactoryPostProcessor. It can read and rewrite bean definitions. Property placeholder resolution and @ConfigurationProperties binding registration happen here.
Then, for each singleton in dependency order:
- The constructor runs with resolved constructor arguments.
- Field and setter injections are applied.
- The
Awarecallbacks give the bean its name, itsBeanFactory, and theApplicationContextif it asked. - Every BeanPostProcessor's
postProcessBeforeInitializationruns. @PostConstructruns, thenInitializingBean.afterPropertiesSet, then anyinitMethod.- Every post-processor's
postProcessAfterInitializationruns. This is where AOP proxies, transaction proxies, and async proxies wrap the object. - The result is stored in the singleton map.
On shutdown, @PreDestroy, DisposableBean.destroy, and destroyMethod run in reverse creation order.
What to use:
- The constructor for everything that only needs its dependencies, because it is testable without Spring.
@PostConstructonly for work that needs all injections complete, such as validating a combination of settings.- An
ApplicationRunneror anApplicationReadyEventlistener for work that needs the whole context and may take time, such as warming a cache. - A
BeanPostProcessorwhen you want to wrap or inspect every bean of some type, which is rare in application code.
Picture it One bean that logs from every hook, so the order and the moment the proxy appears are printed rather than described.
The setup A bean with a hook at every step, and a post-processor that watches it.
@Service
public class OrderService implements InitializingBean, DisposableBean, BeanNameAware {
OrderService(Clock clock) { log("1 constructor"); }
@Autowired void setRepo(OrderRepo repo) { log("2 setter injection"); }
public void setBeanName(String n) { log("3 BeanNameAware: " + n); }
@PostConstruct void pc() { log("5 @PostConstruct, class=" + getClass().getSimpleName()); }
public void afterPropertiesSet() { log("6 afterPropertiesSet"); }
@PreDestroy void pd() { log("8 @PreDestroy"); }
public void destroy() { log("9 DisposableBean.destroy"); }
@Transactional public void place() { } // makes Spring wrap this bean in a proxy
}
@Component
class Spy implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object b, String n) {
if (b instanceof OrderService) log("4 BPP before: " + b.getClass().getSimpleName());
return b;
}
public Object postProcessAfterInitialization(Object b, String n) {
if (b instanceof OrderService) log("7 BPP after: proxy is created around the bean here"); // ✓ proxy appears
return b;
}
}
Make the invisible visible The four phases the container runs through.
phase 0 BeanFactoryPostProcessors rewrite bean DEFINITIONS (no beans exist yet)
phase 1 per singleton: new -> inject -> Aware -> BPP.before -> @PostConstruct
-> afterPropertiesSet -> initMethod -> BPP.after (proxy) -> singleton map
phase 2 context ready: SmartInitializingSingleton, ContextRefreshedEvent,
ApplicationRunner, ApplicationReadyEvent
phase 3 shutdown, reverse creation order: @PreDestroy -> destroy() -> destroyMethod
What you see
# illustrative output
1 constructor
2 setter injection
3 BeanNameAware: orderService
4 BPP before: OrderService
5 @PostConstruct, class=OrderService <- raw object, no proxy exists yet ✗ annotations do nothing here
6 afterPropertiesSet
7 BPP after: proxy is created around the bean here <- OrderService$$SpringCGLIB$$0 from now on ✓
... context ready ...
8 @PreDestroy
9 DisposableBean.destroy
Why The proxy is created in the very last initialisation step, so everything before it, including @PostConstruct, runs on the raw object.
The fix Put each job in the hook that matches what it needs.
| Job | Hook | What is guaranteed there |
|---|---|---|
| Use dependencies, build state | Constructor | Dependencies resolved; testable without Spring |
| Validate a combination of settings | @PostConstruct | All injections done; bean still raw |
| Inspect other beans that are fully wired and proxied | SmartInitializingSingleton | Every non-lazy singleton created |
| Warm a cache, call transactional code | ApplicationRunner or ApplicationReadyEvent listener on another bean | Whole context up; calls go through proxies |
| Wrap or inspect every bean of a type | BeanPostProcessor | Runs around every bean |
What you see now The same bean, called from an ApplicationReadyEvent listener on another bean.
# illustrative output
in @PostConstruct class=OrderService transaction active: false
from the listener class=OrderService$$SpringCGLIB$$0 transaction active: true ✓
Land it The one fact that matters most is that a bean inside @PostConstruct is not yet proxied, so anything relying on its own annotations does not work there.
- "Where does
@ConfigurationPropertiesbinding happen in that sequence, and why does that matter for validation?" Binding is done by
ConfigurationPropertiesBindingPostProcessor, aBeanPostProcessor, in itspostProcessBeforeInitializationstep. So for a class-based properties bean the constructor runs first with no values, then binding fills the fields, then@PostConstructruns.That order is why validation with
@Validatedon the properties class is applied during binding, before@PostConstruct, and why a constructor-bound record, the recommended form, is different: the binder calls its constructor with the resolved values directly, so validation runs before the object even exists.It also means a
@PostConstructthat reads another bean's properties is safe, but a constructor that reads its own field-bound properties is not, because they are still null.- "Which hook would you use to close resources on shutdown, and what happens if it takes too long?"
@PreDestroyon the owning bean, or an explicitdestroyMethodon the@Beanannotation; Boot also infersclose()andshutdown()methods by name.Destruction runs in reverse creation order on the thread that closes the context, after the embedded server has stopped accepting requests if graceful shutdown is on.
The time budget is
spring.lifecycle.timeout-per-shutdown-phase, default 30 seconds, applied to eachSmartLifecyclephase; beans in the same phase are stopped concurrently and the context waits up to that limit.If Kubernetes'
terminationGracePeriodSeconds, default 30, expires first, the process gets SIGKILL and the remaining@PreDestroymethods never run, so the two numbers must be set together with the pod's budget larger than Boot's.- "You said
@PostConstructruns on the raw object. How would you demonstrate that in a test?" I would write a bean with a
@Transactionalmethod, and in@PostConstructlog boththis.getClass().getName()andTransactionSynchronizationManager.isActualTransactionActive()after calling that method. The class name prints the plain class, not the$$SpringCGLIB$$subclass, and the transaction check prints false.Then I inject the same bean into a test and repeat the two prints through the injected reference: the class name now carries the CGLIB suffix and the transaction is active.
That pair of outputs is the whole proof, and it is a five-minute test I have used to settle the argument with a colleague more than once.
the two printsruns offline# illustrative output in @PostConstruct : class=com.shop.OrderService txActive=false via injected ref : class=com.shop.OrderService$$SpringCGLIB$$0 txActive=true- "What is
SmartInitializingSingleton, and when is it better than@PostConstruct?" It is a callback,
afterSingletonsInstantiated(), invoked once on each bean implementing it after every non-lazy singleton in the context has been created and initialised, but beforeContextRefreshedEvent.It sits between
@PostConstruct, which knows only about this bean, and anApplicationRunner, which knows the whole application is up.It is the right hook when a bean must inspect other beans that are guaranteed to be fully wired and proxied, for example a registry that collects every
@EventListenermethod or everyPaymentProviderimplementation.Spring's own
EventListenerMethodProcessorand the scheduled-annotation processor use it for exactly that reason, because scanning beans for annotations in@PostConstructwould see them half built.
Q7 · Scenario. "Startup fails with 'The dependencies of some of the beans in the application context form a cycle: orderService → inventoryService → orderService'. The code compiled fine yesterday. Walk me through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a constructor-injection cycle. Two beans each need the other before either can be constructed. Since Boot 2.6 circular references are refused by default (
spring.main.allow-circular-references=false). It compiled because Java does not know about the container. - Evidence: the message itself. Boot prints the cycle with the bean names and the constructor parameter that closes it. I check the git log for yesterday's change; someone added a dependency in one direction that already existed in the other.
- Likely causes, ranked:
- A genuine design smell: two services share responsibilities that belong in a third.
- A convenience injection, such as inventory needing one method of orders.
- A self-injection added to work around the self-invocation trap.
- Fix, in order of preference:
- Extract the shared piece into a third bean that both depend on, so the graph becomes a tree.
- Or invert one edge with an application event, so inventory publishes "stock reserved" and orders listens.
- Or, if the code cannot be touched today, mark one constructor parameter
@Lazy. It injects a proxy that resolves the real bean on first call. - Turning
allow-circular-referencesback on is the last resort. It silently relies on field or setter injection and a half-initialised bean.
- Prevention: keep constructor injection everywhere, since it makes cycles fail loudly at startup instead of surfacing as a null field in production. A context-loading test in CI catches it before merge.
Picture it Two constructors that wait for each other, the startup failure they print, and the graph before and after the fix.
The setup
@Service
class OrderService {
OrderService(InventoryService inventory) { } // orderService -> inventoryService
}
@Service
class InventoryService {
InventoryService(OrderService orders) { } // inventoryService -> orderService ❌ TRAP: closes the loop
}
The trace Neither constructor can finish first.
create orderService
└─► constructor needs inventoryService, so create it first
└─► constructor needs orderService
└─► orderService is still being created: its constructor has not returned ✗ nothing to hand over
What you see
# illustrative output
APPLICATION FAILED TO START
Description:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| orderService defined in file [.../OrderService.class]
↑ ↓
| inventoryService defined in file [.../InventoryService.class]
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default.
Update your application to remove the dependency cycle between beans.
Why A constructor-injected bean cannot exist until all its arguments exist, so a loop has no first bean.
The fix Extract the shared piece into a third bean. The short-term alternative is @Lazy on one parameter.
@Service
class StockReservation { } // new bean, depends on neither service
@Service
class OrderService {
OrderService(StockReservation stock) { } // ✅ FIX: orderService -> stockReservation
}
@Service
class InventoryService {
InventoryService(StockReservation stock) { } // ✅ FIX: inventoryService -> stockReservation
}
// Stop-gap if the refactor cannot land today:
// OrderService(@Lazy InventoryService inventory) // injects a proxy, resolves on first call
What you see now The graph is a tree and the context starts.
before: orderService <──► inventoryService ✗ cycle
after: orderService ──► stockReservation <── inventoryService ✓ no cycle
When it goes wrong
| Symptom | Root cause | Action |
|---|---|---|
| Startup fails with the cycle message | Two constructors depend on each other | Extract a third bean, or invert one edge with an event |
Another cycle appears after one @Lazy | The graph held a cluster of three or four classes | Draw the graph from /actuator/beans; extract the shared logic |
| Cycle exists in production, not in tests | Tests load a slice or mock one side | One full-context @SpringBootTest in CI |
Land it The cycle error is the framework doing you a favour, and the fix is nearly always a missing third class rather than a flag.
- "You added
@Lazyon one constructor parameter and now a different cycle appears. What next?" That means the graph had more than one cycle, and breaking one edge exposed the next.
I would stop patching edges and draw the graph:
/actuator/beanslists every bean with its dependencies, and a small script or a graph tool can find all strongly connected components in a minute.Usually there is a cluster of three or four service classes that all call each other, which is a single missing abstraction, not several.
I would extract the shared logic into a new bean with no dependencies on the others, so the cluster becomes a star around it.
If that refactor cannot land today, the temporary measure is
@Lazyon every edge of the cluster with a ticket and a date, and never the globalallow-circular-referencesflag.- "What exactly does the container do when
allow-circular-referencesis true, and why can it produce a bean that bypasses@Transactional?" With the flag on, the container resolves a cycle among field- or setter-injected singletons by handing out an early reference from a singleton factory, a callback that returns the partially constructed instance before initialisation and before post-processing.
If the bean is meant to be proxied, the container tries to create the proxy early through
SmartInstantiationAwareBeanPostProcessor.getEarlyBeanReference.That works for standard AOP, but if a later post-processor wraps the bean again, the early reference the other bean holds is a different object from the final one, and the container throws "has been injected into other beans in its raw version".
When it does not throw, the risk is that one participant holds a raw reference and its calls skip the transaction interceptor. With constructor injection there is no early reference, so the whole mechanism is off the table.
the failure when it does throwruns offline# illustrative output BeanCurrentlyInCreationException: Error creating bean with name 'orderService': Bean with name 'orderService' has been injected into other beans [inventoryService] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean.- "How does the event-based fix change behaviour, and what are its costs?"
Publishing an
ApplicationEventfrom inventory and handling it in orders replaces a direct method call with an indirect one throughApplicationEventMulticaster.By default the listener runs synchronously on the publishing thread and inside the same transaction, so behaviour is nearly identical to the direct call, but the compile-time dependency is gone.
The costs: the call is no longer visible in the IDE's call hierarchy, exceptions in the listener propagate back to the publisher unless it is
@Async, and ordering among several listeners needs@Order.If I use
@TransactionalEventListenerthe handler runs after commit, which is safer for side effects but means the publisher cannot observe the result. I reserve the event approach for genuinely one-directional notifications and use the extracted-third-bean approach when the two sides actually need each other's results.- "The cycle only shows up in production and not in tests. How is that possible?"
Tests probably load a smaller context. A
@WebMvcTestor a@DataJpaTestslice only creates the beans in its slice, and a test with@MockitoBeanon one of the two services replaces it with a mock that has no dependencies, which severs the cycle.Profiles can do the same: if
InventoryServicehas a@Profile("!test")variant with an extra dependency, the cycle exists only outside tests.The verification is simple: a single
@SpringBootTestwith the production profile's bean set and no mocks, run in CI. If that is too slow to run on every commit, run it nightly, but run it, because the context that goes to production must have been loaded at least once by a machine that is not production.
Q8. "Constructor injection versus field injection: give me the mechanical reasons, not the style ones."
Reveal answer
Strong answer Four mechanical differences.
- Timing: constructor arguments are resolved before the object exists, so a constructor-injected bean is never observable in a half-built state. A field-injected bean exists with null fields until the injection step runs. Any code that runs in between, including a super-constructor, sees nulls.
- Immutability: constructor injection lets the fields be
final, which the JVM treats as safely published across threads without further synchronisation. - Cycles: constructor injection makes a circular dependency fail at startup with a clear message. Field injection lets the container break the cycle by handing out an early, unproxied reference. That is how you end up with a bean holding a reference that bypasses
@Transactional. - Testing and reflection: a constructor can be called from a plain unit test with mocks. Spring's AOT engine can generate direct constructor calls for native images. Field injection needs reflection with
setAccessibleand reflection hints.
The cost of constructor injection is a long parameter list, which is honest feedback that the class has too many responsibilities.
Setter injection has one legitimate niche: optional dependencies with a sensible default.
Picture it The same class built both ways, with the state of its field printed at each moment.
The setup The code below: field injection first, constructor injection second.
// ❌ TRAP — FIELD INJECTION
@Service
public class OrderService {
@Autowired private PaymentGateway gateway; // set by reflection, AFTER construction
public OrderService() {
gateway.warmUp(); // ❌ TRAP: NullPointerException, it is still null here
}
}
// - cannot be final, so the field is mutable for the object's whole life
// - no way to construct it in a plain unit test without reflection
// - hides that this class needs 9 collaborators; the constructor stays empty
// - circular dependencies are resolved silently instead of failing at startup
// Result: NullPointerException while the bean is being created
// ✅ FIX — CONSTRUCTOR INJECTION
@Service
public class OrderService {
private final PaymentGateway gateway; // final: assigned once, visible safely
public OrderService(PaymentGateway gateway) { // single ctor -> @Autowired optional
this.gateway = gateway;
gateway.warmUp(); // Result: guaranteed non-null
}
}
// - the object is fully valid the moment it exists
// - `new OrderService(fake)` in a test, no Spring at all
// - a 9-argument constructor is ugly ON PURPOSE: it is the class telling you it does too much
Read the last comment. The strongest mechanical argument is the one about design feedback: field injection lets a class accumulate dependencies invisibly, while a constructor makes the growth impossible to ignore in review.
Make the invisible visible The gateway field, moment by moment.
field injection constructor injection
t0 new OrderService() t0 resolve PaymentGateway first
gateway = null t1 new OrderService(gateway)
t1 constructor body runs: gateway is null ✗ gateway = PaymentGatewayImpl ✓
t2 container sets gateway by reflection t2 bean published, always fully built
(only now is the object valid)
What you see
# illustrative output
BeanInstantiationException: Failed to instantiate [com.shop.OrderService]: Constructor threw exception
Caused by: java.lang.NullPointerException:
Cannot invoke "com.shop.PaymentGateway.warmUp()" because "this.gateway" is null
at com.shop.OrderService.<init>(OrderService.java:7)
Why The container can only set a field after the constructor has returned, so the constructor body always sees null.
The fix Constructor injection, as in the second class of the code block.
What you see now
# illustrative output
OrderService constructed, gateway warmed up
unit test: new OrderService(fakeGateway) ✓ no Spring, no reflection
Land it Choose constructor injection because it turns wiring mistakes into startup failures instead of runtime nulls, which is the only kind of failure you want from a container.
- "You said final fields are safely published. What does that mean at the JVM level, and does it still matter with Spring's singletons?"
The Java Memory Model guarantees that if a constructor writes a
finalfield and the object reference is published afterwards, any thread that obtains that reference sees the field's value, even without synchronisation.For non-final fields there is no such guarantee unless the publication itself uses a lock or a volatile. In Spring's case the singleton map is a
ConcurrentHashMap, and the request threads obtain the bean through it, so publication is already safe in practice.But the final-field guarantee still matters in two places: beans created outside the container with
new, and any place where a reference escapes during construction, such as a bean registering itself in a static registry.Making the fields final costs nothing and removes the reasoning burden, which is why I do it regardless.
- "When is a class with a twelve-parameter constructor acceptable?"
Almost never for a service, and sometimes for a facade or a controller that genuinely orchestrates many collaborators.
The honest check is whether the class uses all twelve in most methods, or whether each method uses two or three of them; the second case is several classes wearing one name.
Two mechanical ways to shrink it without hiding the problem: group related collaborators into a small holder record, for example a
Clientsrecord with the three outbound clients, which is still constructor-injected and still testable; or use Spring Framework 6.1's@Autowiredon a record-style constructor with Lombok's@RequiredArgsConstructorto remove the boilerplate.What I would not do is switch that class to field injection to make the parameter list disappear, because the coupling is still there, only invisible.
- "Does constructor injection change anything for AOT and native images?"
Yes, and it is one of the reasons the Spring team pushes it. Spring AOT generates a Java source class per bean that calls the constructor directly:
new OrderService(inventoryService, clock), resolved at build time. That is plain compiled code with no reflection hints needed.For field injection, AOT must instead emit reflection hints for each field and generate code that calls
Field.setat runtime, which adds to the image's metadata and is slower to start. Setter injection is in between.The difference is small per bean, but a service with 400 beans notices it in both image size and startup, and constructor injection also avoids a whole category of missing-hint errors in native mode.
- "How do you handle optional dependencies with constructor injection?"
Three ways, and I pick by intent.
Optional<MetricsPublisher>as a constructor parameter is resolved to empty when no bean exists, which is readable and explicit.ObjectProvider<MetricsPublisher>is better when the dependency is expensive or when I want to defer the lookup, sincegetIfAvailable()resolves lazily.optional dependency, two formsruns offlineOrderService(Optional<MetricsPublisher> metrics) { // empty when no bean exists this.metrics = metrics; } OrderService(ObjectProvider<MetricsPublisher> provider) { // lookup deferred until used provider.ifAvailable(p -> p.publish("started")); }And
@Autowired(required = false)on a constructor parameter, or@Nullableon it, injects null. I avoid the null version because it moves the check to every use site.For a truly optional feature I usually prefer a no-op implementation registered by a condition, so the consuming class always has a non-null collaborator and the branching lives in the configuration rather than in the business method.
Q9. "What does @Configuration(proxyBeanMethods = false) change, when is it safe, and why does Boot use it everywhere?"
Reveal answer
Strong answer A normal @Configuration class is subclassed with CGLIB. The subclass intercepts a call from one @Bean method to another and redirects it to the container, which returns the singleton instead of running the method again. That is what makes this.dataSource() inside jdbcTemplate() return the shared pool.
With proxyBeanMethods = false the class is used as-is:
- No subclass is generated.
- Each
@Beanmethod is invoked once by the container. - Any direct call between them runs the body and creates a fresh object the container does not know about.
It is safe exactly when no @Bean method calls another. Dependencies are passed as method parameters instead, which the container resolves.
Boot's auto-configurations use it everywhere for three reasons:
- Generating a CGLIB subclass per configuration class costs measurable startup time when there are hundreds.
- The subclass is impossible in a native image without extra work.
- The parameter style makes the dependency graph explicit.
The trap is a developer who later adds a direct call between methods in such a class and gets two pools without any error. That is why the Boot team recommends the parameter style as a habit rather than a per-class decision.
Picture it The subclass CGLIB generates written out as code, and the same call traced with and without it.
The setup The code below: orderMapper() calls objectMapper() directly, first under the default, then in the parameter style.
@Configuration // proxyBeanMethods = true by default
public class AppConfig {
@Bean ObjectMapper objectMapper() { return new ObjectMapper(); }
@Bean OrderMapper orderMapper() {
// ❌ TRAP: this is a PLAIN JAVA CALL. With the proxy, it is intercepted and
// returns the singleton from the container instead of a new instance.
return new OrderMapper(objectMapper());
}
}
// Result with proxyBeanMethods = true : one ObjectMapper. The class is CGLIB-subclassed.
// Result with proxyBeanMethods = false: TWO ObjectMappers — the second is not managed,
// so no BeanPostProcessors ran on it. ❌
@Configuration(proxyBeanMethods = false) // "lite" mode: no subclass, faster startup
public class AppConfig {
@Bean ObjectMapper objectMapper() { return new ObjectMapper(); }
// ✅ FIX: ask for the bean as a parameter and the container injects it.
// Result: one ObjectMapper, with or without the CGLIB subclass.
@Bean OrderMapper orderMapper(ObjectMapper objectMapper) {
return new OrderMapper(objectMapper);
}
}
The rule that falls out: proxyBeanMethods = false is safe exactly when no @Bean method calls another one directly. Boot uses it throughout its own auto-configurations because they are written in the parameter style, and it removes a CGLIB subclass per configuration class at startup.
Make the invisible visible What the generated subclass looks like, written as pseudo-Java.
// proxyBeanMethods = true: Spring defines this class at runtime and instantiates IT as the configuration
class AppConfig$$SpringCGLIB$$0 extends AppConfig {
@Override
ObjectMapper objectMapper() {
if (beanFactory.containsSingleton("objectMapper")) {
return beanFactory.getBean("objectMapper"); // container's singleton, body skipped
}
return super.objectMapper(); // first call only: runs the body once
}
}
The trace The same line, objectMapper() inside orderMapper().
proxyBeanMethods = true
container ──► orderMapper()
└─► this.objectMapper() intercepted by the subclass ✓ returns the container's singleton
proxyBeanMethods = false
container ──► orderMapper()
└─► this.objectMapper() plain Java call ✗ new ObjectMapper, unknown to the container
What you see
# illustrative output
proxyBeanMethods = true
AppConfig class : AppConfig$$SpringCGLIB$$0
same ObjectMapper? : true
proxyBeanMethods = false
AppConfig class : AppConfig
same ObjectMapper? : false <- expected: <ObjectMapper@5a2e> but was: <ObjectMapper@7c3d>
Why Without the subclass nothing sits between the two methods, so objectMapper() is just a Java method that builds a new object each time.
The fix The parameter style in the second half of the code block: ask for the bean as a parameter and the container injects it.
What you see now
# illustrative output
proxyBeanMethods = false, parameter style
AppConfig class : AppConfig (no subclass generated)
same ObjectMapper? : true ✓
Land it Use proxyBeanMethods = false as the default for new configuration classes and inject through parameters, and the question of inter-bean method calls never arises.
- "How would you detect the 'two pools' bug in a codebase that already has
proxyBeanMethods = falseeverywhere?" Two ways. The cheap check is a metric:
hikaricp.connectionsis tagged by pool name, and Hikari names unnamed poolsHikariPool-1,HikariPool-2, so a second pool appears in the dashboard as a pool nobody declared.metrics scraperuns offline# illustrative output hikaricp_connections{pool="HikariPool-1"} 10 hikaricp_connections{pool="HikariPool-2"} 10 <- a pool nobody declared ✗The structural check is static: an ArchUnit rule that finds every class annotated
@Configuration(proxyBeanMethods = false)and fails if any method annotated@Beanin it calls another@Beanmethod of the same class.ArchUnit can express that with method-call analysis in about ten lines, and it runs in the unit-test phase. Spring itself only warns at runtime when the
@Configurationis proxied and a@Beanmethod is final or private, which does not cover this case.- "What is the actual startup saving, and is it worth the risk in application code?"
Generating one CGLIB subclass costs roughly a millisecond or two on a warm JIT and more during startup, plus a class definition that stays in metaspace. For an application with 20 configuration classes that is under 50 milliseconds, which is not worth a debate.
For Boot's own 150 or so auto-configurations, plus a native image where CGLIB generation at runtime is impossible, it is significant, which is why Boot uses it everywhere.
My position for application code is that the flag is fine and the parameter style is a good habit, but I would not do a sweeping change to an existing codebase just for the milliseconds, because the failure mode of a missed inter-method call is silent. I introduce it for new classes and for anything targeting native.
- "Does the proxying affect
@Beanmethods declared in a@Componentrather than a@Configuration?" Yes: that is called lite mode. A
@Beanmethod on a@Component, or on any class that is not@Configuration, behaves exactly as ifproxyBeanMethods = false: no subclass, direct calls create new objects. Spring documents this as "bean lite mode".It is a common source of the two-pools bug because the author believed
@Beanalone implied the singleton redirect.The visible clue is that a lite-mode class can have
@Beanmethods that are private or final, which a full@Configurationwould reject at startup with aBeanDefinitionParsingException.So if I see
@Beanon a@Servicein code review, I ask whether that was a deliberate choice.
Q10 · Scenario. "A cache-warming method annotated @Transactional(readOnly = true) is called from @PostConstruct in the same class. It runs, but Hibernate logs 'no transaction is in progress' and lazy collections throw. Explain and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the annotation is present but no transaction exists during the call. Two independent reasons apply here, and either alone is enough.
- Evidence: enable
logging.level.org.springframework.transaction.interceptor=TRACE. If the warm-up call never logs "Getting transaction for", the proxy was not involved. - Causes:
- Self-invocation:
@PostConstructruns inside the raw object, and a call to the annotated method onthisnever reaches the transaction proxy. - Timing: even a call through the proxy would fail here, because
@PostConstructruns beforepostProcessAfterInitialization, so the proxy does not exist yet for this bean. - Readiness of infrastructure: during construction, the
EntityManagerFactoryand other infrastructure may not be fully ready either.
- Self-invocation:
- Fix:
- Move the warm-up to an
ApplicationRunneror an@EventListener(ApplicationReadyEvent.class)method in a different bean, which then calls the cache service through its proxy. - Alternatively use
TransactionTemplateprogrammatically inside the runner, which needs no proxy at all. - Mark the warm-up as non-blocking for readiness if it is slow, or run it on a separate thread so the service becomes ready first.
- Move the warm-up to an
- Prevention: a rule in code review that
@PostConstructnever does I/O and never calls annotated methods. A startup test that asserts the cache is populated afterApplicationReadyEvent.
Picture it The moment the proxy is created, set against the moment the warm-up runs, and the log lines that prove it.
The setup The code below: the broken CacheService first, then the two fixes.
// ❌ TRAP — two independent reasons, either one is enough to fail.
@Service
public class CacheService {
@PostConstruct
void warm() {
loadAll(); // ❌ TRAP (1) self-invocation: never touches the proxy
} // (2) @PostConstruct runs BEFORE the proxy exists at all
@Transactional(readOnly = true)
public void loadAll() { ... } // Result: annotation might as well be a comment, no transaction
}
// ✅ FIX A — a different bean, after the context is fully up.
@Component
public class CacheWarmer {
private final CacheService cacheService; // injected = the PROXY
CacheWarmer(CacheService cacheService) { this.cacheService = cacheService; }
@EventListener(ApplicationReadyEvent.class)
void warm() {
cacheService.loadAll(); // Result: goes through the proxy, transaction starts
}
}
// ✅ FIX B — no proxy needed at all.
@Component
public class CacheWarmer {
private final TransactionTemplate tx;
private final CacheRepository repo;
@EventListener(ApplicationReadyEvent.class)
void warm() {
tx.executeWithoutResult(status -> repo.loadAll()); // Result: transaction opened by the template
}
}
Read why Fix A works and moving the method alone would not. The call must cross a bean boundary — cacheService.loadAll() on an injected reference hits the proxy, whereas this.loadAll() from anywhere inside the same object never can, no matter which lifecycle hook it is called from.
The trace
container ──► new CacheService() raw object
└─► @PostConstruct warm() raw object, proxy does not exist yet
└─► this.loadAll() ✗ plain call, no TransactionInterceptor
container ──► postProcessAfterInitialization proxy wraps the raw object, too late for warm()
...
ApplicationReadyEvent ──► CacheWarmer.warm()
└─► cacheService.loadAll() injected reference = the proxy
└─► TransactionInterceptor: begin transaction ✓
└─► target.loadAll()
What you see
# illustrative output, TRACE on org.springframework.transaction.interceptor
(no "Getting transaction for [com.shop.CacheService.loadAll]" line at all)
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:
com.shop.Category.products: could not initialize proxy - no Session
Why The annotation is advice applied by the proxy. A call on this during @PostConstruct never meets the proxy, and the proxy does not exist yet.
The fix Fix A and Fix B in the code block: a different bean, after the context is up, or a TransactionTemplate.
What you see now
# illustrative output, TRACE on org.springframework.transaction.interceptor
Getting transaction for [com.shop.CacheService.loadAll]
cache warmed: 1204 entries
Completing transaction for [com.shop.CacheService.loadAll]
Land it Two rules cover this and a dozen similar bugs: annotations only work through the proxy, and the proxy does not exist until initialisation is finished.
- "You moved it to an
ApplicationRunnerand it still says 'no transaction is in progress'. What next?" Then the call from the runner is still not reaching the transaction proxy. I would check three things in order.
First, whether the runner calls the annotated method through an injected reference to a different bean, not a method on itself; if the warm-up method lives on the runner class, moving it did not change the self-invocation.
Second, whether the method is public and non-final, because CGLIB skips final methods silently. Third, whether the annotation is on an interface method while the bean was proxied by class, since class proxies do not see interface annotations.
If all three pass, I would enable
logging.level.org.springframework.transaction=TRACEand look for "Creating new transaction with name" naming my method; its absence means the interceptor never ran and its presence means the transaction exists and the lazy loading fails for another reason, such as the entity being detached.- "Why not just use
TransactionTemplateeverywhere and avoid proxies entirely?" It is a legitimate style and I use it for exactly this kind of infrastructure code.
TransactionTemplate.execute(status -> …)wraps the lambda in a transaction managed by the injectedPlatformTransactionManager, with no proxy, so self-invocation and lifecycle timing cannot bite, and the transaction boundary is visible in the code.The costs are readability in business code, where dozens of nested lambdas are worse than one annotation, and the loss of declarative attributes like
readOnlyandpropagationin one place, though the template does support them.My rule is annotations for the service layer where calls always come through injected references, and the template for runners, scheduled jobs, message listeners, and anything that needs a transaction boundary smaller than a method.
- "How would you keep readiness honest while a slow warm-up runs?"
Readiness flips to accepting traffic after
ApplicationReadyEvent, which fires after all runners finish. If the warm-up runs inside the runner, readiness stays down until it completes, which is honest but blocks startup.If I move the warm-up to a background thread so startup is fast, I must hold readiness down myself: publish
AvailabilityChangeEvent.publish(context, ReadinessState.REFUSING_TRAFFIC)when the background job starts andACCEPTING_TRAFFICwhen it finishes.The readiness health group reads that state, so Kubernetes routes only after the cache is full. The Kubernetes side needs a startup probe with a
failureThresholdtimesperiodSecondsthat covers the longest warm-up, otherwise the kubelet kills the pod for being unready.- "What is the third problem you mentioned about infrastructure not being ready, precisely?"
During singleton creation, beans are built in dependency order, so when this bean's
@PostConstructruns, only its own dependencies are guaranteed to exist.Things it does not inject may not exist yet: the
EntityManagerFactoryexists if a repository was injected, but the Flyway migration may not have run if nothing forced that ordering, second-level caches may not be started, and@EventListenermethods on other beans are not registered until after all singletons are created.So a warm-up query in
@PostConstructcan run against a schema that is one migration behind, or publish an event nobody hears. That is why the safe hooks for anything touching the database are the ones after the whole context is refreshed.
These questions test whether you know what the container substitutes for your object, when, and what that substitution cannot do.
Q11. "JDK dynamic proxy versus CGLIB proxy: how does each work, what does each refuse to do, and which does Boot pick?"
Reveal answer
Strong answer A JDK dynamic proxy is created by java.lang.reflect.Proxy at runtime. It implements a list of interfaces and routes every interface method to an InvocationHandler.
- It cannot proxy a class, only interfaces.
- So a bean proxied this way can be injected only by its interface type.
- Injecting by the concrete class fails with "bean is of type jdk.proxy2.$Proxy".
A CGLIB proxy generates a subclass of your concrete class at runtime and overrides its methods to route through the interceptor chain. Spring now ships CGLIB inside spring-core as a repackaged copy.
- It refuses
finalclasses. - It cannot intercept
finalorprivatemethods. - It needs a constructor to call, though Spring's Objenesis integration lets it skip running the constructor body.
Boot defaults to CGLIB for everything (spring.aop.proxy-target-class=true), so that injection by concrete type works and behaviour does not change when someone adds an interface.
In a native image neither can be generated at runtime. Spring AOT pre-generates the proxy classes at build time, which is why every proxied bean must be discoverable statically.
Picture it Both proxy classes written out as code, then a table of which call works against which proxy.
The setup The code below: an interface-based bean first, then a class-based bean with final, private and static methods.
// JDK DYNAMIC PROXY — used when the bean implements at least one interface.
// Spring generates a class implementing OrderService and delegating to the target.
public interface OrderService { void place(Order o); }
@Service
class OrderServiceImpl implements OrderService {
@Transactional public void place(Order o) { ... }
public void internalOnly() { ... } // NOT on the interface -> unreachable via proxy
}
// ❌ TRAP: injecting `OrderServiceImpl` fails, the proxy is not an OrderServiceImpl.
// Result: BeanNotOfRequiredTypeException.
// ✅ FIX: always inject the interface.
// CGLIB PROXY — a runtime SUBCLASS of the target class. Boot's default
// (proxyTargetClass = true), so it is what you actually get.
@Service
public class OrderService {
@Transactional public void place(Order o) { ... } // proxied: overridden
@Transactional public final void audit() { ... } // ❌ TRAP: SILENTLY NOT PROXIED
@Transactional private void internal() { ... } // ❌ TRAP: SILENTLY NOT PROXIED
@Transactional static void helper() { ... } // ❌ TRAP: SILENTLY NOT PROXIED
}
// Result: CGLIB works by overriding methods. final, private and static cannot be
// overridden, so the annotation is ignored with no warning at all.
Read the three silent failures. This is the mechanism behind a whole family of "the annotation does nothing" bugs: @Transactional, @Async, @Cacheable and @PreAuthorize all rely on the same overriding trick, and all fail the same quiet way on a final, private or static method.
Make the invisible visible The two generated classes, as pseudo-Java.
// JDK dynamic proxy: implements the INTERFACE, knows nothing about OrderServiceImpl
final class $Proxy37 implements OrderService {
public void place(Order o) { handler.invoke(this, placeMethod, new Object[]{o}); } // advice, then target.place(o)
// internalOnly() does not exist here: it is not on the interface
}
// CGLIB proxy: a SUBCLASS, so it can only override what is overridable
class OrderService$$SpringCGLIB$$0 extends OrderService {
@Override public void place(Order o) { /* advice, then target.place(o) */ }
// audit() is final -> cannot be overridden, not here ✗
// internal() private -> cannot be overridden, not here ✗
// helper() static -> not an instance method, not here ✗
}
What you see
# illustrative output
bean.getClass().getName() jdk.proxy2.$Proxy37 (JDK proxy)
bean.getClass().getName() com.shop.OrderService$$SpringCGLIB$$0 (CGLIB proxy)
inject OrderServiceImpl while the bean is a JDK proxy:
BeanNotOfRequiredTypeException: Bean named 'orderServiceImpl' is expected to be of type
'com.shop.OrderServiceImpl' but was actually of type 'jdk.proxy2.$Proxy37'
Why A JDK proxy is a sibling of your class under the interface, not a subclass of it. A CGLIB proxy can only change what a subclass may override.
The fix Inject the interface for a JDK proxy, and on a class-based bean never put final on advised methods or the class.
What you see now The same calls against each proxy kind, with @Transactional on each method.
| Code line | JDK proxy (interface) | CGLIB proxy (class) |
|---|---|---|
orderService.place(o), public, on the interface | Advice runs | Advice runs |
orderService.internalOnly(), not on the interface | Not callable through the interface type | Not applicable: class is the type |
orderService.audit(), final | Not applicable | Silently not applied |
internal(), private | Not applicable | Silently not applied |
helper(), static | Not applicable | Silently not applied |
Field of type OrderServiceImpl | Throws BeanNotOfRequiredTypeException | Works |
Field of type OrderService (interface) | Works | Works |
Land it Say "class-based proxies by default, so no final on beans" and you have covered the practical consequence most teams learn the hard way.
- "A bean is injected by its interface, and someone adds
spring.aop.proxy-target-class=false. What breaks and where?" Every proxied bean that implements an interface becomes a JDK proxy of that interface only. Any injection point that asks for the concrete class now fails at startup with "bean is of type jdk.proxy2.$Proxy37 but was expected to be of type OrderServiceImpl".
Tests that autowire the implementation class fail the same way. Beans with no interface still get CGLIB, because a JDK proxy is impossible for them, so the failure is selective and confusing.
Methods that exist on the class but not on the interface become unreachable through the proxy.
startup failureruns offline# illustrative output Field orderService in com.shop.OrderController required a bean of type 'com.shop.OrderServiceImpl' that could not be found. (or) BeanNotOfRequiredTypeException: Bean named 'orderServiceImpl' is expected to be of type 'com.shop.OrderServiceImpl' but was actually of type 'jdk.proxy2.$Proxy37' Beans with no interface still get CGLIB, so only some injection points fail.I would only set that flag for a native-image build where CGLIB proxy hints are a problem, and even then I would prefer fixing the injection types over flipping the global default.
- "What does Objenesis actually do, and why does it matter for a class with a constructor that has side effects?"
Objenesis instantiates a class without calling any of its constructors, using JVM-specific tricks such as
sun.reflect.ReflectionFactoryor serialisation hooks. Spring uses it for CGLIB proxies so the proxy subclass can be created without running the target's constructor a second time.Without it, the proxy creation would invoke the constructor again, so a constructor that opens a connection or increments a counter would do so twice: once for the real bean and once for the proxy.
With Objenesis the proxy is an empty shell that holds a reference to the fully constructed target and delegates every call. The exception is
@Configurationclasses, where the CGLIB subclass is the bean itself, so there the constructor runs once through the subclass.Objenesis is unavailable in a native image, which is one reason proxies there are pre-generated.
- "How do you verify which kind of proxy a given bean got in a running service?"
The quickest is
AopUtils.isJdkDynamicProxy(bean)andAopUtils.isCglibProxy(bean)from a test or a debug endpoint. Without code, the class name tells you: a CGLIB proxy's class name contains$$SpringCGLIB$$as of Spring Framework 6, and a JDK proxy's class name starts withjdk.proxy.checking the proxy kindruns offlineAopUtils.isJdkDynamicProxy(bean); // true for jdk.proxy2.$Proxy37 AopUtils.isCglibProxy(bean); // true for ...$$SpringCGLIB$$0 AopProxyUtils.ultimateTargetClass(bean); // the real class behind the proxy/actuator/beansshows the type Spring registered, which is the target type, not the proxy, so it is less useful. In a debugger, hovering the injected field shows the proxy class immediately. If I need the target,AopProxyUtils.ultimateTargetClass(bean)unwraps it.I use this when a colleague swears an annotation is not firing, because the first question is always "is this object even a proxy".
- "Boot 4 and Spring Framework 7 dropped anything here?"
As of Aug 2026 the model is unchanged: CGLIB remains repackaged inside
spring-core, class proxies remain the Boot default, and JDK proxies remain the fallback for interface-only targets. Two related changes are worth knowing.Spring Framework 6 already moved to its own repackaged CGLIB with Java 17 support and removed the old
spring-cglib-repacknaming.And Spring AOT's generated proxy classes now cover both configuration class proxies and AOP proxies for native, with hints generated automatically for beans the container sees at build time.
The practical rule "no final on beans, no final on advised methods" is exactly as true on Boot 4 as it was on Boot 2.
Q12 · Design. "Design a payment module where five payment providers implement one PaymentProvider interface, new providers can be added by adding a class, and a request picks a provider by name. Use the container, not a switch statement."
Reveal answer
Strong answer Assumptions: providers are stateless singletons, a request names its provider, and adding a provider must not touch existing code.
Design:
- Each provider is a
@ComponentimplementingPaymentProviderwith aString id()method. - A
PaymentRoutertakesList<PaymentProvider>in its constructor. The container fills it with every bean of that type, ordered by@Orderif present. - The router builds a
Map<String, PaymentProvider>keyed byid()once at startup, failing fast on duplicate ids. - Lookup is a map get; unknown ids throw a domain exception.
- A provider that should exist only in some environments carries
@Profileor@ConditionalOnProperty("payments.stripe.enabled"), and the router simply never sees it. - Where two providers compete for the same id, an explicit
@Primaryor a priority method decides.
Trade-offs: injecting the list couples the router to the container's discovery. But the alternative, a registry each provider calls in @PostConstruct, has ordering problems.
What I would not do:
- Inject
ApplicationContextand callgetBean(name)per request, because it hides the dependency and costs a lookup. - Use
@Qualifierper provider in the router, because that reintroduces the switch statement. - Make providers prototype-scoped without a reason.
Picture it What the container injects, the map the router builds from it, and the same request resolved step by step.
The setup One interface, one provider, and the router.
public interface PaymentProvider { String id(); Receipt charge(Money amount); }
@Component
class StripeProvider implements PaymentProvider {
public String id() { return "stripe"; }
public Receipt charge(Money amount) { ... }
}
@Component
class PaymentRouter {
private final Map<String, PaymentProvider> byId;
PaymentRouter(List<PaymentProvider> providers) { // container fills it with EVERY bean of that type
this.byId = providers.stream().collect(
Collectors.toUnmodifiableMap(PaymentProvider::id, p -> p)); // duplicate id: IllegalStateException
}
PaymentProvider route(String id) {
PaymentProvider p = byId.get(id);
if (p == null) throw new UnknownProviderException(id);
return p;
}
}
Make the invisible visible The list the container hands to the constructor, and the map built from it.
# illustrative output
List<PaymentProvider> injected (5 beans)
0 AdyenProvider id=adyen
1 BraintreeProvider id=braintree
2 PaypalProvider id=paypal
3 SquareProvider id=square
4 StripeProvider id=stripe
byId = {adyen=AdyenProvider, braintree=BraintreeProvider, paypal=PaypalProvider, square=SquareProvider, stripe=StripeProvider}
The trace
POST /payments {"provider": "stripe"}
└─► PaymentController.pay()
└─► router.route("stripe") map get ✓ StripeProvider
└─► provider.charge(amount)
POST /payments {"provider": "klarna"}
└─► router.route("klarna") map get returns null ✗ UnknownProviderException: klarna
What you see A provider the container does not see never reaches the map.
# illustrative output
List<PaymentProvider> injected (4 beans): adyen, braintree, paypal, square
route("stripe") -> UnknownProviderException: stripe
Why Membership of the list is decided by the container, from classes, profiles and conditions. The router never names a provider.
The comparison Injecting Map<String, PaymentProvider> directly keys it by bean name, so the same rename behaves differently in each design.
| Design | Routing key before | Routing key after | Outcome |
|---|---|---|---|
| Map injected by the container | stripeProvider | stripeGateway | Silently breaks every request that sends the old key |
Map built from the list via id() | stripe | stripe | Unchanged |
When it goes wrong
| Symptom | Root cause | Action |
|---|---|---|
Request for a known provider throws UnknownProviderException | Class lacks @Component, sits outside the scan, or is excluded by @Profile | Add a context test that asserts the map holds the expected ids |
| Startup fails with "Duplicate key" | Two providers return the same id() | Give each a unique id; the fail-fast is deliberate |
| Routing breaks after a class rename | Key taken from the bean name | Build the map from id() |
Land it The container already knows every implementation, so ask it for the list once and let profiles and conditions decide membership.
- "What if two providers need different configuration, say separate API keys and timeouts, and there are 20 of them?"
Then the configuration moves out of code into a map bound by
@ConfigurationProperties("payments"), with aMap<String, ProviderSettings>keyed by provider id, where each entry has the key, the base URL, and the timeout.Each provider's constructor takes the properties bean and reads its own entry by id, failing fast at startup if the entry is missing.
For 20 providers I would stop writing one class per provider and instead have one
HttpPaymentProviderclass that is instantiated once per map entry by aBeanDefinitionRegistryPostProcessoror, more simply, by a@Bean List<PaymentProvider>method that maps the entries.The router does not change: it still receives the list. Adding a provider is then a YAML entry, and the "add a class" requirement becomes "add a class only when the behaviour differs".
- "The requirement changes: the selection must happen at runtime by tenant, with a fallback provider if the primary fails. What changes?"
The router grows a policy. It takes a
TenantProviderPolicythat maps tenant to an ordered list of provider ids, backed by a cached configuration table rather than static properties so it can change without a deploy.The
chargemethod walks the list: attempt the first provider inside a Resilience4j circuit breaker named per provider; if the breaker is open or the call fails with a retryable error, move to the next.Idempotency matters here, because a failure after the first provider actually charged must not lead to a second charge, so each attempt carries the same client idempotency key and a provider that returns "unknown outcome" halts the chain rather than falling through.
The container part is unchanged; the interesting new piece is the policy and the ordered failover, and I would write that as plain code with a unit test per outcome.
- "What would you cut if you had a day to ship this?"
I would cut the profile and condition machinery for per-environment membership and the duplicate-id failing check, and ship the list injection, the map by id, and the domain exception for an unknown id. Those three are the core, and they take an hour.
I would keep one test that boots the context and asserts the map contains the expected ids, because that is what catches a provider someone forgot to annotate.
The environment membership can be added when a second environment actually needs a different set, and the duplicate check can be added when a second developer touches the module.
What I would not cut is the interface with the
id()method, because retrofitting it means touching every provider.- "Why is injecting
Map<String, PaymentProvider>directly a worse choice than building the map from the list?" Spring will inject a
Map<String, PaymentProvider>keyed by bean name, and it is tempting. The problem is that the key becomes the bean name, which defaults to the decapitalised class name, soStripeProviderbecomesstripeProvider, and a rename of the class silently changes the routing key.The business identifier belongs in the domain, on the
id()method, not in the container's naming. Building the map from the list also lets me validate the ids, reject duplicates, and normalise case at startup in one place.The bean-name map is fine for internal plumbing where the name is an implementation detail; it is wrong when the key is part of a request contract.
Q13. "Explain bean scopes, and precisely how a request-scoped bean can be injected into a singleton without breaking."
Reveal answer
Strong answer The scope decides how many instances exist and how long each lives.
singleton, the default, is one instance per container, created eagerly at startup and shared by everyone.prototypecreates a new instance on every injection orgetBeancall. The container does not track prototypes after creation, so@PreDestroynever runs for them.- The web scopes,
request,session, andapplication, hold one instance per HTTP request, per user session, or per servlet context. They are stored in the request or session attributes.
The problem: a singleton is constructed once. If the container injected a request-scoped bean directly, the singleton would keep the instance from the first request forever.
The solution is a scoped proxy. With @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS) the singleton receives a CGLIB proxy. Every method call on that proxy looks up the current request's instance through RequestContextHolder and delegates.
The same trick, or an ObjectProvider<T> that you call getObject() on, handles prototypes in singletons. Boot 3 also has @RequestScope and @SessionScope as shorthand with the proxy mode preset.
Picture it The stand-in object written out as code, then two concurrent requests and an @Async call traced through it.
The setup Using the code under "Going deeper" below: a request-scoped CurrentUser injected into the singleton AuditService.
Make the invisible visible What the injected proxy looks like, as pseudo-Java.
class CurrentUser$$SpringCGLIB$$0 extends CurrentUser { // injected ONCE into AuditService
@Override
public String getUserId() {
CurrentUser real = beanFactory.getBean("scopedTarget.currentUser"); // asks the request scope
return real.getUserId(); // delegate to this request's instance
}
}
The trace
request 1 (http-nio-8080-exec-3) request 2 (http-nio-8080-exec-7)
AuditService.record("login") AuditService.record("export")
└─► proxy.getUserId() └─► proxy.getUserId()
└─► request scope of request 1 └─► request scope of request 2
└─► CurrentUser@3f2 (alice) ✓ └─► CurrentUser@9ab (bob) ✓
@Async thread (task-1)
AuditService.record("nightly")
└─► proxy.getUserId()
└─► no request bound to this thread ✗ ScopeNotActiveException
What you see
# illustrative output
INFO alice performed login
INFO bob performed export
on the @Async thread:
ScopeNotActiveException: Error creating bean with name 'scopedTarget.currentUser':
Scope 'request' is not active for the current thread; consider defining a scoped proxy ...
Caused by: IllegalStateException: No thread-bound request found
Why The proxy has the singleton's lifetime and looks up the real instance on every call, through a thread-local that only request threads have.
The fix Read what the async work needs on the request thread and pass it as a plain value.
String userId = currentUser.getUserId(); // on the request thread: proxy works
executor.submit(() -> auditService.recordFor(userId, "nightly")); // no scoped bean touched here
What you see now
# illustrative output
INFO [task-1] alice performed nightly ✓
Going deeper Two precisions worth having ready.
@RequestScope,@SessionScope, and@ApplicationScopeare Spring Framework annotations, present since Framework 4.3, not a Boot 3 addition. They presetproxyMode = TARGET_CLASSso the scoped proxy is on by default.- The request scope works only on threads where
RequestContextHolderhas been populated. TheDispatcherServletand Boot'sRequestContextFilterdo that for the request thread.
On an @Async thread, a @Scheduled thread, or a Kafka listener, calling any method on the scoped proxy throws ScopeNotActiveException with "No thread-bound request found".
Spring MVC's async support propagates the context for DeferredResult and Callable returns. RequestContextHolder.setRequestAttributes(attrs, true) makes it inheritable to child threads.
For executor threads the honest fix is to read what you need on the request thread and pass a plain value.
// ❌ TRAP — the singleton is created once at startup, when no request exists.
@Component
public class AuditService { // singleton
private final CurrentUser currentUser; // request-scoped
// Result: BeanCreationException: Scope 'request' is not active for the current thread
}
// ✅ FIX — a scoped proxy. The singleton holds a permanent stand-in object;
// every method call on it looks up the real bean for the CURRENT request.
@Component
@RequestScope // shorthand for @Scope(value="request", proxyMode=TARGET_CLASS)
public class CurrentUser {
private String userId;
public String getUserId() { return userId; }
}
@Component
public class AuditService {
private final CurrentUser currentUser; // this is the PROXY, injected once
AuditService(CurrentUser currentUser) { this.currentUser = currentUser; }
public void record(String action) {
// resolved per call, on the calling thread, from the request scope
log.info("{} performed {}", currentUser.getUserId(), action);
}
}
The proxy is what makes the lifetimes compatible. A singleton may hold a reference for hours; a request bean lives milliseconds. The stand-in has the singleton's lifetime and the real object's behaviour, resolved fresh on every call — and it fails if you call it on a thread with no request bound, which is exactly the @Async bug in Q66.
Land it Whenever a longer-lived bean depends on a shorter-lived one, something must resolve the short-lived instance per call, and that something is the scoped proxy.
- "What happens if you call a request-scoped bean's method from an
@Asyncmethod?" It throws. The scoped proxy resolves the current instance by calling
RequestContextHolder.currentRequestAttributes(), which reads a thread-local set by the servlet filter on the request thread.The
@Asyncexecutor thread has no such thread-local, so the lookup fails withScopeNotActiveExceptionwhose message says no thread-bound request is found.The fix is not to propagate the request into the executor, because the request may have finished by the time the task runs and the servlet container reuses the request object.
Instead, read whatever the async work needs from the request-scoped bean before submitting, pass it as a plain parameter, and let the async method be independent of the request. That also makes the async method testable without a servlet environment.
- "What is the cost of the scoped proxy per call, and where does the instance actually live?"
Each call on the proxy goes through a CGLIB method interceptor that asks the
RequestScopefor the object by bean name.RequestScopestores instances as attributes on the currentHttpServletRequest, under a key derived from the bean name, and creates one on first access with the usual initialisation callbacks.The lookup is a thread-local read plus a hash map get on the request attributes, so it is well under a microsecond and not worth worrying about. The instance is destroyed when the request completes, and
@PreDestroyruns then via the request's destruction callback.Session scope is the same idea with the
HttpSessionas the store, which is why session-scoped beans need to be serialisable if you use Spring Session with Redis.- "Why does
prototypeskip@PreDestroy, and what does that mean for a prototype that holds a connection?" The container hands out a prototype and forgets it; there is no registry of prototype instances, because tracking every one would leak memory for beans that callers may discard freely. So the container cannot know when to call
@PreDestroy, and it does not.If a prototype holds a resource, the caller owns the cleanup: call
close()explicitly, wrap it in try-with-resources, or register it with aDestructionAwareBeanPostProcessor-based tracker, which the reference documentation describes for exactly this.In practice a prototype with a resource is a design smell; the resource belongs in a singleton pool and the short-lived object should borrow from it.
- "How would you create a custom scope, for example a 'job' scope for a batch run?"
I implement
org.springframework.beans.factory.config.Scope:get(name, objectFactory)returns the instance for the current job or creates one,remove(name)discards it, andregisterDestructionCallbackstores callbacks to run when the job ends. The current job is identified by a thread-local or aScopedValuethat the batch runner sets.I register it with a
CustomScopeConfigurerbean mapping the name"job"to the instance, and beans use@Scope(value = "job", proxyMode = TARGET_CLASS).Spring Batch ships this exact thing as
@JobScopeand@StepScope, so for batch I would use those rather than write my own; the custom scope is worth writing for something like a "message" scope in a consumer.
Q14 · Scenario. "A developer marks a stateful ReportBuilder as @Scope("prototype") so each caller gets a fresh one. In production, reports from different users are mixing data. What happened?"
Reveal answer
Strong answer In diagnosis order:
- Symptom: shared mutable state across requests, which means one
ReportBuilderinstance is being reused. - Evidence: log
System.identityHashCode(this)in the builder, or inspect the injecting bean with the/actuator/beansendpoint. The builder is injected into a singletonReportServiceby plain constructor injection. - Cause: prototype scope means "new instance per injection point", not "per call". The singleton service was created once at startup, received one prototype instance then, and has used that same instance for every request since. The scope annotation did exactly what it says; the expectation was wrong.
- Fix, in order of preference:
- Make
ReportBuildernot a bean at all. A stateful builder with a short life is a plain object created withnewinside the method. - Or inject
ObjectProvider<ReportBuilder>and callgetObject()per request. - Or, if it needs request context, make it request-scoped with a scoped proxy.
- Make
- Prevention: a review rule that beans are stateless unless the scope and proxy mode say otherwise. A concurrency test that runs two reports in parallel and checks isolation.
Picture it The one builder instance every request shares, with the hash code and the mixed rows printed.
The setup The code below: the broken ReportService first, then the three fixes.
// ❌ TRAP — "prototype" only means "a new one each time it is REQUESTED".
// A singleton requests it exactly once, at startup, and then holds that one forever.
@Service
public class ReportService { // singleton
private final ReportBuilder builder; // @Scope("prototype")
ReportService(ReportBuilder b) { this.builder = b; } // ONE builder, shared by all threads
public Report build(Query q) {
return builder.reset().apply(q).build(); // ❌ TRAP: race, two requests, one builder
// Result: reports from different users mix
}
}
// ✅ FIX 1 — ObjectProvider: ask for a fresh instance per call. My default.
@Service
public class ReportService {
private final ObjectProvider<ReportBuilder> builders;
ReportService(ObjectProvider<ReportBuilder> builders) { this.builders = builders; }
public Report build(Query q) {
return builders.getObject().apply(q).build(); // Result: new instance per call
}
}
// ✅ FIX 2 — a scoped proxy on the prototype bean, same mechanism as request scope.
@Component @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ReportBuilder { ... }
// ✅ FIX 3 — the honest one: stop making it a bean.
public Report build(Query q) {
return new ReportBuilder().apply(q).build(); // it has no dependencies; just construct it
}
Fix 3 deserves the most consideration. A stateful builder with no injected collaborators does not need to be a bean at all, and making it one bought nothing but this bug.
Make the invisible visible How many builders exist, and who holds them.
startup: ReportService (singleton) ──holds──► ReportBuilder@1a2b3c4d (the only one ever created)
request A (thread exec-1) builder.reset().apply(qA) ──► ReportBuilder@1a2b3c4d
request B (thread exec-2) builder.reset().apply(qB) ──► ReportBuilder@1a2b3c4d ✗ same object
What you see
# illustrative output
[exec-1] build user=alice builder=1a2b3c4d
[exec-2] build user=bob builder=1a2b3c4d <- same hash code on both requests
report returned to alice: rows = [alice-1, bob-1] ✗ contains bob's data
report returned to bob: rows = [alice-1, bob-1] ✗ contains alice's data
Why The singleton asked for a ReportBuilder once, at startup, and prototype scope hands out a new object only when it is asked.
The fix Fix 1, 2 or 3 in the code block above. The honest one is Fix 3, not a bean.
What you see now
# illustrative output
[exec-1] build user=alice builder=5e91c0aa
[exec-2] build user=bob builder=77d3b4f1 <- different instance per call
report returned to alice: rows = [alice-1] ✓
report returned to bob: rows = [bob-1] ✓
Land it Prototype scope answers "how many when injected", and the answer for a singleton consumer is "one, forever", so short-lived state usually should not be a bean.
- "You switched to
ObjectProvider.getObject()per request and the data mixing stopped, but now memory climbs slowly. What next?" A prototype obtained per request is created every time and never tracked, so a leak means something is holding on to the instances. Two usual suspects. First, the builder registers itself somewhere long-lived, such as a listener list or a static cache, and nothing removes it.
Second, the builder is a proxied bean, say with
@Transactionalmethods, and each prototype carries its own CGLIB proxy plus advisor chain, which is small but adds up under a metric that showsReportBuilder$$SpringCGLIBinstances accumulating.I would take a heap histogram with
jcmd <pid> GC.class_histogramand look for the builder's class count growing between two samples five minutes apart. If it grows, find the retaining path with a heap dump.two histogram samplesruns offline# illustrative output num #instances #bytes class name 7: 41230 1319360 com.shop.ReportBuilder <- sample 1 7: 118944 3806208 com.shop.ReportBuilder <- sample 2, five minutes later: growing, something retains themIf the class carries proxies it did not need, drop the annotations and the proxy disappears.
- "Why do you prefer 'not a bean' over a request-scoped bean here?"
A bean earns its place by needing something from the container: injection of collaborators, a lifecycle, or a scope tied to a container-managed context. A stateful builder that lives for one method call needs none of those.
Making it a bean adds a proxy, a scope lookup per call, and a dependency on
RequestContextHolderthat breaks the moment the report is generated from a scheduled job instead of a request.A plain
new ReportBuilder(dependencies)inside the service method, with the collaborators it needs passed in from the service's own injected fields, is simpler, thread-safe by construction, and testable with no container.I reach for request scope only when the object must be shared across several beans within one request, such as a per-request tenant context.
- "How would you write the test that proves the isolation?"
A test that runs two report generations concurrently with different inputs and asserts each output contains only its own data.
Concretely: an
ExecutorServicewith two threads, twoCompletableFutures each callingreportService.generate(userA)andgenerate(userB)with aCountDownLatchinside a test double of the repository to force both to be mid-flight at the same time, then assertions that report A has no rows tagged B.Run it a hundred times in a loop, because a race that appears one time in twenty will pass a single run.
This is a cheap test to keep, and it turns "we think the fix worked" into a reproduction you can rerun after every refactor of that class.
- "Does
@Lookupstill exist, and would you use it?" It does. An abstract method annotated
@Lookupon a bean is overridden by a CGLIB subclass that callsgetBeaneach time, returning a fresh prototype per call. It works and it predatesObjectProvider.I would not choose it in new code, because it requires the class to be non-final and proxied even if nothing else about it needs a proxy, it does not work in a native image without extra hints, and the abstract method reads as strange to a newcomer.
ObjectProvider<ReportBuilder>expresses the same intent as a plain constructor parameter, works everywhere including AOT, and givesgetIfAvailableandstreamfor free.
Q15. "When would you turn on spring.main.lazy-initialization=true, and what does it cost you?"
Reveal answer
Strong answer Lazy initialisation defers creating each singleton until it is first needed, instead of building all of them at startup. Startup gets faster, sometimes by half, and memory at rest is lower because unused beans are never built.
I would turn it on for developer machines and for test runs, where fast restarts matter and full correctness at startup does not.
The costs in production are real:
- You lose fail-fast. A misconfigured bean that would have crashed the service at startup, where the deployment would have been rolled back, now crashes the first request that touches it, which is a user-facing error.
- The first request pays. The first request to touch a heavy subsystem pays the construction cost, so your p99 after deploy shows a latency spike that is hard to attribute.
- Readiness lies. The pod reports ready while half its beans do not exist.
If a specific bean is genuinely expensive and rarely used, mark that one bean @Lazy and keep the global default eager.
Since Boot 2.2 there is also @Lazy(false) to opt individual beans out of a global lazy setting, which is the tool for keeping Actuator and health indicators eager under a lazy default.
Picture it The same service with lazy off and on, with startup, first request and bean counts read at three moments.
The setup One property, and the per-bean alternative.
spring:
main:
lazy-initialization: true # every bean definition becomes lazy
Make the invisible visible The number of singletons that actually exist, and what the metrics read.
# illustrative output eager lazy
startup finished 6.2 s 3.1 s
singletons created 212 of 212 47 of 212
readiness UP UP <- but 165 beans do not exist yet
first POST /orders 40 ms 3.0 s <- builds EntityManagerFactory, pool, clients
after a few hundred requests 212 of 212 203 of 212
The trace The first request on a lazy instance.
POST /orders
└─► OrderController not created yet, create it now
└─► OrderService not created yet, create it now
└─► EntityManagerFactory ✗ built on the user's request: 2.6 s of the 3.0 s
What you see A bad property is found by a user instead of by the deployment.
# illustrative output
eager: startup fails, deployment rolled back, no user affected ✓ fail-fast
lazy: startup succeeds, readiness UP, first request that touches it: 500 ✗ user-facing
Why Laziness moves construction, and every construction error, from startup to the first call.
The fix Keep the global default eager. Defer only the heavy bean, and keep the health indicators eager if a global lazy setting is used.
@Component
@Lazy // only this expensive, rarely used bean is deferred
class PdfRenderer { }
@Bean
static LazyInitializationExcludeFilter eagerHealthIndicators() { // only needed under a global lazy setting
return LazyInitializationExcludeFilter.forBeanTypes(HealthIndicator.class);
}
When it goes wrong
| Symptom | Root cause | Action |
|---|---|---|
| p99 spikes right after every deploy | First requests build lazy beans | Keep heavy beans eager, or warm them before readiness |
| First health probe times out | Health indicators are lazy and all built on the probe | @Lazy(false) or an exclude filter |
| A misconfiguration reaches production | Fail-fast lost | CI smoke test that boots the context and touches the lazy bean once |
Land it Global laziness trades a known startup cost for unknown request-time costs, which is the wrong direction for anything behind a readiness probe.
- "Which beans does Boot itself keep eager under a global lazy setting, and how?"
Boot's
LazyInitializationBeanFactoryPostProcessormarks every bean definition lazy, then consults a list ofLazyInitializationExcludeFilterbeans and leaves alone anything a filter matches.Boot registers filters for the infrastructure it knows must be eager:
SmartInitializingSingletonimplementations, the task scheduler and scheduled-annotation processor so@Scheduledjobs still start, the embedded server, and the Actuator endpoints.An application adds its own by declaring a
@Bean LazyInitializationExcludeFilter, for exampleLazyInitializationExcludeFilter.forBeanTypes(HealthIndicator.class). That is the mechanism behind the advice to keep health indicators eager: without it, the first probe pays construction cost for every indicator and can time out.- "How much startup does it actually save, and how would you measure it honestly?"
It depends entirely on what fraction of beans are heavy and unused at startup. Typical services see 20 to 50 percent, because the expensive beans, pools, entity managers, and clients are also the ones touched on the first request.
I would measure with Boot's startup timeline: enable
BufferingApplicationStartup, read/actuator/startup, and compare thespring.beans.instantiatesteps eager versus lazy.Then, and this is the honest part, I would measure the first-request latency for the main endpoints with lazy on, because that is where the saved time went.
If the first request moved from 40 milliseconds to 3 seconds, the setting did not save anything for a Kubernetes pod behind a readiness probe; it moved the cost to a user.
- "Is there a middle ground for a service with a genuinely slow, rarely used subsystem?"
Yes: per-bean laziness.
@Lazyon the heavy bean's class or@Beanmethod defers only that bean, and@Lazyon the injection point in its consumer injects a proxy so the consumer itself stays eager. Everything else keeps fail-fast behaviour.For a subsystem, I put
@Lazyon its configuration class, which marks every bean declared in it lazy.The remaining risk is that the lazy bean's misconfiguration is discovered on first use, so I add a smoke test in CI that boots the context and explicitly touches that bean once, which restores the fail-fast property without paying for it in production startup.
- "What does lazy initialisation change for a native image or the JDK AOT cache?"
For a native image the bean definitions are still resolved at build time, so laziness only defers instantiation, exactly as on the JVM, and the startup saving is smaller because native startup is already tens of milliseconds. For the JDK AOT cache introduced with JDK 24 and 25, which snapshots loaded and linked classes from a training run, laziness works against you: classes not loaded during the training run are not in the cache, so a lazy bean's first use on a cold instance pays class loading that an eager start would have cached. The way to have both is a training run that exercises the lazy paths, which is one more reason to keep laziness selective rather than global.
Q16 · Scenario. "After adding a shared library, startup fails with 'The bean objectMapper, defined in class path resource [.../JacksonAutoConfiguration.class], could not be registered. A bean with that name has already been defined'. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: two definitions with the same bean name. Since Boot 2.1 bean definition overriding is disabled (
spring.main.allow-bean-definition-overriding=false), so the second registration fails instead of silently replacing the first. - Evidence: the message names both sources. Here the library defined an
ObjectMapperbean namedobjectMapper, and Boot's auto-configuration then tried to define one with the same name. The interesting question is why Boot's@ConditionalOnMissingBeandid not back off. - Likely causes, ranked:
- The library registered its bean through component scanning of a package the application also scans, with a bean name that matches while the type differs, for example a subclass or a
FactoryBean. The condition on type did not match. - The library's configuration is an auto-configuration that is ordered after Boot's, so Boot's definition landed first and the library's collided.
- The library uses an older mechanism that registers definitions directly with a
BeanDefinitionRegistryPostProcessoroutside the ordering rules.
- The library registered its bean through component scanning of a package the application also scans, with a bean name that matches while the type differs, for example a subclass or a
- Fix:
- Have the library declare
@AutoConfiguration(before = JacksonAutoConfiguration.class)and use@ConditionalOnMissingBeanitself. - Or rename its bean and let the application choose with
@Primary. - Better still, the library should not define an
ObjectMapperat all but aJsonMapper.Buildercustomizer (Boot 4) orJackson2ObjectMapperBuilderCustomizer(Boot 3), which composes with Boot's mapper. - Turning on overriding is the wrong fix because it makes the outcome depend on load order.
- Have the library declare
- Prevention: the library ships a context test against the Boot versions it supports.
Picture it The registration order that produces the clash, the failure text, and the registry after the library stops defining a mapper.
The setup The library's auto-configuration, ordered after Boot's, with no guard.
@AutoConfiguration(after = JacksonAutoConfiguration.class) // ❌ TRAP: lands second
public class LibJsonAutoConfiguration {
@Bean
ObjectMapper objectMapper() { // ❌ TRAP: no @ConditionalOnMissingBean
return new ObjectMapper().findAndRegisterModules();
}
}
Make the invisible visible The bean names in registration order.
# bean name used as in the question
1 objectMapper -> JacksonAutoConfiguration registered first
2 objectMapper -> LibJsonAutoConfiguration ✗ name already taken, overriding is disabled
What you see
# illustrative output
APPLICATION FAILED TO START
Description:
The bean 'objectMapper', defined in class path resource [...LibJsonAutoConfiguration.class], could not be registered.
A bean with that name has already been defined in class path resource [...JacksonAutoConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
Why Two definitions claimed one name, and the guard that exists to make ordering accidents loud refused the second.
The fix The library contributes a customizer and never a mapper (Boot 3 form shown).
@AutoConfiguration
public class LibJsonAutoConfiguration {
@Bean // ✅ FIX: customise Boot's mapper, do not define one
Jackson2ObjectMapperBuilderCustomizer libJsonCustomizer() {
return builder -> builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
What you see now
# illustrative output
1 one ObjectMapper bean, defined by JacksonAutoConfiguration
2 libJsonCustomizer applied to it, together with spring.jackson.* properties ✓
context started
When it goes wrong
| Symptom | Root cause | Action |
|---|---|---|
Clash although Boot uses @ConditionalOnMissingBean | Library bean has the same name but a different type, so the type condition does not match | Rename it, or stop defining a mapper |
| Library bean registered after Boot's | Library auto-configuration is ordered after Boot's | before = JacksonAutoConfiguration.class and its own guard |
| Definition appears with no ordering at all | A BeanDefinitionRegistryPostProcessor registers it directly | Exclude it, or replace it with a customizer |
Land it The overriding guard exists to make ordering accidents fail loudly, and the right response is to fix the ordering, not to silence the guard.
- "How do you find out which of the three causes it is in ten minutes?"
Run with
--debugand read two things.In the condition report, find
JacksonAutoConfigurationand itsjacksonObjectMappermethod: if it is in positive matches, Boot's condition did not see the library's bean, which means the library registered in the late phase or by a mechanism outside the ordering rules.Then search the report and the startup log for the library's configuration class name: if it appears as an auto-configuration, check its ordering attributes; if it does not appear at all, it is component-scanned or registered by a registry post-processor.
Finally, put a breakpoint in
DefaultListableBeanFactory.registerBeanDefinitionconditioned onbeanName.equals("objectMapper")and look at the two stack traces; the second one shows exactly who tried to register and from where.- "The library is a third-party jar you cannot change. What do you do today?"
Two safe options.
Exclude the library's configuration class from my component scan with
@ComponentScan(excludeFilters = @Filter(type = ASSIGNABLE_TYPE, classes = TheirJacksonConfig.class))if it arrives through scanning, or exclude it viaspring.autoconfigure.excludeif it is an auto-configuration, and then reproduce whatever it configured as a customizer of my own.Or, if I want their mapper, exclude Boot's
JacksonAutoConfigurationinstead and accept thatspring.jackson.*properties stop working. I would pick the first because Boot's mapper composes with everything else.What I would not do is turn on
spring.main.allow-bean-definition-overriding, because then the winner depends on registration order and a future Boot release changes it silently.- "What did Boot 4 change about how you customise Jackson, and does the bean name still matter?"
As of Aug 2026, Boot 4 targets Jackson 3, whose mapper type is
tools.jackson.databind.json.JsonMapper, built with aJsonMapper.Builder. Boot's auto-configuration creates the builder, appliesspring.jackson.*properties, then calls everyJsonMapperBuilderCustomizerbean in order, and only then builds the mapper.So a library that wants to influence JSON contributes a customizer bean and never a mapper. The auto-configured mapper bean is still named
jsonMapperin Boot 4 andjacksonObjectMapperin Boot 3, and Boot 4 also registers anObjectMapperalias for compatibility.The name still matters for the collision, but the correct design makes the collision impossible because nobody but Boot defines the mapper.
- "What is the actual behaviour when overriding is enabled, and is there ever a case for it?"
With
spring.main.allow-bean-definition-overriding=true, the later registration replaces the earlier one and Spring logs it at INFO as "Overriding bean definition for bean 'objectMapper'". Which one is later depends on the parse order: user configuration before auto-configuration, and among user classes the scan order.The legitimate cases are tests, where
@TestConfigurationoverrides a production bean on purpose and Boot's test support enables it in that narrow case, and a migration where an old XML definition and a new annotation definition coexist for one release.In an application running in production I have never seen a case where the flag was better than fixing the ordering.
Q17. "List the property sources in priority order, and explain relaxed binding well enough that I could set a Hikari property from a Kubernetes environment variable."
Reveal answer
Strong answer From lowest to highest priority, later wins:
SpringApplication.setDefaultProperties.@PropertySourceannotations.application.ymland profile-specific files inside the jar, then the same files outside the jar next to it or under./config/.RandomValuePropertySourceforrandom.*.- OS environment variables.
- Java system properties (
-D). - JNDI.
- Servlet context and config parameters.
SPRING_APPLICATION_JSON.- Command-line arguments.
- Properties from
@SpringBootTestand@TestPropertySource, at the very top in tests.
Relaxed binding means Boot accepts several spellings of the same key:
spring.datasource.hikari.maximum-pool-sizein kebab case.maximumPoolSizein camel case.maximum_pool_sizewith underscores.- For environment variables the canonical form is upper case with dots and dashes replaced:
SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE=8. List indexes use underscores too,MY_LIST_0_NAME.
In a Kubernetes manifest that is one env entry. It overrides whatever the yml inside the jar says, because environment variables sit above packaged files.
When it seems not to work, /actuator/env shows each key with the source that won, and /actuator/configprops shows the bound value the bean actually holds.
Picture it One key looked up through the stack of property sources, with the winner and the shadowed values printed.
The setup The value is 10 in the jar. The Kubernetes manifest sets the pool size to 20.
spring:
datasource:
hikari:
maximum-pool-size: 10
env:
- name: SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE
value: "20"
The relaxed-binding code block follows: five spellings of one key, and the one place relaxed binding does not apply.
# All of these bind to the SAME property. Relaxed binding lowercases,
# strips separators, and treats -, _ and camelCase as equivalent.
spring.datasource.hikari.maximum-pool-size = 20 # canonical (yaml/properties)
spring.datasource.hikari.maximumPoolSize = 20 # camelCase
spring.datasource.hikari.maximum_pool_size = 20 # underscores
SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE = 20 # environment variable
SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE = 20 # also works
# The env-var rule: uppercase, and every non-alphanumeric becomes _
# So in a Kubernetes manifest:
# env:
# - name: SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE
# value: "20"
# ❌ TRAP: relaxed binding applies to @ConfigurationProperties, NOT to @Value.
# @Value("${maximum-pool-size}") is a literal key lookup and will NOT
# find MAXIMUM_POOL_SIZE from the environment.
# Result: @Value misses the relaxed spellings.
# ✅ FIX: bind with @ConfigurationProperties for anything set from the environment.
Read the last three lines. This is the practical reason to prefer @ConfigurationProperties over @Value for anything that might be set from an environment variable in a container — @Value does a literal lookup and silently misses the relaxed spellings.
Make the invisible visible The lookup of one key, from the top of the stack down.
spring.datasource.hikari.maximum-pool-size
command-line args (not set)
SPRING_APPLICATION_JSON (not set)
system properties (-D) (not set)
environment: SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE = 20 ✓ wins
application.yml in the jar = 10 shadowed
What you see First with a typo in the manifest, where the environment variable never matches.
// illustrative output, with management.endpoint.env.show-values=ALWAYS
{ "property": { "source": "Config resource 'class path resource [application.yml]'", "value": 10 },
"propertySources": [
{ "name": "Config resource 'class path resource [application.yml]'", "property": { "value": 10 } } ] }
Why The key was never set in the environment, so nothing sits above the packaged file.
The fix Correct the name in the manifest, then read the same endpoint again. Prefer @ConfigurationProperties over @Value for anything an environment variable may set.
What you see now
// illustrative output, with management.endpoint.env.show-values=ALWAYS
{ "property": { "source": "systemEnvironment", "value": "20" },
"propertySources": [
{ "name": "systemEnvironment", "property": { "value": "20" } },
{ "name": "Config resource 'class path resource [application.yml]'", "property": { "value": 10 } } ] }
Land it The rule to say aloud is "environment beats file, command line beats environment, and Actuator env tells you which one won".
- "The environment variable is set in the pod but
/actuator/configpropsstill shows 10 for the pool size. What next?" Three checks. First, is the variable actually in the process environment:
kubectl execinto the pod and runenv | grep HIKARI, because a typo in the manifest or a missingenvFromis the usual reason.Second, does
/actuator/envlist the key undersystemEnvironmentwith the expected value; if it does but configprops disagrees, the binding target is different from what I assumed, for example the pool was built by hand in a@Beanmethod that never had@ConfigurationProperties("spring.datasource.hikari")on it, so Boot's properties are not applied to it at all.Third, is a higher source overriding it: a
-Dsystem property in the container'sJAVA_TOOL_OPTIONS, orSPRING_APPLICATION_JSON, both of which sit above plain environment variables.- "How do you set a list or a map from environment variables, and where does it get ugly?"
Lists use an index in the name:
APP_ALLOWED_ORIGINS_0=https://a.exampleandAPP_ALLOWED_ORIGINS_1=https://b.examplebind toapp.allowed-origins[0]and[1]. Maps work when the key is simple:APP_LIMITS_GOLD=1000binds toapp.limits.gold.It gets ugly when a map key contains characters that the environment cannot express, such as a dot or a dash, because environment names cannot carry them and relaxed binding lowercases everything, so the key
eu-west-1becomeseuwest1.For those cases I use
SPRING_APPLICATION_JSON='{"app":{"limits":{"eu-west-1":1000}}}', which is a single environment variable holding JSON that Boot parses into a property source, or a mounted YAML file added throughspring.config.import=file:/etc/app/limits.yml.- "What does
spring.config.importdo, and how is it different fromadditional-location?" spring.config.importis declared inside a configuration file and pulls in another source, which is then processed as if it came later in the same file, so imported values override the importer.It supports plain files,
optional:prefixes so a missing file is not fatal, aconfigtree:loader that turns a directory of Kubernetes secret files into properties with the file name as the key, and extension loaders for Vault and Config Server.spring.config.additional-locationis set from outside, on the command line or in the environment, and adds file locations to the search path before the defaults.The difference is who decides: the import is the application's decision written in its own config, and the additional location is the operator's.
- "Which property source wins between a profile-specific file inside the jar and a plain
application.ymloutside the jar?" The outside file, and it is a common surprise. Boot processes locations in order, and for each location it loads the plain file and then the profile-specific files, with profile-specific overriding plain within that location. But a later location overrides all files of an earlier location.
The default order is classpath root, then
classpath:/config/, then the current directory, then./config/, then./config/*/. So./config/application.ymlbeatsclasspath:application-prod.yml, because the external location is processed later. If I want the external override to be profile-aware, I ship./config/application-prod.ymltoo.The way to check is
/actuator/env, which lists each source with its origin and order.config locations, lowest to highestruns offline1 classpath:/application.yml (in the jar) 2 classpath:/config/application.yml 3 ./application.yml 4 ./config/application.yml 5 ./config/*/application.yml highest: beats classpath:application-prod.yml ✓
Q18 · Design. "Design feature flags for a Boot service so that a flag can switch an implementation at startup, and a different kind of flag can be toggled at runtime without a restart."
Reveal answer
Strong answer Two kinds of flag, two mechanisms, because their lifetimes differ.
Startup flags choose which beans exist:
- Mechanism. A
@ConditionalOnProperty(name = "features.new-pricing", havingValue = "true")on the new implementation andmatchIfMissing = trueon the old one. - Wiring. Both implement the same interface, so exactly one is wired.
- Where it fits. Anything that changes wiring, such as a different client or storage.
- Why it is safe. It is evaluated once, so it cannot flip mid-request.
Runtime flags are data, not wiring:
- Backing. A
FeatureFlagsbean backed by a@ConfigurationPropertiesrecord, made refreshable through a flag provider. - Provider. An in-house table polled every 30 seconds, or a vendor SDK such as OpenFeature with a provider.
- API.
boolean isEnabled(String key, Context ctx), so percentage rollouts and per-tenant targeting are possible. - Effect. Code branches on the call; nothing is rewired.
Around both kinds:
- Visibility. Both kinds are surfaced through a custom Actuator endpoint so operators can see current values.
- Metrics. Every evaluation emits a Micrometer counter tagged by flag and outcome, so a bad rollout is visible in the same dashboard as the latency it causes.
- Trade-off. Runtime flags accumulate; each needs an owner and a removal date, tracked in the flag definition.
- Not
@RefreshScope. I would not use Spring Cloud Config's@RefreshScopeto rebuild beans on the fly for flags, because rebuilding a pool or client mid-traffic is a reliability risk for a problem that a boolean lookup already solves. - Not
@ConditionalOnPropertyfor runtime flags. That cannot change after startup.
Picture it Two flags over time: the startup flag fixes the bean registry once, and the runtime flag is a map lookup whose contents change while the pod runs.
The setup
public interface PricingEngine { Money price(Cart cart); }
// Startup flag: exactly one of these two beans exists in the container
@Service
@ConditionalOnProperty(name = "features.new-pricing", havingValue = "true")
class NewPricingEngine implements PricingEngine { /* ... */ }
@Service
@ConditionalOnProperty(name = "features.new-pricing", havingValue = "false", matchIfMissing = true)
class LegacyPricingEngine implements PricingEngine { /* ... */ }
// Runtime flag: one bean, and the answer is looked up on every call
@Service
class CheckoutService {
private final FeatureFlags flags;
CheckoutService(FeatureFlags flags) { this.flags = flags; }
Receipt checkout(Cart cart, String tenantId) {
if (flags.isEnabled("express-checkout", Context.of(tenantId))) { // data lookup, nothing rewired
return express(cart);
}
return standard(cart);
}
}
Make the invisible visible
# illustrative output
features.new-pricing=true pricingEngine -> NewPricingEngine (LegacyPricingEngine: condition not met, no bean)
features.new-pricing=false pricingEngine -> LegacyPricingEngine (NewPricingEngine: condition not met, no bean)
(property not set) pricingEngine -> LegacyPricingEngine (matchIfMissing = true)
# the runtime flag is not in the registry at all, it is a row in a map:
FeatureFlags.snapshot = { "express-checkout" -> Flag(enabled=true, percentage=10) }
The trace
# illustrative output
t=0s table row: express-checkout enabled=false percentage=0 map snapshot: enabled=false
t=12s operator: UPDATE feature_flags SET enabled=true, percentage=10 WHERE key='express-checkout'
t=12s checkout(tenant-17) --> isEnabled() reads old snapshot --> false (change not polled yet)
t=30s @Scheduled reload --> AtomicReference.set(newMap) readers never block
t=31s checkout(tenant-17) --> isEnabled() --> hash("tenant-17"+key) % 100 = 4 < 10 --> true ✓ no restart
t=31s checkout(tenant-88) --> hash(...) % 100 = 57 >= 10 --> false ✓ 10% rollout
What you see
# illustrative output
t=0s features.new-pricing=false at startup --> LegacyPricingEngine is the only bean
t=12s operator flips the value to true --> price() still goes to LegacyPricingEngine ✗ bean was chosen at startup
t=90s pod restarts --> NewPricingEngine now wired (a restart, so not a runtime flag)
# illustrative output
flag.evaluations{flag="express-checkout",outcome="false"} 1840
flag.evaluations{flag="express-checkout",outcome="true"} 212 # about 10 percent, as configured
Why A startup flag decides which classes become beans, and that decision is made once when the context is built. A runtime flag is a value read per call from a map that a timer replaces, so nothing is rewired and no bean is rebuilt.
The decision table
| Symptom | Root cause | Action |
|---|---|---|
| Flipped a row, nothing changes until restart | The flag was put in @ConditionalOnProperty, which is evaluated once at startup | Move it to an isEnabled lookup |
| Pool or client rebuilt on every flag change | @RefreshScope discards and recreates the bean target | Replace with a map reloaded by a timer |
| Dead branches nobody tests | No owner, no removal date on the flag | Add owner and removal date to the flag definition |
| Bad rollout noticed by customers first | No per-evaluation metric | Counter tagged by flag and outcome on the dashboard |
Land it Decide per flag whether it changes wiring or behaviour, and use the container for the first and a plain lookup for the second.
- "How would you implement the runtime flag provider yourself, without a vendor, in a day?"
A
feature_flagstable with columns for key, enabled, percentage, and an optional JSON of targeting rules.A
FeatureFlagsbean holds anAtomicReference<Map<String, Flag>>and a@Scheduled(fixedDelayString = "${flags.refresh:30s}")method that reloads the table and swaps the reference atomically, so readers never see a half-loaded map and never take a lock.isEnabled(key, ctx)reads the map, applies the percentage by hashing the tenant or user id with the flag key so the same user gets the same answer every time, and returns false for an unknown key.Every evaluation increments a Micrometer counter tagged by key and outcome. A small write endpoint on the management port, with audit, flips a row. That is about 150 lines and covers most teams' needs for years.
the swap that keeps readers lock-freeruns offlineprivate final AtomicReference<Map<String, Flag>> flags = new AtomicReference<>(Map.of()); @Scheduled(fixedDelayString = "${flags.refresh:30s}") void reload() { flags.set(repo.loadAll()); } // build the whole map first, then one atomic swap boolean isEnabled(String key, Context ctx) { Flag f = flags.get().get(key); // never sees a half-loaded map, never locks return f != null && f.enabled() && f.admits(ctx.id(), key); // unknown key: false }- "A runtime flag needs to change a bean's dependency, for example switch from Redis cache to local cache. What do you do?"
I do not rewire the bean. I inject both implementations and make the switch a delegating wrapper: a
SwitchableCachethat holds the Redis-backed and the local-backedCacheand consults the flag per call to pick one.The wrapper is the only bean the rest of the code sees, so nothing is rebuilt and both implementations are fully initialised and verified at startup.
The trade-off is that both must be able to run, so both pools exist; that is the cost of an instant switch.
delegating wrapperruns offline@Component @Primary class SwitchableCache implements Cache { private final Cache redis, local; private final FeatureFlags flags; // both built and verified at startup public Object get(String k) { return (flags.isEnabled("redis-cache", Context.none()) ? redis : local).get(k); } }If the intention is really "we will migrate from Redis to local and never go back", it is a startup flag, not a runtime one, and I would use
@ConditionalOnPropertyand a redeploy.- "What would you cut under time pressure, and what would you refuse to cut?"
I would cut percentage rollouts and targeting, shipping boolean on-off only, and I would cut the Actuator endpoint in favour of a direct SQL update by an operator for the first release. I would refuse to cut three things: the atomic swap of the flag map, because a lock in the hot path is a latency bug waiting to happen; the metric per evaluation, because without it a bad flag flip is invisible until customers call; and the owner-and-removal-date fields on the flag, because a flag with no owner lives forever and every one of them is a branch in production code that nobody tests anymore.
- "Why is
@RefreshScopea bad fit for flags, in mechanism?" @RefreshScopefrom Spring Cloud puts the bean behind a scoped proxy whose target is discarded on a refresh event and recreated on the next call.Recreation means the constructor runs again, and if the bean holds a connection pool or a client, the old one is destroyed while requests may still be using it, and every in-flight call after the refresh pays construction cost.
For a flag, which is a boolean, that is a heavy mechanism: the refresh event goes through the bus, invalidates the whole scope, and all refresh-scoped beans rebuild, not just the one that changed.
A lookup in a map that is reloaded by a timer costs nothing per request and touches nothing else, so it is the better fit for data that changes often.
what @RefreshScope does on a flag changeruns offline# illustrative output refresh event --> whole refresh scope invalidated FraudClient (refresh-scoped) target discarded, rebuilt on next call ✗ old pool destroyed while requests may use it ReportClient (refresh-scoped) target discarded, rebuilt on next call ✗ did not change, rebuilt anyway flag lookup instead: map swap, 0 beans rebuilt ✓
Q19. "@PostConstruct, ApplicationRunner, ApplicationStartedEvent, ApplicationReadyEvent: in what order do they fire, and which one is right for warming a cache from the database?"
Reveal answer
Strong answer The order, one hook at a time:
@PostConstruct: runs per bean during that bean's creation, while the context is still being built, so other beans may not exist and this bean is not yet proxied.ContextRefreshedEvent: fires when the context has finished creating all singletons.ApplicationStartedEvent: the embedded server starts and this fires. The port is bound, but Boot considers the application not yet ready.ApplicationRunnerandCommandLineRunner: every one runs, in@Order, on the main thread.ApplicationReadyEvent: fires only after all runners return, and it is the event that flips the Actuator readiness state to accepting traffic.
For cache warming from the database, an ApplicationRunner is the natural choice, for three reasons:
- Everything exists. All beans and proxies are there.
- Transactions work. They go through the proxy of whatever service you call.
- Readiness stays down until warming completes, so Kubernetes does not send traffic to a cold instance.
If warming can take minutes, the trade-off is startup time against a cold first request.
Then I would run it asynchronously from an ApplicationReadyEvent listener and keep the readiness probe down through a custom AvailabilityChangeEvent until the cache reports full, so the service is honest about its state without blocking the main thread.
@Component
public class StartupOrder {
// 1. Bean construction — dependencies injected, nothing else is ready.
public StartupOrder(OrderRepository repo) { }
// 2. @PostConstruct — this bean is initialised. The PROXY DOES NOT EXIST YET,
// and other beans may not be created. Do not do I/O here.
@PostConstruct void init() { }
// 3. ApplicationStartedEvent — context refreshed, all beans ready,
// runners have NOT run yet.
@EventListener(ApplicationStartedEvent.class) void started() { }
// 4. ApplicationRunner / CommandLineRunner — run in @Order sequence.
// An exception here FAILS STARTUP, which is usually what you want.
@Bean ApplicationRunner warmCaches(CacheService cache) {
return args -> cache.loadAll();
}
// 5. ApplicationReadyEvent — everything above finished. The port is open.
// Correct place for: warm-up, scheduled work, registering with discovery.
@EventListener(ApplicationReadyEvent.class) void ready() { }
}
The distinction that matters operationally is between 4 and 5. A slow ApplicationRunner delays readiness, which is right for work that must finish before traffic arrives and wrong for a warm-up that should not block the pod from becoming ready.
Picture it The five callbacks fire in a fixed order, and readiness reads 503 until the last of them.
The setup The code below shows all five callbacks in one class; add a log line to each.
Make the invisible visible
# illustrative output
12:00:01.101 StartupOrder constructor
12:00:01.104 StartupOrder @PostConstruct (this bean is not proxied yet)
12:00:03.870 StartupOrder ApplicationStartedEvent GET /actuator/health/readiness -> 503 OUT_OF_SERVICE
12:00:03.872 warmCaches loading 50000 rows ...
12:00:09.440 warmCaches done in 5568 ms GET /actuator/health/readiness -> 503 OUT_OF_SERVICE
12:00:09.441 StartupOrder ApplicationReadyEvent GET /actuator/health/readiness -> 200 UP
The trace
new StartupOrder(repo) constructor, dependencies injected
└─► init() @PostConstruct ✗ no proxy yet, other beans may not exist, no I/O here
context refreshed, server bound
└─► started() ApplicationStartedEvent ✓ beans ready, runners not run
└─► warmCaches.run(args) ApplicationRunner ✓ proxies and transactions work; exception here fails startup
└─► ready() ApplicationReadyEvent ✓ readiness flips to accepting traffic
Why Readiness is a separate state that Boot flips only when ApplicationReadyEvent fires, so everything before it, including a runner, holds the pod out of rotation. That is a feature for must-finish work and a problem for a slow warm-up.
The fix For a slow warm-up, move it off the main thread and hold readiness down explicitly.
@EventListener(ApplicationReadyEvent.class)
void warmInBackground() {
// readiness has just flipped to ACCEPTING_TRAFFIC, so take it back at once
AvailabilityChangeEvent.publish(publisher, ReadinessState.REFUSING_TRAFFIC);
executor.submit(() -> {
cache.loadAll(); // minutes, off the main thread
AvailabilityChangeEvent.publish(publisher, ReadinessState.ACCEPTING_TRAFFIC);
});
}
What you see now
# illustrative output
12:00:03.870 ApplicationStartedEvent readiness 503
12:00:03.871 ApplicationReadyEvent readiness 200 for a moment, then 503 (REFUSING_TRAFFIC published)
12:00:03.872 warm-up thread loading 50000 rows ... main thread already free
12:03:10.015 warm-up thread done readiness 200 (ACCEPTING_TRAFFIC published)
Comparison
| Where the warm-up code lives | Readiness during warming | If it throws |
|---|---|---|
ApplicationRunner on the main thread | 503 until the runner returns | Startup fails, process exits non-zero |
Synchronous ApplicationReadyEvent listener | Already 200, pod takes traffic while warming | Exception reaches the publisher on the main thread |
@Async listener that publishes REFUSING_TRAFFIC itself | 503 again until it publishes ACCEPTING_TRAFFIC | Only the AsyncUncaughtExceptionHandler sees it |
Land it Pick the hook by what must already exist when your code runs, and remember that readiness is tied to ApplicationReadyEvent, not to the port being open.
- "An
ApplicationRunnerthrows. What does the application do, and is that what you want?" SpringApplication.runcatches the exception, reports it through theFailureAnalyzersand theSpringApplicationRunListeners, firesApplicationFailedEvent, closes the context, and exits with a non-zero code.For a warm-up that is usually what I want, because a service that cannot load its reference data should not take traffic, and Kubernetes will restart it and back off.
For an optional warm-up, I would catch inside the runner, log at ERROR with a metric, and continue, so that a flaky cache source does not cause a crash loop.
The point to say out loud is that runner failures stop the whole application, so the decision "is this warm-up mandatory" must be made explicitly in a try block, not by accident.
what a failing runner printsruns offline# illustrative output ERROR o.s.boot.SpringApplication : Application run failed java.lang.IllegalStateException: failed to run ApplicationRunner (stack trace of the exception thrown in the runner) Process finished with exit code 1 # context closed, Kubernetes restarts the pod with back-off- "What if the cache warming takes 3 minutes and the readiness probe's budget is 60 seconds?"
Then a blocking runner causes the kubelet to kill and restart the pod before it ever becomes ready, which is a crash loop that looks like a slow service. Two fixes, and I would do both.
First, add a startup probe with
failureThreshold: 30andperiodSeconds: 10, giving 5 minutes before liveness even begins, because that is what startup probes are for.Second, move the warm-up to a background thread from an
ApplicationReadyEventlistener and hold readiness down withAvailabilityChangeEventuntil it is done, so the pod is honest but the main thread and the liveness probe are free.If the warm-up is genuinely optional, let the pod go ready and serve cold with a metric on cache hit rate.
probes for a 3-minute warm-upruns offlinestartupProbe: httpGet: { path: /actuator/health/liveness, port: 8080 } periodSeconds: 10 failureThreshold: 30 # 30 x 10 s = 5 minutes before liveness takes over- "Where do
ContextRefreshedEventandWebServerInitializedEventfit, and when would you use them?" ContextRefreshedEventfires at the end ofrefresh(), after all singletons exist andSmartLifecyclebeans have started, but before the web server is listening; in a plain Spring Framework application it is the main "everything is wired" hook.WebServerInitializedEvent, with itsServletWebServerInitializedEventsubclass, fires when the embedded server has bound its port and carries theWebServer, so it is the hook for reading the actual port whenserver.port=0, for registering with a service registry, or for logging the URL.Neither is right for cache warming, because the readiness state is not held down by either;
ApplicationRunnerandApplicationReadyEventare the ones whose timing is tied to readiness.- "Runners run in
@Order. What about listeners on the same event, and can a listener be asynchronous?" Listeners for one event run in
@Orderas well, lowest first, on the thread that publishes the event, which forApplicationReadyEventis the main thread.A listener can be made asynchronous with
@Asyncon the@EventListenermethod if@EnableAsyncis present, and then it runs on the task executor and the publisher does not wait.The subtlety is that exceptions in an async listener are not propagated to anyone except the
AsyncUncaughtExceptionHandler, so a failed async warm-up needs its own logging and metric.Also, an asynchronous listener on
ApplicationReadyEventruns after readiness has already flipped, so it cannot hold traffic back unless it publishes the availability change itself.
Q20 · Scenario. "A pod starts, logs 'Started OrderApplication in 6.2 seconds', Tomcat is on 8080, but Kubernetes never routes traffic to it. /actuator/health/readiness returns 503 with status OUT_OF_SERVICE. Walk through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom: liveness is fine and the context is up, but the readiness group reports the application is not accepting traffic. Since OUT_OF_SERVICE is the readiness group's own state, either Boot's
ApplicationAvailabilitystill saysREFUSING_TRAFFIC, or a health indicator included in the readiness group is down. - Evidence: call
/actuator/health/readinesswithmanagement.endpoint.health.show-details=alwaysto see the components.- If it lists
readinessState: OUT_OF_SERVICEalone, the availability state never flipped. - If it lists
db: DOWNorkafka: DOWN, a custom group membership is pulling the readiness down.
- If it lists
- Likely causes, ranked:
- A hung runner. An
ApplicationRunneris still running or hung, because readiness only flips after all runners return, and "Started in 6.2 seconds" is logged before runners finish. - A widened group. Someone added the database indicator to the readiness group with
management.endpoint.health.group.readiness.include=readinessState,db, and the database is unreachable from this pod. - A deliberate refusal. Code published
AvailabilityChangeEvent.publish(ctx, ReadinessState.REFUSING_TRAFFIC), for example a consumer waiting for a partition assignment, and never published the opposite.
- A hung runner. An
- Fix: thread-dump the pod with
/actuator/threaddumporjcmdto find the stuck runner, typically an HTTP call with no timeout; set timeouts; move slow warm-up off the main thread as in Q19; review the readiness group's membership so only dependencies without which the pod truly cannot serve are included. - Prevention: an alert on pods that are live but not ready for more than two minutes, and a startup budget check in the startup timeline endpoint.
Picture it The main thread is parked inside a runner, so the readiness state never leaves REFUSING_TRAFFIC even though the app logged "Started".
The setup
@Bean
ApplicationRunner loadPartnerData(PartnerClient client) {
return args -> client.fetchAll(); // ❌ TRAP: HTTP call with no timeout, blocks the main thread
// Result: readiness never flips, pod is live but never ready
}
Make the invisible visible
# illustrative output
$ curl -i localhost:8081/actuator/health/readiness
HTTP/1.1 503
{"status":"OUT_OF_SERVICE","components":{"readinessState":{"status":"OUT_OF_SERVICE"}}}
$ curl -i localhost:8081/actuator/health/liveness
HTTP/1.1 200
{"status":"UP"}
The trace
SpringApplication.run()
├─► refresh() ✓ context built, Tomcat on 8080
├─► log "Started OrderApplication in 6.2 seconds" logged BEFORE the runners
├─► callRunners()
│ └─► loadPartnerData.run()
│ └─► client.fetchAll() ✗ no timeout, blocked in a socket read
└─► ApplicationReadyEvent ✗ never reached, readiness stays REFUSING_TRAFFIC
What you see
# illustrative output
"main" #1 prio=5 RUNNABLE
at java.base/sun.nio.ch.SocketDispatcher.read0(Native Method)
...
at com.acme.PartnerClient.fetchAll(PartnerClient.java:41)
at com.acme.OrderApplication.lambda$loadPartnerData$0(OrderApplication.java:27)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:...)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:...)
Why "Started" is logged when the context is built, but ApplicationReadyEvent, which flips readiness, fires only after every runner returns. One runner stuck on a network read keeps the pod alive and out of rotation.
The fix
HttpRequest req = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(5)) // ✅ FIX: request timeout
.build();
HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(2)) // ✅ FIX: connect timeout
.build();
What you see now
# illustrative output
12:00:03 Started OrderApplication in 6.2 seconds
12:00:08 WARN loadPartnerData: partner call timed out after 5 s, continuing without partner data
12:00:08 ApplicationReadyEvent GET /actuator/health/readiness -> 200 {"status":"UP"}
Decision table
| Symptom | Root cause | Action |
|---|---|---|
Only readinessState is OUT_OF_SERVICE, main thread is inside a runner | A runner is hung, so ApplicationReadyEvent never fired | Set timeouts, move slow warm-up off the main thread |
db: DOWN or kafka: DOWN listed in the readiness group | The group was widened with group.readiness.include | Include only dependencies the pod cannot serve without |
readinessState is REFUSING_TRAFFIC and the main thread is idle | Code published REFUSING_TRAFFIC and never the opposite | Grep for AvailabilityChangeEvent.publish, publish ACCEPTING_TRAFFIC when the condition is met |
Land it "Started" means the context is built, not that the app is ready; readiness is a separate state that runners and health groups can hold down.
- "The thread dump shows the main thread idle in
Thread.joinand no runner is stuck. What next?" Then the runners completed and readiness should have flipped, so the readiness group itself is reporting a component down. I would call
/actuator/health/readinesswith details enabled and read the components list.If
readinessStateisACCEPTING_TRAFFICbut the group isOUT_OF_SERVICE, some other indicator is in the group: checkmanagement.endpoint.health.group.readiness.includeacross all property sources with/actuator/env, because a platform starter or a profile file may have addeddborkafka.If the state itself is
REFUSING_TRAFFIC, grep the code forAvailabilityChangeEvent.publishand forReadinessState.REFUSING_TRAFFIC; a consumer or a leader-election component may have published it and never published the opposite because its condition never came true.the two shapes of the details outputruns offline# illustrative output {"status":"OUT_OF_SERVICE","components":{"readinessState":{"status":"OUT_OF_SERVICE"}}} # state itself is REFUSING_TRAFFIC: grep for the publisher {"status":"OUT_OF_SERVICE","components":{"readinessState":{"status":"UP"},"db":{"status":"DOWN"}}} # state fine, a group member is down- "How exactly does the readiness group map the state to an HTTP code, and can you change it?"
The
ReadinessStateHealthIndicatormapsACCEPTING_TRAFFICtoUPandREFUSING_TRAFFICtoOUT_OF_SERVICE. The health endpoint'sHttpCodeStatusMapperthen maps status to HTTP:UPandUNKNOWNto 200,DOWNandOUT_OF_SERVICEto 503. Both mappings are configurable:management.endpoint.health.status.http-mapping.OUT_OF_SERVICE=200changes the code globally, and per-group withmanagement.endpoint.health.group.readiness.status.http-mapping.Aggregation across components uses
management.endpoint.health.status.order, defaultDOWN, OUT_OF_SERVICE, UP, UNKNOWN, so the worst status wins.I would not change the readiness mapping, because 503 is what Kubernetes' probe understands, but a custom
DEGRADEDmapped to 200 is a legitimate addition for a dependency you can serve without.- "Should the database be in the readiness group at all?"
It depends on whether the pod can do anything useful without it, and the answer must be per service.
For an order service where every endpoint writes to the database, a pod that cannot reach the database is useless and readiness should say so, so that traffic goes to pods that can.
The counter-argument is the herd effect: if the database blips for 10 seconds, every pod goes unready at once, the service disappears from the load balancer, and clients see connection errors instead of a few 500s.
For that reason I keep the readiness group to
readinessStateby default, add the database only when the service is purely a database front, and never add external HTTP dependencies, since a partner's outage should not remove our pods.- "What are the Kubernetes probe settings you actually pair with these endpoints?"
Liveness on
/actuator/health/livenesswithperiodSeconds: 10,failureThreshold: 3, and noinitialDelaySecondswhen a startup probe exists. Readiness on/actuator/health/readinesswithperiodSeconds: 5andfailureThreshold: 3, so a pod leaves rotation within 15 seconds of trouble.A startup probe on the liveness path with
failureThresholdset so that the total covers the slowest cold start with margin.Boot's
management.endpoint.health.probes.enabled=trueexposes the two groups automatically on Kubernetes, andmanagement.endpoint.health.probes.add-additional-paths=trueadds/livezand/readyzon the main port for cases where the management port is not reachable by the kubelet.probes in the pod specruns offlinelivenessProbe: { httpGet: { path: /actuator/health/liveness, port: 8080 }, periodSeconds: 10, failureThreshold: 3 } readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 8080 }, periodSeconds: 5, failureThreshold: 3 } # out of rotation within 15 s startupProbe: { httpGet: { path: /actuator/health/liveness, port: 8080 }, periodSeconds: 10, failureThreshold: 30 }
This group tests whether you can trace a behaviour change back to a classpath change, and whether you know the tools that show the container's decisions.
Q21. "What is actually inside spring-boot-starter-data-jpa, and what happens if you exclude HibernateJpaAutoConfiguration?"
Reveal answer
Strong answer A starter is a dependency descriptor with almost no code. spring-boot-starter-data-jpa pulls in:
spring-boot-starter-jdbc, which brings HikariCP andspring-jdbc;hibernate-coreandspring-data-jpa;spring-aspects;- the Jakarta Persistence and Transaction APIs.
Its only role is to make the classes present, so that the relevant @ConditionalOnClass guards match:
DataSourceAutoConfigurationseesDataSourceand creates the pool.HibernateJpaAutoConfigurationseesEntityManagerand Hibernate'sSessionImplementor, and creates theEntityManagerFactoryandJpaTransactionManager.JpaRepositoriesAutoConfigurationsees Spring Data and enables repository scanning.
Exclude HibernateJpaAutoConfiguration and you keep the pool and JDBC, but you lose three things:
- the entity manager;
- the JPA transaction manager;
- every repository, because the repositories auto-configuration is conditional on an
EntityManagerFactorybean.
The service starts if nothing injects those, and otherwise fails with "no qualifying bean of type EntityManagerFactory".
You would exclude it when you want to build the EntityManagerFactory yourself, for multiple databases or a custom persistence unit, and then you also own the transaction manager and repository enablement.
Picture it A starter adds jars, each auto-configuration turns on because of those jars, and excluding the middle one makes the ones after it go quiet.
The setup
@SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class) // ❌ TRAP: takes away the entity manager and its dependents
public class ShopApplication { }
@Service
class OrderService {
OrderService(OrderRepository repo) { } // Result: needs a repository, which needs an EntityManagerFactory
}
Make the invisible visible
spring-boot-starter-data-jpa
├─ spring-boot-starter-jdbc
│ ├─ HikariCP
│ └─ spring-jdbc
├─ hibernate-core
├─ spring-data-jpa
├─ spring-aspects
└─ jakarta.persistence-api, jakarta.transaction-api
# illustrative output
default HibernateJpaAutoConfiguration excluded
dataSource -> HikariDataSource -> HikariDataSource ✓ kept
entityManagerFactory -> LocalContainerEntityManagerFactoryBean -> (absent) ✗
transactionManager -> JpaTransactionManager -> (no JpaTransactionManager) ✗
orderRepository -> proxy of OrderRepository -> (absent) ✗
The trace
spring-boot-starter-data-jpa on classpath
└─► DataSourceAutoConfiguration DataSource present ✓ pool created
└─► HibernateJpaAutoConfiguration EntityManager + SessionImplementor ✓ EMF + JpaTransactionManager
└─► JpaRepositoriesAutoConfiguration needs an EntityManagerFactory bean ✓ repositories scanned
with HibernateJpaAutoConfiguration excluded:
└─► HibernateJpaAutoConfiguration skipped ✗ no EMF, no JPA tx manager
└─► JpaRepositoriesAutoConfiguration no EntityManagerFactory bean ✗ no repositories
What you see
# illustrative output
Description:
Parameter 0 of constructor in com.acme.OrderService required a bean of type 'com.acme.OrderRepository' that could not be found.
Action:
Consider defining a bean of type 'com.acme.OrderRepository' in your configuration.
Why The starter only supplies classes. Each auto-configuration switches on because of what is on the classpath or already registered, so removing one removes everything that was conditional on its beans.
The fix
@Configuration(proxyBeanMethods = false)
@EnableJpaRepositories(basePackages = "com.acme.orders",
entityManagerFactoryRef = "ordersEmf", transactionManagerRef = "ordersTx") // ✅ FIX: you now enable repositories
class OrdersJpaConfig {
@Bean LocalContainerEntityManagerFactoryBean ordersEmf(DataSource ds) { // ✅ FIX: you build the EMF
var emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(ds);
emf.setPackagesToScan("com.acme.orders");
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return emf;
}
@Bean PlatformTransactionManager ordersTx(@Qualifier("ordersEmf") EntityManagerFactory emf) {
return new JpaTransactionManager(emf); // ✅ FIX: you own the tx manager
}
}
What you see now
# illustrative output
dataSource -> HikariDataSource ✓
ordersEmf -> LocalContainerEntityManagerFactoryBean ✓ yours
ordersTx -> JpaTransactionManager ✓ yours
orderRepository -> proxy of OrderRepository ✓ enabled by your @EnableJpaRepositories
Land it A starter is a promise about the classpath, and excluding one auto-configuration means taking over everything that was conditional on its beans.
- "How do you find out what a starter actually brings in, and how do you keep it from bringing too much?"
mvn dependency:tree -Dincludes=org.springframework.bootorgradle dependencies --configuration runtimeClasspathprints the transitive graph under the starter. For the auto-configuration effect rather than the jars, the condition report with--debugshows which classes matched because of that starter.To keep it lean, I exclude what I do not want at the dependency level rather than at the auto-configuration level: for example excluding
spring-boot-starter-tomcatto use Jetty, or excludingspring-boot-starter-loggingto use Log4j2.Excluding jars is better than excluding auto-configurations because a class that is absent cannot be accidentally used by application code either, and the
@ConditionalOnClassguards back off naturally.excluding a jar rather than an auto-configurationruns offline<dependency> <groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> <exclusions><exclusion> <!-- Tomcat classes are gone, so its guards back off --> <groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId> </exclusion></exclusions> </dependency>- "If you exclude
HibernateJpaAutoConfigurationand build theEntityManagerFactoryyourself, what else stops working that you might not expect?" Several things Boot wired for you quietly. The
spring.jpa.*properties are bound by that auto-configuration, sospring.jpa.hibernate.ddl-autoandspring.jpa.properties.*are ignored unless I readJpaPropertiesandHibernatePropertiesmyself and pass them to the builder.The
@DependsOnedge to Flyway or Liquibase is gone, so schema validation can run before migration; I must add it. Hibernate's naming strategies default to Boot'sSpringPhysicalNamingStrategyequivalent only through Boot's vendor adapter, so table names may change from snake_case to the entity name.The open-in-view interceptor, the Hibernate metrics binder, and the
@DataJpaTestslice all depend on the auto-configured beans. Boot's documentation has anEntityManagerFactoryBuilderhelper that recovers most of this, which is what I would use.a property that is silently ignoredruns offlinespring.jpa.hibernate.ddl-auto=validate # bound by HibernateJpaAutoConfiguration # Result with that auto-configuration excluded: no error, no effect, unless you read JpaProperties yourself- "What does
spring-aspectsin that list do, and does anyone need it?" It ships the AspectJ aspects for
@Transactionaland@Configurable, meant for compile-time or load-time weaving as an alternative to proxies. With weaving,@Transactionalworks on private methods and on self-invocation because the advice is woven into the bytecode rather than applied by a proxy.Almost nobody uses it, because it requires the AspectJ compiler or a load-time weaving agent, and Boot's proxy-based transaction management covers the common cases.
It is in the starter because Spring Data JPA's own POM declares it as a dependency for its
@Configurablesupport for domain objects. It is safe to exclude and I sometimes do to shrink the jar, though it is small.- "Boot 4 renamed starters. What does that mean for a dependency upgrade?"
As of Aug 2026, Boot 4 introduced more specific starter names, for example
spring-boot-starter-webmvcalongside the classicspring-boot-starter-web, andspring-boot-starter-data-jpakept its name but pulls in the new per-technology auto-configuration modules such asspring-boot-jpaandspring-boot-hibernate. The classic names still resolve for compatibility.For an upgrade, the practical work is in two places: any explicit dependency on
spring-boot-autoconfigurein your own libraries needs to become the specific module, and any test that imports auto-configurations by class name needs the new package.OpenRewrite's Boot 4 recipe rewrites both, and I would run it rather than edit by hand across a fleet.
Q22 · Scenario. "A team adds spring-boot-starter-security to pull in one password-hashing class. The next morning every endpoint returns 401 and CSRF failures appear in the logs. Nobody wrote any security configuration. Explain, and say what they should have done."
Reveal answer
Strong answer In diagnosis order:
- Symptom: authentication is being enforced where none was configured. The classpath changed, so auto-configuration changed.
- Evidence: the condition report shows
SecurityAutoConfigurationandUserDetailsServiceAutoConfigurationnow matched, and the startup log prints "Using generated security password" for the default in-memory user. - Cause: in the absence of any
SecurityFilterChainbean, Spring Security's auto-configuration registers a default chain.- It requires authentication for every request.
- It enables form login and HTTP basic.
- It enables CSRF protection for state-changing requests.
- Adding the starter made
@ConditionalOnClass(SecurityFilterChain.class)true, and@ConditionalOnMissingBeanfound no user chain, so the defaults applied.
- Fix, in order of preference:
- If they truly only wanted
BCryptPasswordEncoder, depend onspring-security-cryptoalone, which has no auto-configuration. - If they will need security anyway, declare an explicit
SecurityFilterChainbean that states the intended policy, even if it is permit-all for now. - Excluding
SecurityAutoConfigurationworks but leaves a security dependency on the classpath doing nothing, which confuses the next reader.
- If they truly only wanted
- Prevention:
- A context-loading test with a single authenticated and a single anonymous request in CI would have caught it.
- Dependency review that asks "which auto-configurations does this jar switch on" for any new starter.
Picture it One pom line registers a whole filter chain, and the two requests below show where each of the two symptoms comes from.
The setup
<!-- the only change: a pom entry, added to get BCryptPasswordEncoder -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <!-- ❌ TRAP: switches on SecurityAutoConfiguration -->
</dependency>
Make the invisible visible
// roughly what the default SecurityFilterChain does
http.authorizeHttpRequests(a -> a.anyRequest().authenticated()); // every request needs a login
http.formLogin(withDefaults()); // login page for browsers
http.httpBasic(withDefaults()); // Authorization: Basic for clients
// CSRF protection stays on, which is Spring Security's default
# illustrative output, abbreviated
FilterChainProxy
SecurityContextHolderFilter
HeaderWriterFilter
CsrfFilter <- POST/PUT/DELETE without a token stop here
LogoutFilter
UsernamePasswordAuthenticationFilter
BasicAuthenticationFilter
ExceptionTranslationFilter
AuthorizationFilter <- anyRequest().authenticated()
The trace
GET /orders (no credentials)
└─► FilterChainProxy ─► ... ─► AuthorizationFilter ✗ anonymous, anyRequest().authenticated() fails --> 401
POST /orders (no credentials, no CSRF token)
└─► FilterChainProxy ─► CsrfFilter ✗ no token, rejected before any controller --> 403
What you see
# illustrative output
Using generated security password: 3f9a6c1e-5b7d-4c0e-9a42-0d8e6b7f1a10
This generated password is for development use only. Your security configuration must be updated before running your application in production.
$ curl -i localhost:8080/orders
HTTP/1.1 401
WWW-Authenticate: Basic realm="Realm"
$ curl -i -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 403
Why A pom entry changed what is on the classpath, which flipped the conditions, which registered a chain nobody wrote. The defaults are locked down on purpose.
The fix
@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(a -> a.anyRequest().permitAll()) // ✅ FIX: explicit policy, even if open for now
.csrf(csrf -> csrf.disable()) // decision for a stateless API with no cookies
.build();
}
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId> <!-- ✅ FIX: BCryptPasswordEncoder, no auto-configuration -->
</dependency>
What you see now
# illustrative output
$ curl -i localhost:8080/orders
HTTP/1.1 200
$ curl -i -X POST localhost:8080/orders -H 'Content-Type: application/json' -d '{}'
HTTP/1.1 201
Comparison
| Option | FilterChainProxy | CSRF filter | BCryptPasswordEncoder |
|---|---|---|---|
| Starter, no chain of your own | Runs the default chain | On, POSTs fail | Available |
| Explicit permit-all chain | Runs, everything permitted | On unless disabled | Available |
Exclude SecurityAutoConfiguration | Not registered | Gone | Available |
Only spring-security-crypto | Not on the classpath | Gone | Available |
Land it With Boot, a dependency is a configuration change, and the safe default for security is lockdown, so add the starter only when you are ready to write the chain.
- "They wrote a permit-all chain and it still returns 401 on some paths. What next?"
Two things to check. First, is their chain actually the one that matched: if the new bean has a request matcher, requests outside it fall through to no chain at all, which with Boot's defaults means the auto-configured default chain still applies.
Boot's
SpringBootWebSecurityConfigurationbacks off only when at least oneSecurityFilterChainbean exists, so the default should be gone, but a second chain from a library or the Actuator security configuration may have its own matcher and a lower order.Enable
logging.level.org.springframework.security=DEBUG, which logs "Securing GET /path" followed by the chain that matched and each filter invoked.Second, check for a
@EnableWebSecurityin a library with its own chain, and for method security on the controller, which returns 403 rather than 401, so the code itself is a clue.what the DEBUG log showsruns offline# illustrative output DEBUG o.s.security.web.FilterChainProxy : Securing GET /actuator/info DEBUG o.s.security.web.FilterChainProxy : Securing GET /orders/5 # chain that matched is named in the filter lines that follow- "What is the exact difference between excluding the auto-configuration and declaring a permit-all chain, in terms of what is left running?"
With a permit-all chain,
FilterChainProxyis still registered, the whole default filter list still runs on every request, and the security context, CSRF token repository, and header writers still do their work; only the authorization rule says permit.That costs a little per request and, importantly, keeps CSRF on unless disabled, which is why the permit-all chain alone may still fail POSTs. Excluding
SecurityAutoConfigurationmeans noFilterChainProxyat all, so nothing security-related runs, but the jar is still there andspring-security-cryptoclasses are usable.The permit-all chain is the honest option when security is coming; the exclusion is the honest option when it is not, and the cleanest is to depend only on
spring-security-crypto.- "How would you build the CI check that a new starter does not silently change behaviour?"
I would commit the condition report. A test starts the context with
ConditionEvaluationReportaccess, or simply runs the application with--debugin a build step, extracts the list of positive-match auto-configuration class names, sorts them, and compares against a checked-in file.Adding a starter changes the list, and the diff appears in the pull request as a file change that a reviewer must approve, which turns "which auto-configurations does this jar switch on" from a question nobody asks into a diff everybody sees.
The Boot test support has
ApplicationContextRunnerfor library tests, which lets the same assertion be expressed ashasSingleBean(SecurityFilterChain.class)in a unit-speed test.the checked-in file diff in the pull requestruns offline# illustrative output org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration + org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration + org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration- "What about the generated password: is it a risk on its own?"
It is printed to the log at startup as "Using generated security password: <uuid>" with a warning that it is for development only.
The risk is that logs are often shipped to a central store readable by many people, so anyone with log access can authenticate as the default
userwith full access to every endpoint of that service until it restarts.On a service that was never meant to have security, that is a live credential to a service that now blocks everyone else.
It is another reason the fix must be immediate: either remove the dependency or define a chain plus a real
UserDetailsServiceor resource server configuration, at which pointUserDetailsServiceAutoConfigurationbacks off and the password stops being generated.
Q23. "@Import, @ComponentScan, and @ImportAutoConfiguration: when is each the right tool?"
Reveal answer
Strong answer Three tools, three different jobs.
@Importregisters specific classes by name: configuration classes, plain components, or anImportSelectororImportBeanDefinitionRegistrarthat decides programmatically.- It is explicit and order-preserving.
- That makes it the right tool inside a library, for composing configurations, and for "enable" style annotations, which is exactly how
@EnableSchedulingand@EnableCachingwork under the hood.
@ComponentScandiscovers by package, which is convenient for application code and wrong for libraries.- It depends on package layout.
- It cannot be conditionally backed off.
- It runs in the early phase, so it wins every
@ConditionalOnMissingBeanargument against the consuming application.
@ImportAutoConfigurationimports named auto-configuration classes but processes them in the late, auto-configuration phase with their conditions honoured.- It exists for test slices, where
@WebMvcTestuses it to bring in just the web auto-configurations. - It is also for rare cases where an application wants one auto-configuration without
@EnableAutoConfiguration.
- It exists for test slices, where
In an application: scan your own packages, @Import third-party configuration you want explicitly, and leave @ImportAutoConfiguration to Boot's test support.
Picture it One library imported three ways, shown as the beans each way registers and the phase each runs in.
The setup
// library, package com.vendor
@Configuration
class VendorConfig {
@Bean @ConditionalOnMissingBean ObjectMapper vendorMapper() { return new ObjectMapper(); }
}
@Component class VendorAuditor { } // internal helper
@Component class VendorRetryHelper { } // internal helper
// application, pick ONE of these:
@Import(VendorConfig.class) // A
@ComponentScan("com.vendor") // B ❌ TRAP in a library or third-party package
@ImportAutoConfiguration(VendorConfig.class) // C
Make the invisible visible
# illustrative output
A @Import(VendorConfig.class) vendorConfig, vendorMapper
B @ComponentScan("com.vendor") vendorConfig, vendorMapper, vendorAuditor, vendorRetryHelper ✗ helpers are now your beans
C @ImportAutoConfiguration(...) vendorMapper only if the app defines no ObjectMapper of its own ✓ backs off
The trace
early phase your @Configuration classes, @ComponentScan results, @Import targets
└─► B registers everything under com.vendor here, unconditionally
└─► A registers VendorConfig here, in the order written
late phase deferred imports: auto-configurations and @ImportAutoConfiguration
└─► C: VendorConfig's @ConditionalOnMissingBean sees every bean registered above ✓
Comparison
| Application code line | Phase | What becomes a bean | @ConditionalOnMissingBean in VendorConfig |
|---|---|---|---|
@Import(VendorConfig.class) | Early | VendorConfig and its @Bean methods | Evaluated early, so it cannot see the auto-configured beans |
@ComponentScan("com.vendor") | Early | Every component under com.vendor, including helpers | Wins the argument, auto-configuration then backs off |
@ImportAutoConfiguration(VendorConfig.class) | Late | VendorConfig and its @Bean methods | Honoured, backs off if the application has its own bean |
Why Scanning and importing run in the early phase, before any condition can see the rest of the application. Only the late phase lets a library say "use mine unless the application has its own".
The fix For application code, scan your own packages and @Import third-party configuration by name. For a library, ship it as an auto-configuration.
# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in the vendor jar
com.vendor.VendorConfig
# application: no @Import, no @ComponentScan on com.vendor; own ObjectMapper bean, if any, wins
Land it Scan what you own, import what you choose, and let auto-configuration handle what should back off.
- "What is the difference between an
ImportSelectorand anImportBeanDefinitionRegistrar, and when would you write each?" An
ImportSelectorreturns class names to import, decided at runtime from the importing class's annotation metadata; it is the tool for "enable" annotations that choose between configurations, for example picking a proxy-based or AspectJ-based configuration by an attribute.An
ImportBeanDefinitionRegistrarreceives theBeanDefinitionRegistrydirectly and registers definitions programmatically; it is the tool when the beans cannot be expressed as configuration classes, for example one repository proxy per interface found by scanning, which is how@EnableJpaRepositoriesworks.I would write a selector when I have a fixed set of configuration classes to choose among, and a registrar when the number or shape of beans depends on scanning or external metadata. Both run in the early phase, so neither is a place for
@ConditionalOnMissingBean.the shape of eachruns offlineclass MySelector implements ImportSelector { public String[] selectImports(AnnotationMetadata meta) { return new String[] { "com.acme.ConfigA" }; } // names only } class MyRegistrar implements ImportBeanDefinitionRegistrar { public void registerBeanDefinitions(AnnotationMetadata meta, BeanDefinitionRegistry reg) { reg.registerBeanDefinition("clientA", new RootBeanDefinition(HttpClientBean.class)); // one definition per entry } }- "How does
@ComponentScanin a library actually cause trouble for the consuming application?" Suppose the library's
@Configurationcarries@ComponentScan("com.vendor")and the application imports it. Every component undercom.vendoris registered in the early phase, unconditionally. If one of them is aDataSourceor anObjectMapper, Boot's auto-configuration then backs off and the application silently runs on the vendor's bean.If the application defines its own bean with the same name, startup fails with the overriding error from Q16.
And because scanning registers everything, the library's internal helpers become beans in the application, visible in
/actuator/beansand eligible for injection by type, which creates ambiguity errors for types the application also defines.Conditions cannot save a scanned library because scanning runs before the application's own classes may have been processed.
- "How does
@WebMvcTestuse@ImportAutoConfiguration, and why can you not just use@SpringBootTestwith a filter?" @WebMvcTestis meta-annotated with@ImportAutoConfigurationwhose class list comes from a file,META-INF/spring/org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc.importsand its siblings, naming just the MVC, Jackson, validation, and Spring Security web auto-configurations. Combined with aTypeExcludeFilterthat limits component scanning to controllers, advice, converters, and filters, the slice loads in a fraction of the time and without a database. A full@SpringBootTestwith a filter would still run@EnableAutoConfiguration, so every auto-configuration whose classes are present would apply, including the pool and the entity manager, and excluding them by hand means keeping a list in sync with every starter you add.- "Can
@Importtake a plain class that is not a configuration, and what does that do?" Yes, since Spring 4.2. Importing a plain class registers it as a bean, as if it had been component-scanned, with constructor injection resolved by the container.
It is useful in tests to bring in one specific component without a scan, and in libraries to register a helper without making it a
@Configuration.The subtlety is that the class is processed as a lite configuration, so any
@Beanmethods on it run in lite mode with no inter-method proxying, and any@ComponentScanon it is honoured.importing a plain classruns offline@Import(PricingHelper.class) // PricingHelper has no @Configuration, no @Component class AppConfig { } // Result: bean "com.acme.PricingHelper" registered, constructor args injectedFor anything more than a single class, I prefer an explicit
@Configurationso the reader knows it is a source of definitions.
Q24 · Design. "Design the package and configuration layout of a modular monolith in Boot with four modules (orders, inventory, billing, notifications) so that a module cannot reach into another's internals, verified in CI."
Reveal answer
Strong answer Assumptions: one deployable, one database for now, a team per module, and we want the option to split later.
Design, piece by piece:
- Packages. One top-level package per module under the application's base package,
shop.orders,shop.inventory, and so on. - Public API. A module's public API is only the types in its top-level package. Everything in sub-packages such as
shop.orders.internalis package-private or documented as internal. - Communication. Modules talk through the public API interfaces and through application events, never through each other's repositories.
- Enforcement. Spring Modulith (2.0 for Boot 4, 1.x for Boot 3).
ApplicationModules.of(ShopApplication.class).verify()in a test fails the build whenshop.billingimportsshop.orders.internal.OrderRepository, and it also detects cycles between modules. - Events. Modulith's
@ApplicationModuleListeneris asynchronous and transactional after commit. It is backed by an event publication registry table, so an event that fails delivery is retried instead of lost. - Data. Each module owns its tables, and a Flyway migration folder per module keeps the ownership visible.
- Configuration. A single
@SpringBootApplicationwith default scanning, because Modulith's checks are structural, not container-based, and per-module@ComponentScanexclusions are brittle.
Trade-offs: one database means a module boundary is a convention until it is a service. That is accepted for now, and the per-module migrations make a later split mechanical.
What I would not do:
- Enforce boundaries with Maven modules alone, because circular Maven modules are just moved to circular events.
- Start with microservices for four modules and one team of eight.
Picture it Four modules as folders, one illegal import, and the build failure that makes the boundary real.
The setup
shop/
orders/ OrderApi.java OrderPlaced.java // public: top-level package
internal/ OrderRepository.java OrderService.java
billing/ BillingApi.java
internal/ InvoiceService.java
// shop.billing.internal.InvoiceService
OrderRepository repo; // ❌ TRAP: import shop.orders.internal.OrderRepository
// src/test/java
@Test void modulesAreRespected() {
ApplicationModules.of(ShopApplication.class).verify(); // Result: fails the build on the line above
}
Make the invisible visible
# illustrative output
orders exposes: OrderApi, OrderPlaced internal: orders.internal.*
inventory exposes: InventoryApi internal: inventory.internal.*
billing exposes: BillingApi internal: billing.internal.*
notifications exposes: (none) internal: notifications.internal.*
The trace
OrderService.place() @Transactional
├─► repo.save(order) ✓ orders owns its tables
├─► events.publishEvent(OrderPlaced) ✓ row written to event_publication in the same transaction
└─► commit
└─► billing @ApplicationModuleListener ✓ async, after commit, retried if it fails
└─► billing.internal.InvoiceService.create()
billing --X--> orders.internal.OrderRepository ✗ verify() fails the build
What you see
# illustrative output
org.springframework.modulith.core.Violations:
- Module 'billing' depends on non-exposed type shop.orders.internal.OrderRepository within module 'orders'!
shop.billing.internal.InvoiceService declares field ... references shop.orders.internal.OrderRepository
Why Java package-private cannot span sub-packages, so the boundary is a convention until a test reads the imports. verify() turns the convention into a failing build.
The fix
@Service
class InvoiceService {
private final OrderApi orders; // ✅ FIX: public interface in shop.orders
InvoiceService(OrderApi orders) { this.orders = orders; }
}
// or react to the event instead of asking
@ApplicationModuleListener
void on(OrderPlaced e) { create(e.orderId()); } // ✅ FIX: no dependency on orders internals
What you see now
# illustrative output
modulesAreRespected PASSED
Decision table
| Symptom | Root cause | Action |
|---|---|---|
| Build fails with "depends on non-exposed type" | A module imported another module's internal package | Use the public API or listen to the event |
| Test reports a cycle between modules | Two modules call each other directly | Replace one direction with an event |
| Boundary erodes after the first deadline | No test fails when it is crossed | Keep verify() in CI |
| An event is lost when the listener fails | Delivery not recorded with the publisher's transaction | Use @ApplicationModuleListener with the publication registry |
Land it A monolith stays modular only if a test fails when the boundary is crossed, and Modulith gives you that test for the cost of a package convention.
- "Requirement change: billing must become a separate deployable next quarter. What do you change now?"
Three preparations, none of which require splitting yet. First, billing's public API becomes interface-only with DTOs, no entities crossing the boundary, so that the eventual remote client can implement the same interface.
Second, billing's inbound events, the ones it listens to from orders, get a stable schema and a version field, and I move them onto the Modulith event externalisation feature, which publishes events to Kafka or a queue as well as in-process, so the day it becomes a service the transport already exists.
Third, billing's tables move to their own schema with no foreign keys to other modules' tables, verified by a Flyway migration and a test. With those three, the split is a build change and a deployment, not a rewrite.
- "How does the Modulith event publication registry actually guarantee delivery, and what does it cost?"
When a transaction commits and an event has an
@ApplicationModuleListener, Modulith writes a row to anevent_publicationtable in the same transaction as the publisher's business change, recording the event and the listener id.The listener then runs asynchronously after commit, and on success marks the row completed. If the process dies mid-listener, the row is still open, and on restart, or by a scheduled republish, the event is redelivered.
That gives at-least-once delivery with the publisher's transaction as the source of truth, which is the outbox pattern built in.
The costs: one insert per event per listener, a table that must be cleaned up with the completion mode setting, listeners that must be idempotent because redelivery can happen, and serialisation of the event payload as JSON, so the event class must be serialisable.
the event_publication table at two momentsruns offline# illustrative output id | event_type | listener_id | publication_date | completion_date 1 | shop.orders.OrderPlaced | shop.billing...on | 12:00:01 | NULL <- committed with the order, listener not done 1 | shop.orders.OrderPlaced | shop.billing...on | 12:00:01 | 12:00:03 <- listener finished, row completed # process dies while completion_date is NULL: the event is redelivered on restart- "What would you cut with two weeks for four modules and one team?"
I would cut the per-module Flyway folders and the event registry, and start with synchronous
@ApplicationEventListenercalls and a single migration folder. I would keep the package convention, theverify()test in CI, and the rule that modules talk only through their top-level package, because those three cost a day and are the difference between a modular monolith and a monolith. The reason to keep the test above everything else is that the boundary is only real while a build fails when it is crossed; without the test, the first deadline erodes it and nobody notices for a year.- "Why not enforce the boundary with Gradle subprojects or Java modules instead?"
Both work and both are heavier.
Gradle subprojects enforce compile-time visibility, which is strong, but every shared type needs its own subproject, cyclic dependencies between subprojects are a build error that teams route around by creating a
commonmodule that becomes a dumping ground, and the Spring context still sees everything at runtime.JPMS modules give the strongest boundary but interact badly with reflection-heavy frameworks and are rarely used in Boot applications.
Modulith is a test over a package convention, so it costs nothing at build time, reports violations with the exact class and import, and lets a violation be allowed temporarily with a documented exception.
For one team it is the right size; for ten teams on one repo, subprojects per module add the compile-time wall that people then need.
Q25. "What is a BeanFactoryPostProcessor, when would you write one, and why must its @Bean method be static?"
Reveal answer
Strong answer A BeanFactoryPostProcessor runs after all bean definitions are loaded and before any bean is instantiated, and it can read or modify those definitions. It can:
- change a scope;
- add a property;
- register new definitions, through the
BeanDefinitionRegistryPostProcessorsub-interface; - mark beans lazy.
Spring's own examples are PropertySourcesPlaceholderConfigurer, which resolves ${...}, and ConfigurationClassPostProcessor, which processes @Configuration classes.
You would write one for two reasons:
- to register beans dynamically from external metadata, for instance one client bean per entry in a configuration list;
- to enforce a policy across all definitions, such as making every
@Scheduledbean lazy.
The static rule follows from timing: a post-processor must be created before the definitions it processes are turned into beans.
- If its factory method is an instance method, the container must first instantiate the enclosing
@Configurationclass to call it. - That forces the configuration class, and anything it depends on, to be created early, before other post-processors such as the placeholder resolver have run.
- Boot logs a warning, "not eligible for getting processed by all BeanPostProcessors", for exactly this.
- A static method can be called without the enclosing instance, so the post-processor is created in isolation.
Picture it The order in which the container does its work, and the one-word change that stops a configuration class being built too early.
The setup
@Configuration
class PolicyConfig {
@Value("${policy.name}") String policy; // injected later, by a BeanPostProcessor
@Bean
BeanFactoryPostProcessor makeLazy() { // ❌ TRAP: not static, so PolicyConfig is built first
return bf -> { /* mark definitions lazy */ };
}
@PostConstruct void init() { log.info("policy={}", policy); } // Result: never runs, policy stays null
}
Make the invisible visible
1. bean definitions loaded
2. BeanFactoryPostProcessors created and run (static @Bean method: no PolicyConfig instance needed)
3. BeanPostProcessors registered (@Autowired, @Value, @PostConstruct, AOP proxies)
4. ordinary singletons created (now they pass through every BeanPostProcessor)
The trace
non-static: step 2 needs makeLazy() ──► must create PolicyConfig now
└─► PolicyConfig built at step 2 ✗ BeanPostProcessors from step 3 do not exist yet
└─► @Value not injected, @PostConstruct not run
static: step 2 calls PolicyConfig.makeLazy() directly ✓ no instance needed
step 4 builds PolicyConfig normally ✓ injected and initialised
What you see
# illustrative output
INFO @Bean method PolicyConfig.makeLazy is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface ... (advice: add the static modifier)
(the message continues: this will result in a failure to process annotations such as @Autowired and @PostConstruct in the declaring class)
init() log line: absent
policyConfig.policy == null
Why To call an instance method the container needs the instance. It builds PolicyConfig before the annotation-processing post-processors exist, so the class never gets its injection or its init callback.
The fix
@Bean
static BeanFactoryPostProcessor makeLazy() { // ✅ FIX: static, created in isolation
return bf -> { /* mark definitions lazy */ };
}
What you see now
# illustrative output
init() log line: policy=strict
policyConfig.policy == "strict"
Land it Post-processors are bootstrapping code, and bootstrapping code must not pull ordinary beans into existence early, which is what static prevents.
- "Show me the shape of a post-processor that registers one client bean per configuration entry, and what it cannot do."
It implements
BeanDefinitionRegistryPostProcessorandEnvironmentAware. InpostProcessBeanDefinitionRegistryit usesBinder.get(environment).bind("clients", Bindable.mapOf(String.class, ClientSettings.class))to read the entries, and for each entry builds a definition withBeanDefinitionBuilder.genericBeanDefinition(HttpClientBean.class, () -> new HttpClientBean(settings))and registers it under the entry's key.What it cannot do is inject other beans in the usual way, because no beans exist yet; it must read the
Environmentdirectly, and it cannot depend on@ConfigurationPropertiesbeans since those are ordinary beans created later.It must also be a static
@Beanor a component, and AOT needs it to be deterministic at build time, otherwise the native image is missing those beans.the shape of a registrarruns offlineclass ClientRegistrar implements BeanDefinitionRegistryPostProcessor, EnvironmentAware { private Environment env; public void setEnvironment(Environment e) { this.env = e; } // read the Environment directly public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry reg) { Map<String, ClientSettings> m = Binder.get(env) .bind("clients", Bindable.mapOf(String.class, ClientSettings.class)).orElse(Map.of()); m.forEach((name, cfg) -> reg.registerBeanDefinition(name, BeanDefinitionBuilder.genericBeanDefinition(HttpClientBean.class, () -> new HttpClientBean(cfg)).getBeanDefinition())); } public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) { } // nothing to do here }- "What exactly does the 'not eligible for getting processed by all BeanPostProcessors' warning mean, and what breaks?"
Beans created before the
BeanPostProcessorregistration phase are instantiated without the post-processors that had not yet been registered, and the container logs that warning for each.The concrete breakage is that such a bean is not proxied: no
@Transactional, no@Async, no@PreAuthorize, no@ConfigurationPropertiesbinding if the binding processor was among the ones not yet registered.Symptoms are subtle, because the bean exists and works until an annotation is expected to fire.
The usual trigger is a non-static
@Beanmethod for a post-processor, which pulls in the enclosing configuration class early, and that class's constructor-injected dependencies with it, so a whole subgraph is created too soon.Making the method static, or moving the post-processor to its own configuration class, removes the early pull.
- "How would you verify in a running application which post-processors ran and in what order?"
The order is determined by
PostProcessorRegistrationDelegate: firstPriorityOrderedimplementations, thenOrdered, then the rest, and separately for registry post-processors before plain factory post-processors. To see it, setlogging.level.org.springframework.context.support.PostProcessorRegistrationDelegate=DEBUG, or put a breakpoint ininvokeBeanFactoryPostProcessors.For a post-processor of mine, I log its class name and the count of definitions at entry, which shows whether it ran before or after the placeholder resolver by checking whether a
${…}value is still unresolved.A quick sanity assertion is a test that registers the post-processor with
ApplicationContextRunnerand checks that the expected dynamic beans exist and that none of them carry the raw-version warning.- "How do these interact with Spring AOT and a native image?"
AOT runs the post-processors at build time during its refresh-for-AOT step, so any definitions they register are captured into the generated code, and the post-processor itself is not run again at runtime in the native image.
That is fine as long as the post-processor's output depends only on inputs available at build time. If it reads a runtime environment variable to decide how many clients to create, the native image has the build-time answer frozen.
The workaround is to make the decision data rather than bean structure: register a fixed
ClientRegistrybean and let it create clients at runtime from the environment, so the bean graph is static and the variation lives inside one bean.
Q26 · Scenario. "Startup fails with 'Could not resolve placeholder payment.gateway-url in value ${payment.gateway-url}'. The key is in application.yml, and it works on the developer's laptop. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a placeholder with no default failed to resolve in one environment but not another, so the property sources differ between the two.
- Evidence: run with
--debugor query/actuator/envon a working instance and compare the property source list. Checkspring.config.location,spring.config.additional-location, andSPRING_PROFILES_ACTIVEin the failing environment. - Likely causes, ranked:
- Profile. The key is only in
application-local.yml, and the laptop runs with thelocalprofile while the cluster does not. - Replaced file. The deployment sets
spring.config.locationto an external file, which replaces rather than adds to the packaged file, so the packaged yml is not read at all.additional-locationis the additive one. - Indentation. The yml has an indentation error, so the key parses under a different parent, which YAML accepts silently.
- Missing mount. The value is in a Kubernetes ConfigMap that was not mounted in this namespace.
- Profile. The key is only in
- Fix:
- Put the real value in the environment for that deployment.
- In code, prefer a
@ConfigurationPropertiesrecord with validation over@Value, so the failure message names the property, the origin, and the constraint. - Where a default is legitimate, write
${payment.gateway-url:https://sandbox}, but not for production URLs.
- Prevention:
- A startup smoke test in the pipeline that runs the jar with the production profile and a fake environment.
- A lint that rejects
@Valuewithout a default outside configuration classes.
Picture it Two property source lists side by side: the cluster is missing the file that holds the key.
The setup
# application.yml packaged inside the jar
payment:
gateway-url: https://pay.example.com
# laptop
java -jar app.jar
# cluster: the deployment adds this flag ❌ TRAP: location REPLACES the default search locations
java -jar app.jar --spring.config.location=file:/etc/app/override.yml
Make the invisible visible
# illustrative output, /actuator/env sources
laptop: commandLineArgs, systemProperties, systemEnvironment,
Config resource 'class path resource [application.yml]', <- has payment.gateway-url
cluster: commandLineArgs, systemProperties, systemEnvironment,
Config resource 'file [/etc/app/override.yml]' <- no application.yml in the list
The trace
@Value("${payment.gateway-url}") on PaymentClient
└─► PropertySourcesPlaceholderConfigurer looks through the sources, in order
├─► commandLineArgs no
├─► systemEnvironment no
└─► override.yml no ✗ packaged application.yml was never read
└─► no default given ──► startup fails
What you see
# illustrative output
***************************
APPLICATION FAILED TO START
***************************
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'payment.gateway-url' in value "${payment.gateway-url}"
Why The placeholder resolver only searches the sources that were loaded. spring.config.location replaced the default locations, so the packaged file is not among them.
The fix
java -jar app.jar --spring.config.additional-location=file:/etc/app/override.yml # ✅ FIX: defaults kept, file added on top
# or, with no file at all
PAYMENT_GATEWAY_URL=https://pay.example.com java -jar app.jar # ✅ FIX: relaxed binding of the env var
What you see now
# illustrative output
cluster: commandLineArgs, systemProperties, systemEnvironment,
Config resource 'file [/etc/app/override.yml]',
Config resource 'class path resource [application.yml]' <- read again, payment.gateway-url found
Started OrderApplication in 6.4 seconds
Decision table
| Symptom | Root cause | Action |
|---|---|---|
| Key is missing from the property source list | Different profile active, or spring.config.location replaced the defaults | Compare /actuator/env, switch to additional-location or an environment variable |
| Source is listed but the key is absent | YAML indentation put it under another parent | Fix the indentation, bind to a validated record |
| Source is not listed at all | ConfigMap not mounted, or jar built without the file | Check the mount and unzip -p the artifact |
Land it "Works on my laptop" for configuration always means a different property source list, and config.location versus additional-location is the classic reason.
- "You confirmed the profile is active in the cluster and the key is in the file, and it still fails. What next?"
Then the file that is loaded is not the file I think it is.
I would
kubectl execinto the pod, rununzip -p app.jar BOOT-INF/classes/application-prod.yml | grep -n gatewayto confirm the key is inside the deployed artifact, because a stale image or a build that filtered resources is common.Then I would check the YAML for tabs, which YAML rejects, and for a duplicate top-level
payment:key, which silently drops the first block.Then
/actuator/envon the pod, if reachable, to see whether the property source for that file appears at all; its absence meansspring.config.locationorspring.config.namechanged the search.Finally I would look for a
---document separator with aspring.config.activate.on-profileabove the key that excludes this profile.- "What does the failure look like with a
@ConfigurationPropertiesrecord instead, and why is it better?" With
@ConfigurationProperties("payment")on a record with a@NotBlank String gatewayUrland@Validated, startup fails with Boot'sFailureAnalyzeroutput: a block titled "Binding to target failed" that names the propertypayment.gateway-url, the value it saw, the origin file and line if it came from a file, and the constraint that failed.startup failure with a validated recordruns offline# illustrative output *************************** APPLICATION FAILED TO START *************************** Description: Binding to target ... PaymentProperties failed: Property: payment.gateway-url Value: "null" Reason: must not be blankThat is three facts an operator can act on, versus a placeholder message that names only the key.
The record is also typed, so a URL field can be a
URIand fail on a malformed value, and it is testable: I can bind a map to it in a unit test withBinderand assert the validation.And it is one object to inject rather than a dozen
@Valuestrings scattered through classes.- "When does a missing placeholder not fail at startup, and why is that dangerous?"
Two cases. A placeholder with a default,
${payment.gateway-url:https://sandbox}, resolves to the default silently, so production can run against the sandbox for a week before anyone notices.And a placeholder inside a lazily initialised bean, or one read at runtime via
Environment.getPropertywithout a check, fails only when that code runs. Both turn a deployment-time error into a business-logic error.My rule is that production URLs and credentials never carry a default, that
@ConfigurationPropertiesclasses are validated, and thatEnvironment.getPropertyin application code is a review comment.Where a default is right, for a timeout or a page size, it goes in the properties record's field, not in the placeholder string.
- "How does
spring.config.locationdiffer fromadditional-locationmechanically, and which do you recommend for Kubernetes?" spring.config.locationreplaces the default search locations entirely: the packagedapplication.ymlis no longer read unless you listclasspath:/yourself.spring.config.additional-locationkeeps the defaults and adds the given locations after them, so they override.For Kubernetes I recommend neither in most cases: set values as environment variables from a ConfigMap and Secret, which need no file mounting and sit above every file.
When a mounted file is needed, for example a large YAML of tenant settings, mount it and use
spring.config.import=optional:file:/etc/app/in the packaged YAML, oradditional-locationwith a trailing slash so Boot treats it as a directory and picks up profile-specific files too.location versus additional-locationruns offline--spring.config.location=file:/etc/app/ packaged application.yml: NOT read --spring.config.additional-location=file:/etc/app/ packaged application.yml read first, /etc/app/ added on top
Q27. "What does Spring AOT do at build time for a GraalVM native image, and what container features stop working as a result?"
Reveal answer
Strong answer A native image is compiled ahead of time with a closed world: every class, method, and reflective access must be known at build time, and there is no runtime bytecode generation.
The container normally relies on both. So Spring AOT runs a build-time step that starts the context in a special mode, resolves all bean definitions, evaluates conditions, and then generates:
- Java source, one class per bean, that calls its constructor directly and sets its properties;
- reflection, resource, and proxy hints for GraalVM;
- pre-generated CGLIB proxies for
@Configurationclasses and AOP targets.
The generated code is compiled into the image, so at runtime there is no scanning, no condition evaluation, and no proxy generation.
What stops working is anything decided at runtime:
- Profiles and
@ConditionalOnPropertyare frozen to the values present at build time, so you cannot switch a profile with an environment variable in production.@Profilebeans not selected at build time simply do not exist. - Runtime
@Lazycreation still works, but a bean introduced by aBeanFactoryPostProcessorthat reads runtime input does not. - Reflection on classes AOT did not see, typically JSON serialisation of types only reached through generics or a library's internal reflection, fails with
ClassNotFoundExceptionor missing-member errors. It needs@RegisterReflectionForBindingor aRuntimeHintsRegistrar. - Other casualties: class-based mocks in tests, Groovy-style dynamic code, and most Java agents.
Picture it A profile-selected bean on the JVM versus in a native image, and the generated code that explains the difference.
The setup
@Configuration(proxyBeanMethods = false)
class PaymentConfig {
@Bean @Profile("staging") PaymentProvider fake() { return new FakePayments(); }
@Bean @Profile("!staging") PaymentProvider real() { return new RealPayments(); }
}
// native image built with NO profile active: ❌ TRAP: the build picks "!staging" for good
// deploy with SPRING_PROFILES_ACTIVE=staging Result: still RealPayments, the fake bean does not exist
Make the invisible visible
// OrderService__BeanDefinitions, generated source, simplified
public static BeanDefinition getOrderServiceBeanDefinition() {
RootBeanDefinition def = new RootBeanDefinition(OrderService.class);
def.setInstanceSupplier(args -> new OrderService(args.get(OrderRepository.class))); // direct constructor call
return def; // no scanning, no reflection, no condition check at runtime
}
// PaymentConfig__BeanDefinitions has only real(): fake() was dropped when the build evaluated @Profile
The trace
JVM: start ─► scan ─► evaluate @Profile with SPRING_PROFILES_ACTIVE=staging ─► fake() registered ✓
native: build ─► scan ─► evaluate @Profile with no profile ─► real() registered, fake() dropped
start ─► run generated code only ─► SPRING_PROFILES_ACTIVE=staging is read, but nothing re-evaluates ✗
What you see
# illustrative output
$ SPRING_PROFILES_ACTIVE=staging java -jar app.jar
PaymentProvider bean: FakePayments
$ SPRING_PROFILES_ACTIVE=staging ./app
PaymentProvider bean: RealPayments # chosen at build time
Why The decision about which beans exist moved from startup to the build. At runtime only the generated code runs, so nothing evaluates the profile again.
The fix
@Bean PaymentProvider payments(@Value("${payments.mode:real}") String mode) {
return new SwitchingPayments(new RealPayments(), new FakePayments(), mode); // ✅ FIX: both exist, a value decides
}
What you see now
# illustrative output
$ PAYMENTS_MODE=fake ./app
PaymentProvider bean: SwitchingPayments (mode=fake) # the property is read at runtime
Comparison
| Action | JVM | Native image |
|---|---|---|
Switch a profile with SPRING_PROFILES_ACTIVE at deploy time | Works | Silently not applied to the bean set |
Change spring.datasource.url through an environment variable | Works | Works |
Flip a @ConditionalOnProperty value at startup | Works | Frozen to the build-time value |
| Serialise a type reached only through generics | Works | Fails with missing-member errors unless hinted |
| Generate a CGLIB proxy at runtime | Works | Not possible, proxies are generated at build time |
| Attach a Java agent | Works | Mostly not possible |
Land it Native mode moves the container's decisions from startup to build, so any decision you needed to make per environment has to become configuration data rather than a bean choice.
- "So how do you handle per-environment configuration in a native image, if profiles are frozen?"
Profiles that change which beans exist are frozen at build time; profiles and properties that change values are not. So the pattern is: build the image with the full production bean set, and let every environment difference be a property value.
A database URL, a partner endpoint, a feature flag, a pool size: all are read at runtime from the environment exactly as on the JVM. If two environments genuinely need different beans, for example a fake payment provider in staging, I build two images with
-Dspring.profiles.active=stagingpassed to the AOT step, or better, I make the fake provider a runtime choice by having one bean that delegates to real or fake based on a property.The
spring.aot.enabledflag and the AOT processing goal in the Maven and Gradle plugins are where the build-time profile is set.- "What are the actual numbers: startup, memory, build time, and where does native lose?"
For a typical Boot web service with JPA, as of Aug 2026: JVM startup around 2 to 4 seconds, native around 50 to 100 milliseconds; resident memory at idle around 250 megabytes on the JVM versus 60 to 100 native; a native build takes 3 to 8 minutes and needs 8 gigabytes or more of memory on the build machine.
Native loses on peak throughput, typically 10 to 30 percent lower than a warmed-up JIT because there is no profile-guided optimisation unless you use the enterprise PGO feature, and on build feedback time, which is why you test on the JVM and only verify on native.
It also loses the JVM's diagnostic tools: no JFR by default, limited heap dumps, no dynamic agents. The JDK AOT cache from JDK 24 and 25 now closes much of the startup gap on the JVM, which changes the calculation for many services.
- "What does the generated code look like, and can you read it when something goes wrong?"
Yes, and reading it is the best debugging tool. The AOT step writes Java sources into
target/spring-aot/main/sourcesor the Gradle equivalent.There is one class per bean named like
OrderService__BeanDefinitionswith a static method that builds aRootBeanDefinitionand an instance supplier that calls the constructor with resolved arguments, plus anApplicationContextInitializerthat registers them all in order. Hints go intoMETA-INF/native-image/…/reflect-config.jsonand friends undertarget/spring-aot/main/resources.When a bean is missing in native, I search the generated sources for its name; if the class is absent, AOT never saw the bean, which usually means a condition evaluated differently at build time.
where the output landsruns offlinetarget/spring-aot/main/sources/com/acme/OrderService__BeanDefinitions.java target/spring-aot/main/resources/META-INF/native-image/com.acme/app/reflect-config.json- "How would you verify before shipping that the native binary is correct, and what does that cost in CI?"
Run the integration tests against the binary. The Maven native plugin's
nativeTestgoal and the Gradle equivalent compile the test classes and the application into a single native test binary and run JUnit inside it, so reflection gaps in tests show up as failures.That costs a full native build per run, so I do not run it on every commit; I run the JVM tests per commit and the native tests on the merge to main and nightly, with a build cache for the GraalVM output.
Alongside that, a smoke deployment of the actual image to a staging namespace with the real configuration catches the profile freezing problem, which unit tests cannot see because they fix the profile themselves.
Q28 · Scenario. "A native-image build of a Boot service passes its tests, but in production a single endpoint returns 500 with 'Unable to find a constructor for type CustomerView'. On the JVM it works. Diagnose and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: Jackson cannot instantiate a class reflectively in the native image, and only for one type. That is a missing reflection hint, not a logic bug.
- Evidence: the stack trace comes from Jackson's deserialiser; the type is probably a response or request body reached only through a generic, such as
ResponseEntity<Page<CustomerView>>, or through a type Jackson discovers at runtime by a@JsonSubTypesannotation, so AOT's static analysis of controller signatures never saw it. - Why tests passed: they ran on the JVM, where reflection is unrestricted. Native behaviour is only tested if the tests run against the native binary, which the
-PnativeTestprofile does. - Fix:
- Register the type with
@RegisterReflectionForBinding(CustomerView.class)on a configuration class. - Or implement a
RuntimeHintsRegistrarthat registers the hierarchy, and register it with@ImportRuntimeHints. Then rebuild. - For a broad fix, run the app on the JVM with the GraalVM tracing agent (
-agentlib:native-image-agent) through the integration suite to generate the missing hints automatically.
- Register the type with
- Prevention:
- Run the integration tests against the native binary in CI on every merge.
- Keep DTOs in a package whose types are all registered by one registrar, so a new DTO cannot be forgotten.
Picture it One DTO missing from the generated reflection hints is the whole difference between a 200 on the JVM and a 500 in the native image.
The setup
record CustomerView(String id, String name) { }
record Envelope<T>(List<T> items) { }
@RestController
class CustomerController {
@PutMapping("/customers/bulk")
void bulk(@RequestBody Envelope<CustomerView> body) { } // ❌ TRAP: CustomerView only appears inside a generic
} // Result: JVM works, native image has no hint for CustomerView
Make the invisible visible
// illustrative output
[
{ "name": "com.acme.Envelope", "allDeclaredConstructors": true, "allPublicMethods": true },
// com.acme.CustomerView: no entry, so in the native image its constructor does not exist for Jackson
{ "name": "com.acme.SearchRequest", "allDeclaredConstructors": true, "allPublicMethods": true }
]
The trace
PUT /customers/bulk body {"items":[{"id":"1","name":"Ada"}]}
└─► Jackson deserialises Envelope<CustomerView>
├─► Envelope hint present ✓
└─► CustomerView (list items) no hint, no reachable constructor ✗ JVM: reflection unrestricted, works; native: fails
What you see
# illustrative output
HTTP/1.1 500
{"status":500,"error":"Internal Server Error","path":"/customers/bulk"}
log: ... Unable to find a constructor for type CustomerView # wording from the deserialiser, stack trace inside Jackson
Why The native image keeps only the reflection that was registered at build time. AOT read the controller signature but never walked into the generic, so CustomerView has no entry.
The fix
@Configuration(proxyBeanMethods = false)
@RegisterReflectionForBinding(CustomerView.class) // ✅ FIX: constructor, accessors and fields get hints
class NativeHints { }
What you see now
// illustrative output
{ "name": "com.acme.CustomerView", "allDeclaredConstructors": true, "allPublicMethods": true, "allDeclaredFields": true }
// PUT /customers/bulk -> HTTP/1.1 200
Decision table
| Symptom | Root cause | Action |
|---|---|---|
| 500 in native, 200 on the JVM, one endpoint | Type reached only through a generic or a runtime-discovered subtype, no reflection hint | @RegisterReflectionForBinding or a registrar |
| Tests pass, production fails | Tests ran on the JVM | Run the integration suite against the native binary |
| Many DTOs, unknown gaps | No record of which types need hints | One registrar per DTO package, plus a tracing-agent run |
Land it The native rule is that reflection AOT cannot see does not exist, and the only real test is the native binary itself.
- "You added
@RegisterReflectionForBinding(CustomerView.class), rebuilt, and now a different field is null in the response. What next?" The constructor hint fixed instantiation, but the type has a nested property whose class was not registered, so Jackson cannot see its getters and writes nothing.
@RegisterReflectionForBindingregisters the named type and, as of Spring Framework 6.1, its property types transitively for JavaBeans-style properties, but it does not follow generics likeList<Address>in every case, and it does not see a type reached only through a custom serialiser. I would list the nested types explicitly in the annotation, or write aRuntimeHintsRegistrarthat walks the DTO package and registers every class withMemberCategory.INVOKE_PUBLIC_METHODSandINVOKE_DECLARED_CONSTRUCTORS, and then add aRuntimeHintsPredicatesassertion in a test that checks the hint forAddressis present.a registrar for the nested typeruns offlineclass DtoHints implements RuntimeHintsRegistrar { public void registerHints(RuntimeHints hints, ClassLoader cl) { hints.reflection().registerType(Address.class, MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } } @Configuration @ImportRuntimeHints(DtoHints.class) class NativeHints { }- "How do you test that hints exist without building a native image?"
Spring's AOT test support has
RuntimeHintsPredicates. In a unit test I create aRuntimeHintsinstance, invoke myRuntimeHintsRegistraron it, and assertRuntimeHintsPredicates.reflection().onType(CustomerView.class).withMemberCategory(INVOKE_DECLARED_CONSTRUCTORS)accepts the hints. That runs in milliseconds on the JVM and fails when someone removes or renames a DTO. For the whole application, the AOT processing step itself can run on the JVM in the build without producing an image, and a test with@EnabledInAotModecan boot the AOT-generated context on the JVM using-Dspring.aot.enabled=true, which catches bean-level differences but not GraalVM reflection restrictions.a hint test on the JVMruns offlineRuntimeHints hints = new RuntimeHints(); new DtoHints().registerHints(hints, getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection() .onType(Address.class).withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(hints);- "Why did the tracing agent approach miss this, if the team used it?"
The GraalVM tracing agent records only the reflection that actually happens during the run it observes. If the integration suite never called that endpoint with a response containing a
CustomerView, no hint was recorded.The agent is a coverage tool, and its output is exactly as good as the coverage of the run.
That is why I treat agent output as a starting point and keep a registrar for entire DTO packages as the authoritative source, so a new DTO is registered by being in the package rather than by being exercised.
The agent is still worth running periodically to find surprises in third-party libraries that reflect on their own internals.
- "What would you do differently in a greenfield native-first service?"
I would avoid reflection-dependent serialisation from the start where I can. Jackson with records and a single registrar per DTO package is acceptable, but I would also consider Jackson's Blackbird module or a generated approach.
I would keep all DTOs in one package hierarchy and write the registrar on day one.
I would choose libraries with published reachability metadata in the GraalVM reachability repository, and I would run
nativeTeston main from the first week so drift is caught early rather than at release.And I would use constructor injection and
proxyBeanMethods = falseeverywhere, so AOT generates plain code with no proxy hints to maintain.
Q29. "How does the container decide bean creation order, and what do @DependsOn and @Order each actually control?"
Reveal answer
Strong answer Creation order is driven by dependencies: when the container creates bean A and A's constructor needs B, it creates B first, recursively.
Beans with no dependency relationship are created in the order their definitions were registered. That follows configuration class processing order and, within scanning, an unspecified file-system order. So the only guaranteed ordering is "a bean's dependencies exist before it does".
@DependsOn("flyway")adds an artificial edge for beans that do not inject each other but have a hidden runtime dependency. The classic case is an entity manager that must not validate the schema until migrations have run, and Boot already wires that specific one for Flyway and Liquibase.@Orderand theOrderedinterface control something different: the position of a bean within collections injected asList<T>, the order of filters and interceptors, and the order of listeners and runners. They do not affect creation order at all, which is a common confusion.@Priorityis similar and additionally breaks ties for single-candidate injection.
If you find yourself needing @DependsOn often, that is a sign the dependency should be made explicit in a constructor so the container sees it.
Picture it One log, two orders: beans are created by dependency edges, and the same beans run in @Order.
The setup
@Component @Order(1) class MigrateRunner implements ApplicationRunner {
MigrateRunner() { log("create MigrateRunner"); }
public void run(ApplicationArguments a) { log("run MigrateRunner"); }
}
@Component @Order(2) class WarmupRunner implements ApplicationRunner {
WarmupRunner() { log("create WarmupRunner"); }
public void run(ApplicationArguments a) { log("run WarmupRunner"); }
}
@Component class ReportService { ReportService(Repo repo) { log("create ReportService"); } } // Repo is created first
@Component @DependsOn("flyway") // ✅ hidden edge: nothing is injected, but the schema must exist
class SchemaValidator { SchemaValidator() { log("create SchemaValidator"); } }
Make the invisible visible
# illustrative output
create WarmupRunner <- registration order, @Order has no say
create MigrateRunner
create Repo
create ReportService <- after Repo: constructor dependency
flyway migrations applied
create SchemaValidator <- after flyway: @DependsOn edge
run MigrateRunner <- @Order(1)
run WarmupRunner <- @Order(2)
The trace
refresh()
├─► create ReportService ──► needs Repo ──► create Repo first ✓ dependency edge
├─► create SchemaValidator ──► @DependsOn("flyway") ──► create flyway first ✓ declared edge
└─► create all other singletons in registration order @Order not consulted
callRunners()
└─► sort runners with AnnotationAwareOrderComparator ──► Migrate(1), Warmup(2) ✓ @Order sorts here
Comparison
| Annotation | Creation order | Position in List<T>, filters, runners | Single-candidate tie-break |
|---|---|---|---|
@DependsOn | Yes, a hard edge | No | No |
@Order | No | Yes | No |
@Priority | No | Yes, same as @Order | Yes, lowest value wins, classes only |
Why The container builds from the dependency graph, so only a constructor edge or @DependsOn can move creation. Ordering annotations are applied when a collection is assembled or runners are invoked, after the beans exist.
Land it Creation follows the dependency graph, @DependsOn patches an invisible edge, and @Order sorts lists, not creation.
- "Show me a case where
@Orderseems to control creation order, and explain why it actually does not." Suppose two
ApplicationRunnerbeans,MigrateRunnerwith@Order(1)andWarmupRunnerwith@Order(2). They run in that order, and someone concludes@Ordercontrolled creation. It did not: both beans were created during context refresh, in registration order or dependency order, well before either ran.SpringApplicationcollects all runners after refresh, sorts them withAnnotationAwareOrderComparator, and invokes them. The proof is a constructor log line in each: the constructor order does not follow@Order, therunorder does.The same holds for filters, listeners, and
List<T>injections: the sort is applied at collection time, not at instantiation time.- "What happens if
@DependsOnnames a bean that is lazy, or forms a cycle?" A
@DependsOntarget is forced into existence when the dependent bean is created, so a lazy target stops being lazy in practice as soon as anything depending on it is created eagerly.A cycle of
@DependsOnedges is detected during creation and throwsBeanCreationExceptionwith "Circular depends-on relationship between" naming the two beans; there is no early-reference trick for depends-on because the dependency is not an injection, so it cannot be broken by@Lazyon a parameter.That is one reason I keep
@DependsOnrare: it is a hard edge with no escape hatch, and the container cannot tell whether it is really needed.what a depends-on cycle throwsruns offline# illustrative output BeanCreationException: Error creating bean with name 'a': Circular depends-on relationship between 'a' and 'b'- "How does Boot make JPA wait for Flyway, mechanically, and does it work for a second data source?"
Boot registers an
EntityManagerFactoryDependsOnPostProcessor, aBeanFactoryPostProcessorthat finds everyEntityManagerFactorydefinition and addsflywayorliquibaseto itsdependsOnlist. The same is done forJdbcOperationsandNamedParameterJdbcOperationsbeans so aJdbcTemplate-based initialiser also waits.It applies to every entity manager in the context, but only to the auto-configured Flyway bean name, so with two databases and two hand-built
Flywaybeans I have to add the edges myself: either@DependsOn("reportingFlyway")on the reporting entity manager's@Beanmethod, or by extending that post-processor with the other bean name.Forgetting it produces schema validation failures on first deploy to an empty database, which is the classic symptom.
- "What is
@Priority, and when does it beat@Order?" @Priorityis thejakarta.annotationstandard annotation that Spring honours as an ordering value, so in lists it sorts exactly like@Order.Its extra effect is in single-candidate injection: when several beans of a type exist and none is
@Primary, the container picks the one with the highest priority, meaning the lowest value, instead of failing with an ambiguity error.@Orderdoes not participate in that selection.So
@Priorityis the tool when I want a default among several implementations without@Primary's absoluteness. It only works on classes, not on@Beanmethods, which is a common surprise, and it requires the Jakarta annotations API on the classpath.priority as a default among severalruns offline@Component @Priority(1) class FastGateway implements Gateway { } @Component @Priority(2) class SlowGateway implements Gateway { } @Service class Pay { Pay(Gateway g) { } } // Result: FastGateway injected, no ambiguity error, no @Primary
Q30 · Design. "Design a health indicator and metrics for a third-party fraud-scoring API our service depends on, so that the readiness probe, alerts, and dashboards each get the right signal."
Reveal answer
Strong answer Requirements: know whether the dependency is reachable, know how it is performing, and do not let its outage take our pods out of rotation if we can degrade.
Design, one signal per consumer:
- Health indicator. A
HealthIndicatorbean namedfraudApicalls the vendor's cheap status endpoint with a 1-second timeout. It reportsUP,DOWNwith the last error as a detail, or a customDEGRADEDstatus mapped to HTTP 200 viamanagement.endpoint.health.status.http-mapping.DEGRADED=200. - Not in readiness. Crucially it is not added to the readiness group, because if fraud scoring is down we fall back to a rules-based check rather than refuse traffic.
- Where it does appear. On
/actuator/healthfor humans, and on a separate group,management.endpoint.health.group.deps.include=fraudApi,db, for alerting. - Caching. The indicator's result is cached with
management.endpoint.health.cache.time-to-live=10s, so probes cannot flood the vendor. - Metrics. The client call is wrapped in a Micrometer
Observationnamedfraud.api.callwith tags for outcome and the vendor's decision, which gives a timer with percentiles and a trace span for free. - Breaker. The Resilience4j circuit breaker registers its own
resilience4j.circuitbreaker.stategauge. - Alerts. Page on breaker open for more than 5 minutes, or on error rate above 10 percent over 5 minutes. Do not page on a single health DOWN.
Trade-offs: a synthetic status call can pass while real calls fail, so the breaker's real-traffic metrics are the more trustworthy signal.
What I would not do:
- Put the vendor in the readiness group, because that turns their outage into ours.
- Use a health check that performs a real scoring call, because that costs money and can be rate-limited.
Picture it Four phases of one vendor outage, with what the readiness probe, the health group, and the metrics each read at every phase.
The setup
@Component("fraudApi")
class FraudApiHealthIndicator implements HealthIndicator {
public Health health() {
try { client.status(); return Health.up().build(); } // 1 second timeout on the client
catch (Exception e) { return Health.down().withDetail("error", e.getMessage()).build(); }
}
}
management:
endpoint:
health:
cache.time-to-live: 10s
group:
readiness.include: readinessState # fraudApi deliberately NOT listed: we can degrade
deps.include: fraudApi,db # alerting group
Make the invisible visible
# illustrative output
phase fraudApi readiness breaker error rate action
normal UP 200 UP CLOSED 0.2 % none
vendor slow UP 200 UP CLOSED 12 % for 5 min page: error rate above 10 %
vendor down DOWN 200 UP OPEN fallback rules used page when open for 5 min
recovered UP 200 UP CLOSED 0.3 % resolve
GET /actuator/health/deps -> 503 {"status":"DOWN","components":{"db":{"status":"UP"},"fraudApi":{"status":"DOWN","details":{"error":"timeout"}}}}
GET /actuator/health/readiness -> 200 {"status":"UP"}
Why Each consumer asks a different question. The readiness probe asks whether this pod can serve, and it can, with the fallback. The alert asks whether the dependency is healthy, and the dashboard asks how well it performs.
Decision table
| Symptom | Root cause | Action |
|---|---|---|
| Pods leave the load balancer when the vendor fails | Vendor indicator is in the readiness group | Move it to the deps group, keep the rules fallback |
| Vendor rate-limits our status calls | One synthetic call per probe per pod | Cache the result, or read the breaker state instead of calling |
| Indicator UP, real scoring failing | Synthetic call is not real traffic | Alert on breaker state and error rate from the Observation |
| Indicator and metrics both show a hang | No timeout on the client call | Set a timeout on the client |
Land it Health answers "can this pod serve", metrics answer "how well", and a dependency you can degrade around belongs in the second, not the first.
- "Requirement change: fraud scoring becomes mandatory by regulation, so no fallback is allowed. What changes?"
The indicator moves into the readiness group, because a pod that cannot score cannot legally serve, and refusing traffic is now the correct behaviour.
But putting one vendor's health in readiness across every pod means their blip removes our whole service, so I would soften the edge: the indicator reports DOWN only after the breaker has been open for a sustained window, say 30 seconds, rather than on a single failed probe, and the readiness probe's
failureThresholdadds another 15 seconds.Requests that arrive while scoring is down get a fast 503 with
Retry-Afterinstead of a timeout.And I would push back on the requirement's edge: often "mandatory" means every order must be scored before fulfilment, not before acceptance, in which case the honest design is to accept the order, queue it, and score asynchronously.
the group after the requirement changeruns offlinegroup: readiness.include: readinessState,fraudApi # now mandatory; DOWN only after the breaker has been open about 30 s- "What would you cut with one afternoon?"
I would cut the custom DEGRADED status, the separate health group, and the health cache tuning, and ship two things: the Observation around the client call, which gives the timer, the error tags, and tracing in a few lines, and the circuit breaker with its state gauge.
Alerts come from those two metrics. The health indicator can wait, because a metric on real traffic is a better signal than a synthetic probe anyway; when it is added, its main value is for a human looking at
/actuator/healthduring an incident.What I would refuse to cut is the timeout on the client call, because without it the indicator and the metrics measure a hang, not an outage.
- "Why
Observationrather than a plainTimer?" A Micrometer
Timergives me latency and count with tags.An
Observationfrom the Observation API, when theObservationRegistryis configured by Boot, produces the same timer and additionally a trace span with the same name, a log correlation through MDC, and a consistent set of key-values across all three, from oneobservation.observe(() -> client.score(req))call.It also has a handler pipeline, so a low-cardinality tag such as
outcomegoes to metrics while a high-cardinality one such as the request id goes only to the span.Boot's
RestClient.Builderalready applies an observation per HTTP call, so for a client the extra observation is mostly for naming the business operation rather than the URL.what goes whereruns offlineObservation.createNotStarted("fraud.api.call", registry) .lowCardinalityKeyValue("vendor", "acme") // metrics and span .highCardinalityKeyValue("request.id", requestId) // span only .observe(() -> client.score(req));- "How do you keep the health check from becoming an outage of its own at 10× the pod count?"
With 500 pods probing every 5 seconds, a synthetic status call per probe is 100 requests per second to the vendor, which some vendors rate-limit, and a rate-limited status check shows DOWN and takes the fleet with it. Three controls.
The health cache TTL,
management.endpoint.health.cache.time-to-live=10s, halves it. The indicator reads the breaker state and the last real call's result instead of making a call, which makes it free, and only makes a synthetic call when there has been no real traffic for a minute.And the readiness group excludes it, so the probe frequency does not translate into vendor calls at all; only the human-facing health endpoint does.
The last group of this section tests the less common container tools, what the Boot 4 line changed, and whether you know when Boot itself is the wrong choice.
Q31. "What are FactoryBean and ObjectProvider, and when would each be the right tool?"
Reveal answer
Strong answer A FactoryBean<T> is a bean whose job is to produce another object.
- The container registers the factory under a name, but when you ask for that name you get the product,
T, not the factory. - Asking for
&namewith an ampersand prefix returns the factory itself. - It predates
@Beanmethods and survives because some products need lazy or complex construction that a method cannot express well. Spring's ownLocalContainerEntityManagerFactoryBeanand the Spring Data repository factories areFactoryBeans. - In application code a
@Beanmethod is nearly always clearer, so you would write aFactoryBeanonly when writing framework-style infrastructure.
ObjectProvider<T> is an injection-point type that defers the lookup:
getObject()resolves on call.getIfAvailable()returns null instead of failing when no bean exists.getIfUnique()handles ambiguity gracefully.orderedStream()gives all candidates in order.
It is right for optional dependencies, for prototype beans consumed by singletons, for breaking a cycle without @Lazy, and in library configuration where a bean may or may not be present. Boot's auto-configurations use ObjectProvider heavily for exactly that optional-dependency pattern.
Picture it One name that returns a product instead of its factory, and one injection point that turns a missing bean into a return value.
The setup
class ClientFactoryBean implements FactoryBean<HttpClient> {
public HttpClient getObject() { return HttpClient.newHttpClient(); } // the product
public Class<?> getObjectType() { return HttpClient.class; }
}
@Bean ClientFactoryBean httpClient() { return new ClientFactoryBean(); }
@Service
class Notifier {
Notifier(ObjectProvider<SmsGateway> sms) { // no SmsGateway bean exists in this app
SmsGateway g = sms.getIfAvailable(NoopSms::new); // ✅ resolved when asked, with a fallback
}
}
Make the invisible visible
# illustrative output
ctx.getBean("httpClient") -> java.net.http.HttpClient (the product)
ctx.getBean("&httpClient") -> com.acme.ClientFactoryBean (the factory itself)
ctx.getBean(HttpClient.class) -> the product, found through getObjectType()
What you see
# illustrative output
Notifier(SmsGateway sms) { } // ❌ TRAP when no SmsGateway bean exists
Parameter 0 of constructor in com.acme.Notifier required a bean of type 'com.acme.SmsGateway' that could not be found.
Why A factory bean sits behind the name and hands out its product. A provider moves the lookup from injection time to call time, so absence becomes a return value instead of a startup failure.
Comparison
| Code | No bean exists | Two beans, none primary |
|---|---|---|
SmsGateway sms constructor parameter | Startup fails, no qualifying bean | Startup fails, not unique |
Optional<SmsGateway> parameter | Empty, resolved once at injection | Startup fails, not unique |
provider.getIfAvailable() | Returns null | Throws not unique |
provider.getIfUnique() | Returns null | Returns null |
provider.getObject() | Throws no such bean, at call time | Throws not unique, at call time |
provider.orderedStream() | Empty stream | Both, sorted |
Land it FactoryBean is for producing beans in framework code; ObjectProvider is for consuming beans that may be absent, many, or short-lived.
- "What goes wrong with
FactoryBeanand type matching, and how do you avoid it?" When the container needs to know the type of a bean produced by a
FactoryBeanfor autowiring, it callsgetObjectType().If that returns null, which happens when the product type depends on configuration not yet available, the container may have to instantiate the factory early to discover the type, which can pull in dependencies before post-processors have run and trigger the "not eligible" warning.
It also makes
@ConditionalOnBeanon the product type unreliable, because the type is unknown at condition time. The fix is to makegetObjectType()answer without instantiation, ideally from a constructor argument, and to declare the generic type on the bean definition.Spring Data's repository factories do this carefully, which is why
@ConditionalOnBean(OrderRepository.class)works.a type answer that needs no instantiationruns offlinepublic Class<?> getObjectType() { return HttpClient.class; } // ✅ constant: no dependencies pulled in early // ❌ TRAP: returning null here forces the container to instantiate the factory to learn the type- "How does
ObjectProviderresolve, and what is the cost of callinggetObject()on a hot path?" ObjectProvider.getObject()performs a fullgetBeanby type each call: it resolves candidates, applies primary and priority rules, and for a singleton returns the cached instance from the singleton map.For a singleton the cost is a few hundred nanoseconds of lookup, which is acceptable in most code but not free, so I cache the result in a field on first use when the provider is for an optional singleton.
For a prototype the cost is a full bean creation, which is the point. Since Spring 5.1,
getIfAvailable(Supplier)andifAvailable(Consumer)avoid null checks, andorderedStream()returns all candidates sorted, which is how I would write a plugin registry that respects@Order.- "When would you reach for
ObjectProviderinstead ofOptionalor@Autowired(required=false)?" When the resolution should be deferred or repeated.
Optional<T>is resolved once at injection time, so the bean must be creatable then; that is fine for a plain optional dependency and reads best.ObjectProvider<T>resolves when I ask, so it handles a prototype per call, a bean that would create a cycle if resolved eagerly, and a bean that is expensive and rarely needed, all without changing the consumer's constructor shape.In library auto-configuration it is the standard because the library cannot know whether the application defined the bean, and because Boot's
@Beanmethods use it to accept zero-or-more customizers withorderedStream().required=falsewith a nullable field I avoid because it moves the check to every use site.- "Boot's own
@Beanmethods takeObjectProvider<List<X>>sometimes. Why the extra layer?" A parameter of type
List<X>is resolved by collecting every bean of type X, and if none exist the injection fails for a required parameter.Wrapping it in
ObjectProvidermakes the whole list optional and lazily resolved:provider.getIfAvailable(Collections::emptyList)gives an empty list when there are no customizers, and it defers creating them until the enclosing bean is actually built, which matters for ordering.Boot 2.x used that shape widely; newer code uses
ObjectProvider<X>withorderedStream().toList(), which is equivalent and respects ordering. Either way the intent is the same: accept any number of contributions, including zero, without forcing their creation.accepting zero or more contributionsruns offlineObjectProvider<MapperCustomizer> customizers = ...; customizers.orderedStream().forEach(c -> c.customize(builder)); // zero customizers: nothing happens, no failure
Q32 · Scenario. "The service takes 90 seconds to start in the cluster and 12 seconds locally. Same jar, same JVM flags. Walk me through finding the cause."
Reveal answer
Strong answer In diagnosis order:
- Symptom: an 8x startup difference between environments with identical code, which means the difference is in something the startup path waits on, not in CPU work.
- Evidence to collect: enable the startup timeline with
BufferingApplicationStartupand read/actuator/startup, or simply diff the timestamps in the startup log, to find the gap. Take a thread dump 30 seconds in withjcmd <pid> Thread.printand look at what the main thread is blocked on. Compare the pod's CPU request and limit against the laptop. - Likely causes, ranked:
- CPU throttling. A pod with a 500 millicore limit gets throttled hard during the JIT-heavy first seconds, and startup is CPU-bound.
- A blocking call during startup. Examples: Hibernate's
ddl-auto=validateagainst a remote database, Flyway migrations, a Vault or config-server fetch, or a@PostConstructthat calls a service with no timeout. - DNS or service-mesh sidecar readiness. The app starts before the Envoy sidecar, and every outbound call waits for a timeout.
- Entropy shortage on older images, where
SecureRandomblocks (-Djava.security.egd=file:/dev/./urandom).
- Fix per cause:
- Raise the CPU limit for startup, or use a startup probe with a longer budget.
- Move blocking work to an async runner with timeouts.
- Set
holdApplicationUntilProxyStartsfor the mesh. - Consider the JDK AOT cache or a CDS archive to cut the JIT-bound part.
- Prevention: record startup time as a metric and alert on regression, and keep a startup budget in the deployment checklist.
Picture it Where 90 seconds go: a throttling counter, a startup step list, and a thread dump that shows what the main thread is waiting for.
The setup
# laptop: 8 cores, no limit -> 12 s
# cluster pod:
resources:
requests: { cpu: 500m }
limits: { cpu: 500m } # ❌ TRAP: a quota of 50 ms of CPU per 100 ms, shared by all threads
# Result: 90 s to start, and part of that is waiting on the network
Make the invisible visible
# illustrative output
step tag duration
spring.beans.instantiate flywayInitializer 41.2 s <- gap: waiting on the database
spring.beans.instantiate entityManagerFactory 9.8 s
spring.context.refresh 74.0 s
# illustrative output
container_cpu_cfs_throttled_seconds_total{pod="orders-7d9"} 412 # rising during startup
The trace
SpringApplication.run()
├─► class loading, JIT, GC threads ✗ throttled: quota gone after ~20 ms of each 100 ms
├─► flywayInitializer ──► migrate() ✗ 41 s waiting on a slow database connection
└─► envoy sidecar not ready ──► outbound call times out ✗ per call, until the sidecar is up
What you see
# illustrative output
"main" #1 prio=5 RUNNABLE
at java.base/sun.nio.ch.SocketDispatcher.read0(Native Method)
at org.postgresql.core.PGStream.receiveChar(...)
at org.flywaydb.core.Flyway.migrate(...)
at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(...)
Why Startup does not do 90 seconds of work. It waits, either for CPU it is not allowed to use or for a network answer, and the thread dump shows which.
The fix
resources:
requests: { cpu: 500m } # ✅ FIX: keep the request, drop the limit
startupProbe:
httpGet: { path: /actuator/health/liveness, port: 8080 }
periodSeconds: 10
failureThreshold: 30 # ✅ FIX: 5 minutes of budget before liveness starts
What you see now
# illustrative output
container_cpu_cfs_throttled_seconds_total 0
Started OrderApplication in 14.1 seconds
Decision table
| Symptom | Root cause | Action |
|---|---|---|
| Throttle metric climbs, main thread busy | CPU limit, startup is the most parallel phase | Raise or remove the limit, startup probe |
| Main thread in a socket read under Flyway, Hikari, Vault or the JWT decoder | Network wait | Fix DNS or the security group, add timeouts, move work off the main thread |
| Every outbound call times out early in startup | App up before the mesh sidecar | holdApplicationUntilProxyStarts |
Main thread blocked in SecureRandom | Entropy shortage on an older image | -Djava.security.egd=file:/dev/./urandom |
Land it A big environment-only startup gap is always either a CPU limit or a network wait, and the thread dump at 30 seconds tells you which.
- "You raised the CPU limit and startup only dropped to 70 seconds. What next?"
Then CPU was part of it but the main wait is elsewhere, and the thread dump is the next step, not more tuning. I would take three dumps ten seconds apart with
jcmd 1 Thread.printin the pod and look at the main thread's stack in each: if it is inside a socket read underHikariPool.checkFailFast, the database connection is slow, which is often DNS or a security group; underFlywayAutoConfiguration, migrations are running against a large table; underConfigDataEnvironmentPostProcessor, a config import from Vault or a config server is waiting; underNimbusJwtDecoderorJwtDecoders.fromIssuerLocation, the resource server is fetching the OpenID discovery document from an identity provider that is slow from this cluster. Each of those has a specific fix, and the dump names which one.- "Why is a 500 millicore limit so much worse than half a core sounds?"
A CPU limit in Kubernetes is enforced by the cgroup CFS quota: the container gets 50 milliseconds of CPU time per 100 millisecond period across all threads, and once spent, every thread is frozen until the next period.
Startup is the most parallel, CPU-hungry phase of a JVM's life: the JIT compiler threads, the GC threads, and the main thread all want CPU at once, so the quota is exhausted in the first 20 milliseconds of each period and the process is throttled 80 percent of the time.
On top of that, the JVM sizes its JIT and GC thread pools from the container's CPU count, which is 1 for a limit below 1000m, so compilation is serialised. The metric to look at is
container_cpu_cfs_throttled_seconds_total.The common fix is to remove the CPU limit and keep the request, or to set the limit to at least 2 cores.
one 100 ms period under a 500m limitruns offlinet= 0..20 ms JIT, GC and main threads all running quota (50 ms of CPU, summed over threads) spent t= 20..100 ms every thread frozen ✗ throttled about 80 percent of the time- "What does the JDK AOT cache or CDS actually save here, and how do you set it up?"
Class Data Sharing stores pre-parsed class metadata in an archive so class loading and verification are skipped; Boot 3.3 and later support it through an extracted layout: run
java -Djarmode=tools -jar app.jar extract --layers --destination out, then a training run with-XX:ArchiveClassesAtExit=app.jsaand-Dspring.context.exit=onRefresh, and start production with-XX:SharedArchiveFile=app.jsa.the three CDS stepsruns offlinejava -Djarmode=tools -jar app.jar extract --layers --destination out java -XX:ArchiveClassesAtExit=app.jsa -Dspring.context.exit=onRefresh -jar app.jar # training run java -XX:SharedArchiveFile=app.jsa -jar app.jar # productionThat typically cuts JVM startup by 30 to 40 percent. The JDK AOT cache from JEP 483 in JDK 24 and JEP 514 and 515 in JDK 25 extends this to loaded and linked classes and method profiles, with
-XX:AOTCache, for another sizeable gain.Neither helps with a network wait, so I would only reach for them after the thread dump has shown the startup to be CPU-bound.
- "How do you keep this from regressing at 10× the service count?"
Measure it as a first-class metric. Boot's
application.started.timeandapplication.ready.timegauges are published to Micrometer automatically, so a fleet dashboard can show startup time per service per version, and an alert fires when a deploy's ready time exceeds the previous version's by 50 percent.Second, a platform default of no CPU limit and a startup probe generated from the measured p99 startup with margin, so nobody hand-picks probe numbers.
Third, a startup budget in the platform starter: an
ApplicationListenerthat logs a WARN with the/actuator/startuptop five steps whenever ready time exceeds a configured threshold, which turns the investigation from a thread dump into a log line.
Q33. "What does Actuator expose by default, what is dangerous about the rest, and how do you run it safely in production?"
Reveal answer
Strong answer By default only /actuator/health is exposed over HTTP, with details hidden. Every endpoint is enabled but not web-exposed, and you opt in with management.endpoints.web.exposure.include.
The dangerous ones:
envandconfigpropsreveal configuration, and while Boot masks keys that look like secrets, it cannot recognise every secret.heapdumphands out the entire heap, including session tokens and customer data in memory.threaddumpreveals internals.loggerslets a caller set a logger to TRACE and flood the disk.shutdownstops the process.mappingsandbeansdescribe your attack surface.
Running it safely:
- Bind management to a separate port with
management.server.port=8081, reachable from the cluster network and the metrics scraper but not from the ingress. - Expose only
health,info,prometheus,metricsthere. - Require authentication for anything else through a dedicated
SecurityFilterChainmatched withEndpointRequest.toAnyEndpoint(). - Keep
show-detailsatwhen-authorized. - Never enable
shutdown, since Kubernetes handles lifecycle.
Health groups get their own paths, management.endpoint.health.probes.enabled=true, and Boot also adds /livez and /readyz style paths when running in Kubernetes.
Picture it Two ports, who can reach each, and what the same debugging mistake exposes on the app port versus the management port.
The setup
management:
server:
port: 8081 # ✅ FIX: own port, not routed by the ingress
endpoints:
web:
exposure:
include: health,info,prometheus,metrics # ✅ FIX: opt in to four endpoints only
endpoint:
health:
show-details: when-authorized
probes:
enabled: true
# the mistake, set while debugging:
# management.endpoints.web.exposure.include: "*" ❌ TRAP, together with permitting /actuator/** on the app port
Make the invisible visible
# illustrative output
port 8080 (app, behind the ingress) /orders /customers ... /actuator -> 404 once management has its own port
port 8081 (management, cluster only) /actuator/health /actuator/info /actuator/prometheus /actuator/metrics
not exposed anywhere env configprops heapdump threaddump loggers shutdown mappings beans
The trace
internet ──► ingress ──► :8080 /orders ✓
internet ──► ingress ──► :8080 /actuator/heapdump ✗ 404, not routed to anything
Prometheus scraper ──► :8081 /actuator/prometheus ✓ allowed by network policy
kubelet ──► :8081 /actuator/health/readiness ✓ allowed by network policy
internet ──► :8081 ✗ no route, ingress does not publish this port
What you see
# illustrative output, exposure.include=* and /actuator/** permitted on the app port
$ curl -s -o /dev/null -w "%{http_code} %{size_download}\n" https://shop.example.com/actuator/heapdump
200 431204352 # the whole heap, session tokens included
$ curl -X POST https://shop.example.com/actuator/loggers/ROOT -H 'Content-Type: application/json' -d '{"configuredLevel":"TRACE"}'
204 # disk fills with TRACE output
Why Actuator is an admin interface. On the app port it shares a route with customer traffic, so a single wrong property makes it public. A separate port that the ingress does not publish stays unreachable even if the security chain is wrong.
The fix The safe configuration at the top: own port, four endpoints, details only when authorized.
What you see now
# illustrative output
$ curl -s -o /dev/null -w "%{http_code}\n" https://shop.example.com/actuator/heapdump
404
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST https://shop.example.com/actuator/loggers/ROOT
404
Comparison
| Endpoint | What a caller gets | Rule |
|---|---|---|
health | Status, details hidden | Exposed by default, details when-authorized |
env, configprops | Configuration, masking by key name only | Not exposed on any reachable path |
heapdump | The whole heap | Never exposed |
loggers | Can set a logger to TRACE | Authenticated, management port only |
shutdown | Stops the process | Never enabled |
Land it Treat Actuator as an admin interface, put it on its own port, and let only the scraper and the probes in.
- "How does the secret masking on
/actuator/envwork, and why do you not trust it?" Boot's
Sanitizermasks a property's value if its key matches a built-in pattern: keys containingpassword,secret,key,token,credentials, and a few more, plusvcap_servicesand URI-style values with embedded credentials.Since Boot 3.0 the default is stricter:
management.endpoint.env.show-valuesisneverby default, so all values are masked unless set towhen-authorizedoralways.I do not trust masking as a security boundary because it depends on naming: a key called
partner.gateway.author a JSON blob inSPRING_APPLICATION_JSONcontaining a secret is not matched.A
SanitizingFunctionbean lets me add rules, but the honest protection is not exposingenvon any network path an attacker can reach.masking depends on the key nameruns offline# illustrative output, management.endpoint.env.show-values=always spring.datasource.password ****** partner.gateway.auth s3cr3t-token-value ✗ key name not recognised as a secret- "What do you gain from the separate management port beyond network isolation?"
Three things. The management port runs on its own Tomcat connector with its own thread pool, so a flood of probe or scrape requests, or a heap dump in progress, cannot exhaust the application's request threads, and a saturated application still answers its health probe.
It gets its own
management.server.address, so I can bind it to the pod IP only, or with a sidecar to localhost.And it gives a clean security split: the application chain does not need to know Actuator exists, and the management chain is built from
EndpointRequestmatchers in one place.The cost is that the kubelet must reach that port, which needs the probe definition to name it, and a network policy that allows the scraper and the kubelet and nothing else.
- "Someone argues that authentication on Actuator is enough and the separate port is overkill. Your answer?"
Authentication protects against unauthorised callers if it is configured correctly on every service forever. The separate port protects against the configuration being wrong, because a port the ingress does not route to is unreachable regardless of the security chain.
Defence in depth is the argument, but the concrete case is Q70's pen-test finding: a service where someone set
exposure.include=*and permitted/actuator/**while debugging. With a management port that is not routed, that mistake exposes nothing to the internet.I use both: the port as the boundary and authentication as the control inside it, with the platform starter setting both by default so a team has to work to undo them.
- "What is the Boot 4 or Framework 7 state of Actuator security, anything new?"
As of Aug 2026 the model is the same, with a few tightenings that arrived through the Boot 3.x line and carry into 4:
show-values=neverby default on env and configprops, theheapdumpendpoint requiring explicit inclusion, andEndpointRequestmatchers that understand health groups and additional paths.Boot 3.4 added
management.endpoint.<id>.accesswith valuesnone,read-only, andunrestricted, replacing the olderenabledflag, so a write operation like the loggers endpoint's level change can be turned off while reads stay available; Boot 4 keeps that.The SBOM endpoint and the per-endpoint access model are the two things I would mention as recent.
Q34 · Design. "Design a custom Actuator endpoint that lets operators see and reset the state of the circuit breakers in a service, safely."
Reveal answer
Strong answer Requirements: read state for all breakers, force one closed or open during an incident, audit who did it, and never expose it to the public.
Design, piece by piece:
- Endpoint. A
@Component @Endpoint(id = "breakers")class. Its@ReadOperationreturns a list of breaker name, state, failure rate, and last transition time, taken from Resilience4j'sCircuitBreakerRegistry. - Write. A
@WriteOperationtakesnameandaction(close,open,reset) and callstransitionToClosedStateand friends. - Why
@Endpoint, not a controller. It lives on the management port, is discoverable at/actuator, works over JMX too, and inherits the Actuator security chain. - Exposure and security. Opt-in with
include=breakers, and the write operation is guarded by the endpoint security rule requiring theopsrole. - Audit. Every write logs the principal from the security context, the action, and the before and after state at WARN level, and publishes an
AuditApplicationEventso it lands in the audit trail. - Expiry. Forced states are temporary by design: the write accepts a
ttlSecondsand a scheduled task returns the breaker to automatic mode afterwards, so a forgotten override cannot outlive the incident.
Trade-offs: a per-pod endpoint acts on one instance, so the runbook uses a label-selected loop across pods or a central control plane later.
What I would not do:
- Expose this on the application port.
- Allow anonymous writes.
- Let an override be permanent.
Picture it One operator write, hop by hop, and the log and audit lines it leaves behind.
The setup
@Component
@Endpoint(id = "breakers")
class BreakersEndpoint {
private final CircuitBreakerRegistry registry;
BreakersEndpoint(CircuitBreakerRegistry registry) { this.registry = registry; }
@ReadOperation
List<BreakerView> breakers() { /* name, state, failure rate, last transition */ return List.of(); }
@WriteOperation // POST /actuator/breakers/{name}
void force(@Selector String name, String action, @Nullable Long ttlSeconds) {
CircuitBreaker cb = registry.circuitBreaker(name);
switch (action) {
case "close" -> cb.transitionToClosedState();
case "open" -> cb.transitionToForcedOpenState();
case "reset" -> cb.reset();
default -> throw new IllegalArgumentException(action);
}
// log principal, before and after at WARN; publish AuditApplicationEvent; schedule reset() after ttlSeconds
}
}
Make the invisible visible
# illustrative output
$ curl :8081/actuator/breakers
[{"name":"fraudApi","state":"OPEN","failureRate":100.0,"lastTransition":"2026-03-02T12:00:09Z"},
{"name":"inventory","state":"CLOSED","failureRate":0.4,"lastTransition":"2026-03-02T08:12:44Z"}]
$ curl -X POST :8081/actuator/breakers/fraudApi -H 'Content-Type: application/json' -d '{"action":"close","ttlSeconds":600}'
The trace
POST :8081/actuator/breakers/fraudApi {"action":"close","ttlSeconds":600}
└─► management SecurityFilterChain no ROLE_OPS_WRITE ✗ 401 or 403, nothing changes
└─► management SecurityFilterChain ROLE_OPS_WRITE present ✓
└─► BreakersEndpoint.force("fraudApi", "close", 600)
├─► cb.transitionToClosedState() ✓ OPEN -> CLOSED
├─► WARN log + AuditApplicationEvent ✓ who, what, before, after
└─► scheduled reset() at +600 s ✓ override cannot live forever
What you see
# illustrative output
WARN BreakersEndpoint : principal=alice action=close breaker=fraudApi before=OPEN after=CLOSED ttl=600s
audit type=BREAKER_OVERRIDE principal=alice data={breaker=fraudApi, action=close}
12:10:09 WARN BreakersEndpoint : ttl expired, breaker=fraudApi returned to automatic mode (reset)
Why The incident that needs the override is also the moment mistakes are most likely, so every write needs a guard, a record and an end time.
Decision table
| Symptom | Root cause | Action |
|---|---|---|
| Anyone can flip a breaker | Write operation not covered by a security rule | Require the ops role on the endpoint, a stricter one for POST |
| A breaker stays forced for days | No expiry on the override | ttlSeconds and a scheduled return to automatic |
| Nobody knows who flipped it | No audit | WARN log with the principal plus AuditApplicationEvent |
| Only one pod changed | The endpoint acts on its own registry | Loop over pods in the runbook, or shared state later |
Land it Operator controls belong on the management port with authentication, audit, and an expiry, because the incident that needs them is exactly when mistakes are most likely.
- "Requirement change: a forced state must apply to all 20 pods at once. How does the design change?"
A per-pod endpoint cannot do that, so the source of truth moves to shared state and each pod follows it.
I would keep the endpoint for reading, and for writes, publish the override to a shared store: a row in a small table or a Redis key with the breaker name, the forced state, and the expiry.
Each pod polls it every 5 seconds, or subscribes to a Redis channel for immediacy, and applies the transition locally.
The endpoint's write operation on any pod writes to the store rather than to its own registry, and the audit event is written once, at the store, with the principal.
The trade-off is a dependency on the store during an incident; if the store is unavailable the pods keep automatic mode, which is the safe direction.
the shared override recordruns offline# illustrative output breaker_override name forced_state expires_at set_by fraudApi FORCED_OPEN 12:10:00 alice <- each pod polls every 5 s and applies it locally- "What would you cut with one hour?"
The read operation and nothing else. A read-only
@Endpointwith a@ReadOperationthat returns each breaker's name, state, and failure rate takes twenty minutes and is immediately useful in an incident.The write operation, the expiry, and the audit event are the parts where a mistake is dangerous, so if I cannot do them properly, I do not ship them; operators can restart a pod to reset its breakers, which is crude but safe.
I would also mention that Resilience4j's own Boot starter already registers a
circuitbreakersendpoint with read and a state transition write, so for a first hour the real answer might be to expose that and move on.- "How do you test an
@Endpoint, and how do you secure its write operation specifically?" @WebEndpointTestis not public, so I test with@SpringBootTest(webEnvironment = RANDOM_PORT)plusmanagement.endpoints.web.exposure.include=breakersand aTestRestTemplateorRestClientagainst/actuator/breakers, asserting the JSON shape for the read and the state change for the write. For security, the management chain usesrequestMatchers(EndpointRequest.to("breakers")).hasRole("OPS"); to distinguish read from write I add a matcher on HTTP method, since Actuator maps@WriteOperationto POST, sorequestMatchers(HttpMethod.POST, "/actuator/breakers/**").hasRole("OPS_WRITE"). Boot 3.4's per-endpointaccess=read-onlysetting is a coarser switch that disables the write entirely in environments where no human should be flipping breakers.separate rules for read and writeruns offline.requestMatchers(HttpMethod.POST, "/actuator/breakers/**").hasRole("OPS_WRITE") // write: POST, checked first .requestMatchers(EndpointRequest.to("breakers")).hasRole("OPS") // read- "Why not a plain
@RestControlleron the management port instead of an@Endpoint?" Controllers cannot be placed on the management port; the management context only serves Actuator endpoints.
An
@Endpointalso gets the surrounding conventions: it appears in the/actuatordiscovery document, it is automatically available over JMX, it is disabled unless included, its operations map to GET, POST, and DELETE by annotation, and it participates inEndpointRequestsecurity matchers.A controller on the application port would need me to reinvent each of those and would sit on the same port as customer traffic.
The one case for a controller is when the operation must be part of the application's public API, which an incident control never should be.
Q35. "What changed in the container and platform between Spring Boot 3.5 and 4.0 that you would need to know for a migration? Give the top items."
Reveal answer
Strong answer As of August 2026, Boot 4.0 shipped in November 2025 on Spring Framework 7.0, and the important shifts are these.
- Platform. The Java baseline is 17, with 21 and 25 recommended. It uses the Jakarta EE 11 APIs (Servlet 6.1, Persistence 3.2) with Tomcat 11 and Hibernate ORM 7.
- JSON. Jackson 3, whose packages are
tools.jacksonrather thancom.fasterxml.jackson, with new defaults. The customiser type changed toJsonMapper.Builder, and annotations stay incom.fasterxml.jackson.annotation. - Modules and starters. The autoconfigure jar was split into per-technology modules, so custom auto-configurations that referenced classes by package may need new dependencies. Starters gained more precise names such as
spring-boot-starter-webmvc. - Null safety. JSpecify annotations across the framework, which surfaces as new IDE warnings.
- Spring Framework 7. API versioning in
@RequestMapping, HTTP service clients registered through@ImportHttpServices, and core resilience annotations@Retryableand@ConcurrencyLimit. - Removed items you hit first.
@MockBeanand@SpyBean(use@MockitoBeanand@MockitoSpyBean), thespring.factoriesauto-configuration key,RestTemplatebuilder details, and everything deprecated in 3.x. - Security and shutdown. Spring Security 7 removed the last of the pre-lambda DSL and
WebSecurityConfigurerAdapterremnants. Graceful shutdown became the default. - The deadline. Boot 3.5 itself reached open-source end of life on 30 June 2026, so the migration is not optional for anyone wanting security patches.
Picture it The same small service on 3.5 and on 4.x, the compile error that shows first, and the order the migration runs in.
The setup
@SpringBootTest
class PaymentTest {
@MockBean PaymentClient client; // ❌ TRAP on 4.x: removed, compile error
@Test void pays() { }
}
@Bean Jackson2ObjectMapperBuilderCustomizer naming() { // Jackson 2 customiser type, see the JSON item above
return b -> b.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
}
What you see
# illustrative output
PaymentTest.java:[9,6] error: cannot find symbol
symbol: class MockBean
The fix
@SpringBootTest
class PaymentTest {
@MockitoBean PaymentClient client; // ✅ FIX: Spring Framework's annotation
@Test void pays() { }
}
// customiser: JsonMapperBuilderCustomizer for Jackson 3's JsonMapper.Builder (see Q39)
// annotations such as @JsonProperty stay in com.fasterxml.jackson.annotation
Make the invisible visible
phase what you run what you read
1 latest 3.5 patch build, fix deprecations spring-boot-properties-migrator report at startup
2 OpenRewrite UpgradeSpringBoot_4_0 recipe diff: Jackson imports, test annotations, starter names
3 compile build errors: Jackson 3 API differences, removed classes
4 integration suite Testcontainers against Hibernate 7 failures, JSON snapshot diffs
5 staging deploy, JVM flags unchanged startup time and error rate versus 3.5
Comparison
| Code line | On 4.x |
|---|---|
@MockBean PaymentClient client; | Compile error, removed |
@MockitoBean PaymentClient client; | Works |
@JsonProperty("order_id") on a field | Works, annotations stay in com.fasterxml.jackson.annotation |
Jackson2ObjectMapperBuilderCustomizer bean | Does not target Jackson 3, use JsonMapperBuilderCustomizer |
Library registered only through the old spring.factories key | Silently not applied |
Land it The migration is mostly mechanical, Jackson 3 and the test mock annotations are where the real work is, and the deadline is set by 3.5's end of life, not by features.
- "What is the concrete migration sequence you would run for one service, and how long does it take?"
First, get onto the latest 3.5 patch and fix every deprecation warning, because 4.0 removes what 3.x deprecated; Boot's
spring-boot-properties-migratordependency reports renamed properties at startup. Second, run the OpenRewrite recipeorg.openrewrite.java.spring.boot4.UpgradeSpringBoot_4_0, which rewrites Jackson imports, test annotations, and starter names.Third, build, fix compile errors, mostly Jackson 3 API differences and removed classes. Fourth, run the integration suite with Testcontainers against Hibernate 7 and check query behaviour, then review JSON snapshots for format changes.
Fifth, deploy to staging with the JVM flags unchanged and compare startup time and error rates. For a typical mid-sized service I have seen this take two to five days, with Jackson customisations and any custom auto-configuration being where the days go.
- "Which of these changes can break a running service without a compile error?"
Three. Jackson 3's defaults: dates serialise as ISO strings instead of epoch numbers,
FAIL_ON_UNKNOWN_PROPERTIESis off by default, and some nullability and case-insensitivity defaults changed, so wire formats change while everything compiles.Auto-configuration registration: a library that registered through
spring.factoriesstops applying with no error, so its beans vanish and conditions elsewhere flip. And Hibernate 7's stricter handling of some JPQL and its changed defaults for a few dialect behaviours, which appear only against a real database.None of these are visible in a unit test with mocks, which is why I insist on contract tests for JSON and a Testcontainers suite before calling the migration done.
registering through the imports fileruns offline# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports com.vendor.VendorAutoConfiguration- "Why is the Java baseline 17 when the recommendation is 21 or 25?"
The baseline is the minimum the framework compiles against so that organisations still on 17 can upgrade Boot without a JDK change on the same day.
The recommendation is where the benefits are: virtual threads need 21, and the JDK 24 monitor rewrite and the JDK 25 AOT cache are what make virtual threads and fast startup work well in practice.
As of Aug 2026, 25 is the current long-term support release and 21 is the previous one.
My advice in a migration is to do the Boot 4 upgrade on the JDK you already run to keep the change set small, then move JDK as a separate change with its own canary, because a JDK upgrade changes GC behaviour and that deserves its own observation window.
- "What is the JSpecify change, and does it affect behaviour?"
JSpecify is a set of nullness annotations,
@NullMarkedand@Nullable, that Spring Framework 7 applies across its own API instead of its olderorg.springframework.langannotations. It does not change runtime behaviour at all; it is compile-time information for IDEs and tools like NullAway, so calling a method that may return null without a check now shows a warning where before it was silent. The practical effect in a migration is a wave of IDE warnings, some of which are real bugs, and an opportunity: annotating your own packages with@NullMarkedmakes the checker cover your code too, which is the cheapest static analysis you can turn on.
Q36 · Scenario. "After bumping a service from Boot 3.5 to 4.x, the build fails on @MockBean, then at runtime a partner library's auto-configuration silently stops applying, and JSON dates change format. Order your fixes."
Reveal answer
Strong answer In diagnosis order:
- Compile errors first, because nothing else can be observed until the build passes.
@MockBeanwas deprecated in Boot 3.4 and removed in 4.0; replace with Spring Framework's@MockitoBeanand@SpyBeanwith@MockitoSpyBean. OpenRewrite's Boot 4 migration recipe does this mechanically along with the Jackson package renames. - The silent auto-configuration loss: run with
--debugand check whether the partner's classes appear in the report at all.- If they are absent, the library still registers through the old
spring.factorieskey or depends on a class from the pre-split autoconfigure jar. - Fix by upgrading the library to a Boot-4-compatible release.
- As a bridge, add an
AutoConfiguration.importsfile in your own project that lists the partner's configuration classes, and add the now-separatespring-boot-*-autoconfiguremodule they need.
- If they are absent, the library still registers through the old
- The JSON date format: Jackson 3 changed defaults, including writing dates as ISO-8601 strings instead of timestamps and not failing on unknown properties.
- If clients depend on the old wire format, pin the old behaviour explicitly with
spring.jackson.serialization.write-dates-as-timestamps=trueor aJsonMapper.Buildercustomiser. - Treat it as an API contract to migrate deliberately with a versioned endpoint later.
- If clients depend on the old wire format, pin the old behaviour explicitly with
- Then run the full integration suite with Testcontainers, because Hibernate 7 and Spring Data changes surface only against a real database.
- Prevention: adopt a Boot minor within two months of release on one low-risk service, so the next major is a set of known deltas rather than a cliff.
Picture it Three symptoms from one version bump, laid out in the order they appear and the order they must be fixed.
The setup
1. PaymentTest.java: @MockBean PaymentClient client; // compile error on 4.x
2. partner-lib.jar: META-INF/spring.factories only // its auto-configuration stops applying
3. GET /orders/7 "createdAt": 1767225600000 -> "2026-01-01T00:00:00Z" // wire format changed, nothing failed
Make the invisible visible
# illustrative output, java -jar app.jar --debug
before the fix: Positive matches: (no entry for com.partner.PartnerAutoConfiguration)
Negative matches: (no entry either: the class was never considered)
after the bridge: Positive matches:
PartnerAutoConfiguration matched:
- @ConditionalOnClass found required class 'com.partner.PartnerClient'
The trace
build ───► compile errors ✗ @MockBean: nothing else can be observed until this passes
└─► start with --debug ✗ partner auto-configuration absent from the report
└─► call the API ✗ dates now ISO strings, clients may break
└─► Testcontainers suite ✗ Hibernate 7 and Spring Data differences, only against a real database
Why Each failure only becomes visible once the one before it is fixed. The compiler stops you first, then the wiring goes quiet, then the wire format shifts underneath clients.
The fix
# 1. test annotations
@MockBean -> @MockitoBean @SpyBean -> @MockitoSpyBean ✅ FIX
# 2. bridge for the partner library, in your own project
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.partner.PartnerAutoConfiguration ✅ FIX
# 3. pin the old wire format, deliberately
spring.jackson.serialization.write-dates-as-timestamps=true ✅ FIX
What you see now
# illustrative output
build: compiles
condition report: PartnerAutoConfiguration matched
GET /orders/7 "createdAt": 1767225600000
Decision table
| Order | Symptom | Root cause | Action |
|---|---|---|---|
| 1 | Build fails on @MockBean | Removed in 4.0 | @MockitoBean, @MockitoSpyBean, OpenRewrite recipe |
| 2 | Partner beans missing, no error | Old registration key or pre-split autoconfigure class | Upgrade the library, or an imports file as a bridge |
| 3 | JSON dates changed | Jackson 3 default | Pin explicitly, plan a versioned endpoint |
| 4 | Query or schema differences | Hibernate 7, Spring Data | Testcontainers suite |
Land it Fix in the order compile, wiring, wire format, because each layer hides the next, and treat serialisation defaults as part of your public API.
- "You added an imports file for the partner library and its configuration now fails with a
NoClassDefFoundError. What next?" The library's configuration class references a class that moved with the Boot 4 module split, so the auto-configuration is now found but cannot load. The error names the missing class; typically it is something like
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, which moved to a new package inspring-boot-jdbc.If the reference is in an
@AutoConfiguration(after = …)attribute, the class fails to load at all.Options: add the relevant Boot 4 module as a dependency if it only needs the module and not the old package; if it needs the old package, the library must be rebuilt, so I would fork it temporarily or copy its configuration class into my project with corrected imports until the vendor ships a Boot 4 release.
Pinning Boot 3.5 for that service until then is also acceptable, with a date.
what the error looks likeruns offline# illustrative output java.lang.NoClassDefFoundError: org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration at com.partner.PartnerAutoConfiguration ... # the class named here moved with the module split- "Why do you say treat the JSON defaults as a public API rather than just pinning the old behaviour?"
Pinning restores the old wire format today, but it accumulates: each migration adds another line of "keep the old behaviour", and a year later nobody knows which lines are load-bearing.
Treating the format as a contract means writing it down: a contract test that serialises representative objects and compares against checked-in JSON, so any change is a visible diff, and a versioning plan for the day we want the new format.
The pin becomes a deliberate, tested decision rather than a workaround, and clients get a migration path instead of a surprise.
It also separates the two questions, "what does Boot 4 do by default" and "what do our clients depend on", which are answered by different people.
- "What does
@MockitoBeanchange compared with@MockBeanbeyond the name?" @MockitoBeanlives in Spring Framework's test module rather than Boot's, so it works in plain Spring tests too. It can be applied to fields in the test class, and since Framework 6.2 also at the type level to mock beans by type without a field.A behavioural difference worth knowing: with
@MockitoBeanthe mock replaces the bean definition by type or name in the same way, but the context caching key changes, so tests that mixed the two annotations during migration end up with separate cached contexts and slower suites.It also does not support mocking a bean that does not exist unless you use the
enforceOverrideattribute, which catches tests that were mocking a typo. The migration is mechanical for the annotation but worth a look at test timing afterwards.- "How would you run this across 80 services without a month of downtime for feature work?"
Automate the mechanical part and stagger the rest. A platform engineer prepares the OpenRewrite run and the shared library updates, including the platform starter, and opens a pull request per service with the rewritten code, the dependency bumps, and a CI run.
Teams then own the remaining failures, which are the JSON and Hibernate checks, with a target of two weeks per wave of 15 services.
The wave order is by risk: internal tools first, then services with strong contract tests, then the customer-facing ones last with a canary.
Progress is tracked on a fleet dashboard from the
/actuator/infoBoot version, and the 3.5 end-of-life date is the hard deadline that justifies the schedule.
Q37. "What can you customise on SpringApplication before run(), and what is an EnvironmentPostProcessor for?"
Reveal answer
Strong answer SpringApplication is the bootstrapper. Before calling run() you can:
- set the
WebApplicationType(NONEfor batch jobs so no server starts,SERVLET,REACTIVE); - turn off the banner;
- add
ApplicationListeners that fire for early events likeApplicationEnvironmentPreparedEvent; - add
ApplicationContextInitializers that run before refresh; - set default properties;
- set the application startup recorder for the startup timeline;
- register a shutdown hook or not;
- specify additional primary sources.
The SpringApplicationBuilder gives a fluent version and can build parent-child context hierarchies, which is rare today.
An EnvironmentPostProcessor runs even earlier, after the Environment is built but before the context exists, and it can add or reorder property sources.
- It is registered in
META-INF/spring.factories. - It is the right tool for "load secrets from this vault and expose them as properties", "derive
spring.datasource.urlfrom a cloud platform's environment variable format", or "force a property that nobody may override". - Boot's own
ConfigDataEnvironmentPostProcessor, which loadsapplication.yml, is one, which tells you how foundational this hook is.
Picture it The order of hooks during startup, and the property source list one of them edits.
The setup
public class VaultSecretsPostProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication app) {
Map<String, Object> secrets = Map.of("db.password", "from-vault");
env.getPropertySources().addFirst(new MapPropertySource("vault-secrets", secrets)); // wins over everything
}
}
// META-INF/spring.factories
// org.springframework.boot.env.EnvironmentPostProcessor=com.acme.VaultSecretsPostProcessor
Make the invisible visible
# illustrative output
vault-secrets <- added first by the post-processor
commandLineArgs
systemProperties
systemEnvironment
Config resource 'class path resource [application.yml]' <- loaded by ConfigDataEnvironmentPostProcessor
The trace
SpringApplication.run()
├─► ApplicationEnvironmentPreparedEvent listeners see the Environment, no context yet
│ └─► EnvironmentPostProcessors ✓ last chance to add or reorder property sources
│ ├─► ConfigDataEnvironmentPostProcessor loads application.yml
│ └─► VaultSecretsPostProcessor adds "vault-secrets"
├─► create the ApplicationContext
├─► ApplicationContextInitializers ✓ before refresh
├─► refresh(): BeanFactoryPostProcessors, then beans ✗ too late to change what a bean's @Value sees
└─► runners, ApplicationReadyEvent
Why Placeholders and @Value are resolved against the Environment while beans are created. Anything that must influence configuration has to be in the Environment before that begins.
Comparison
| Hook | Runs | Can still change |
|---|---|---|
Code before run() | Before anything starts | Web application type, banner, default properties, listeners |
EnvironmentPostProcessor | Environment built, no context yet | Property sources and their order |
ApplicationContextInitializer | Before refresh | The context itself |
BeanFactoryPostProcessor | Definitions loaded, no beans yet | Bean definitions |
@PostConstruct | While that bean is created | Only that bean |
Land it If you need to influence configuration before any bean sees it, the answer is an EnvironmentPostProcessor, and everything later is too late.
- "Write me the shape of an
EnvironmentPostProcessorthat loads a secret file, and say where it must go in the source order." The class implements
EnvironmentPostProcessorand, if it needs ordering,Ordered. InpostProcessEnvironment(env, app)it reads the file, builds aMapPropertySource("vault-secrets", map), and callsenv.getPropertySources().addFirst(source)if the secrets must override everything, oraddAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, source)to sit just below environment variables.It is registered with a line in
META-INF/spring.factories:org.springframework.boot.env.EnvironmentPostProcessor=com.acme.VaultSecretsPostProcessor. Ordering relative to Boot'sConfigDataEnvironmentPostProcessor, which has orderOrdered.HIGHEST_PRECEDENCE + 10, decides whether my source is present whenapplication.ymlplaceholders are resolved; to run after it, use a higher order value.Logging is not initialised yet at this point, so Boot gives you a
DeferredLogFactoryin the constructor for messages that print later.- "When would you choose
spring.config.importover anEnvironmentPostProcessor?" Whenever the source can be expressed as a location.
spring.config.import=vault://secret/apporconfigtree:/etc/secrets/is declarative, visible in the configuration file, profile-aware, and participates in Boot's config data ordering withoptional:handling.A custom loader for it is a
ConfigDataLocationResolverandConfigDataLoaderpair, which is the modern extension point the Vault and Config Server integrations use.An
EnvironmentPostProcessoris the right tool for things that are not locations: deriving one property from another, forcing a value nobody can override, or translating a platform's environment variable format, such as turningDATABASE_URLintospring.datasource.url, username, and password.- "What does
WebApplicationType.NONEactually turn off, and does Actuator still work?" It selects a plain
AnnotationConfigApplicationContextrather than a servlet or reactive web context, so no embedded server starts, noDispatcherServletis registered, and the web auto-configurations back off because their@ConditionalOnWebApplicationconditions fail. Beans likeRestClient.Builderstill exist, since they are not web-server dependent.Actuator's HTTP endpoints do not work because there is no server, but the JMX exposure does, and health indicators can be invoked programmatically.
Boot infers the type from the classpath by default, so a batch job that accidentally has
spring-boot-starter-webon the classpath starts Tomcat and stays alive after the job; setting the type to NONE orspring.main.web-application-type=noneis how you make a job exit when its runner finishes.a batch job with and without the settingruns offline# illustrative output spring-boot-starter-web on classpath, type inferred SERVLET: job finishes, Tomcat is still running, process stays alive ✗ spring.main.web-application-type=none: runner returns, context closes, JVM exits ✓- "Is there a case for parent-child contexts today?"
Rarely. The pattern was used for sharing infrastructure beans across several child contexts, for example one child per plugin, or for Spring Cloud's bootstrap context, which loaded remote configuration in a parent before the main context.
Since Boot 2.4 the config data mechanism replaced the bootstrap context, and plugin isolation is better done with a separate
ApplicationContextper plugin created programmatically. The remaining cases I have seen are test harnesses and a few legacy modular deployments.If someone proposes it in a greenfield service, I would ask what they want isolated, and usually the answer is a package boundary that Modulith enforces without a second context.
Q38. "When would you NOT use Spring Boot for a Java service?"
Reveal answer
The real test Whether you can name the costs of the framework you like, with specifics, and still pick it most of the time.
Strong answer Boot's costs are startup time, memory at rest, a large dependency surface, and reflection-heavy behaviour that is hard to reason about in a closed-world build.
I would not use it, or would use it differently, in four cases:
- Serverless functions and CLI tools with a cold-start budget under 200 milliseconds and a memory budget under 128 megabytes. A Boot JVM jar starts in seconds. Boot's native image gets to about 50 milliseconds, but a framework designed for it, such as Quarkus or Micronaut, or plain Java with no container at all, gets there with less build complexity.
- Extremely small services with two endpoints and no database, where a hundred-line Javalin or Helidon SE program has nothing to configure and nothing to audit.
- High-frequency, latency-critical paths where every allocation counts, where the abstraction layers of MVC and JPA are the wrong trade, and a hand-tuned Netty server is justified.
- A team that already runs a different framework well. Consistency beats marginal fit.
Where Boot wins, which is most business services:
- the ecosystem of starters;
- the operational tooling in Actuator and Micrometer;
- the hiring pool;
- defaults that encode a decade of production lessons.
On Java 21 with virtual threads and the JDK AOT cache, most of the traditional performance arguments against it have shrunk to the cold-start case.
Picture it One cold-start requirement measured against each way of building it, then a table of when the answer changes.
The setup
requirement: a function that must answer within 200 ms from zero, in 128 MB
candidates: Boot on the JVM | Boot with CDS | Boot with the JDK 25 AOT cache | Boot native image | Quarkus native or plain Java
Comparison
| Option | Startup | Meets 200 ms from zero? |
|---|---|---|
| Boot web service with JPA on the JVM | 2 to 4 s warm machine, 5 to 10 s on a throttled small container | No |
| Boot with CDS and the optimised layout | About 1 to 2 s | No |
| Boot with the JDK 25 AOT cache | Another 30 to 50 percent off, under a second is realistic | No |
| Boot native image | 50 to 100 ms | Yes, with the closed-world constraints from Q27 |
| Quarkus native, or plain Java | Similar to Boot native, with less build complexity | Yes |
Decision table
| Situation | Deciding factor | Choice |
|---|---|---|
| Business service, changing team | Ecosystem, operations, documented behaviour | Boot |
| Function with a cold start under 200 ms and under 128 MB | Footprint is the requirement | Native-first framework or plain Java |
| Two endpoints, no database | Nothing to configure or audit | Javalin or Helidon SE |
| Hot path where every allocation counts | Abstraction layers cost too much | Hand-tuned Netty |
| Team already running another framework well | Consistency | Keep it |
Land it Choose against Boot when cold start or footprint is the product requirement, and choose it otherwise for the ecosystem and the operational defaults.
- "Give me numbers for the cold-start case, and say what the JDK AOT cache changed."
As of Aug 2026, a Boot web service with JPA on the JVM starts in 2 to 4 seconds on a warm machine and 5 to 10 on a throttled small container.
With CDS and Boot's optimised layout that drops to about 1 to 2 seconds; with the JDK 25 AOT cache, which stores loaded and linked classes plus method profiles from a training run, reports show another 30 to 50 percent, so a service under a second is realistic on the JVM. A Boot native image starts in 50 to 100 milliseconds.
Quarkus native is similar, and its JVM mode starts in well under a second.
So the JVM gap narrowed substantially, but for a function that must answer in 200 milliseconds from zero, native is still the only option, and there the build complexity and the closed-world constraints from Q27 apply to every framework equally.
- "What would you say to a team that wants to write a service with no framework at all?"
I would ask them to list what they will write instead. A JSON codec, request routing, validation, error mapping, a connection pool, transaction boundaries, configuration loading with overrides, health and metrics endpoints, structured logging with trace ids, and graceful shutdown.
Each of those exists in the JDK or a small library, and a good engineer can assemble them in a week.
The cost is not that week; it is that the assembly is unique, so the next engineer learns it from scratch, and every operational lesson Boot's defaults encode, such as the Hikari settings or the readiness probe semantics, has to be relearned in production.
For a tiny stable component with an owner who stays, fine. For a business service with a team that changes, the framework's value is that its behaviour is documented outside the team's heads.
- "How is Micronaut or Quarkus different at the mechanism level, not the marketing level?"
Both do dependency injection at compile time: an annotation processor generates the bean definitions and the injection code while compiling, so at runtime there is no classpath scanning, no reflection for injection, and no proxy generation.
That is why their startup is fast on the JVM and why native images are natural for them.
Spring does the same work at runtime by default and, with Spring AOT, at build time only for native, so its JVM startup still includes scanning and condition evaluation.
where the work happensruns offlineMicronaut, Quarkus: compile: annotation processor writes bean definitions -> run: construct directly Spring on the JVM: run: scan classpath -> evaluate conditions -> reflect and proxy Spring AOT (native): build: the same steps -> run: generated code onlyThe trade-off is flexibility: Spring's runtime model lets conditions depend on the runtime environment and lets libraries contribute configuration without a compile step, which is why its ecosystem is larger.
Quarkus also has a build-time extension model that pre-initialises libraries, which is where much of its speed comes from.
- "What in Boot itself would you turn off for a latency-critical path while keeping the framework?"
Several things, in order of effect. Open-in-view off, so no entity manager spans the request (
spring.jpa.open-in-view=false). JPA replaced byJdbcClientor plain JDBC on that path, since Hibernate's flush and dirty checking are the expensive part.The Actuator's per-request metrics kept but with
management.metrics.web.server.request.autotimetags limited, and percentiles histograms only where needed. Filters trimmed: no request logging, no content caching. Jackson tuned with a pre-builtObjectWriterper type on the hot path.Virtual threads off for that path if it is CPU-bound, because they add nothing there. And the garbage collector chosen for pause time, ZGC or Shenandoah, with the heap sized for allocation rate.
With those, a Boot endpoint runs in the same hundreds of microseconds a hand-written one would.
Q39 · Design. "Our services need a company-standard JSON configuration: snake_case, ISO dates in UTC, unknown fields rejected. Design how a shared library applies this without breaking a service that needs one exception."
Reveal answer
Strong answer Assumptions: Boot 3.5 and 4.x both in the fleet for a while, services use Boot's auto-configured mapper, and one or two services talk to a partner API that needs camelCase.
Design:
- No mapper bean. The library never defines an
ObjectMapperbean, because that would replace Boot's and lose every Boot default and every other customiser. - A customiser instead. On Boot 3, a
Jackson2ObjectMapperBuilderCustomizerbean. On Boot 4, aJsonMapperBuilderCustomizerfor Jackson 3'sJsonMapper.Builder. - What it sets. The naming strategy, the Java time module with
WRITE_DATES_AS_TIMESTAMPSoff and UTC as the time zone, andFAIL_ON_UNKNOWN_PROPERTIESenabled. - Registration. As an auto-configuration with
@ConditionalOnMissingBean(name = "companyJsonCustomizer")and an@Orderthat runs after Boot's property-driven customiser, so thespring.jackson.*properties still apply first and the company policy wins. - The exception path. Because the shared mapper is company-standard, the service that needs camelCase for one partner builds a separate mapper for that client, via
builder.copy()or a secondJsonMapper, and uses it in thatRestClient's message converter only. - Kill switch.
company.json.enabled=falseexists for emergencies.
Trade-offs: strict unknown-field rejection makes the API stricter for clients, which is intended but must be announced.
What I would not do:
- Let services override the whole customiser.
- Set the policy through properties that every service must copy.
Picture it The two ways to apply a JSON policy, the order in which customisers run, and what a client sees.
The setup
// ❌ TRAP: replaces Boot's mapper, loses spring.jackson.*, other customisers, and Boot's module setup
@Bean ObjectMapper objectMapper() { return new ObjectMapper(); }
// ✅ FIX: contribute to Boot's mapper instead
@Bean @Order(100)
Jackson2ObjectMapperBuilderCustomizer companyJsonCustomizer() {
return b -> b.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
.modules(new JavaTimeModule())
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.timeZone(TimeZone.getTimeZone("UTC"));
}
The trace
Jackson2ObjectMapperBuilder
├─► StandardJackson2ObjectMapperBuilderCustomizer order 0 applies spring.jackson.* (for example LOWER_CAMEL_CASE)
└─► companyJsonCustomizer order 100 SNAKE_CASE ✓ runs later, wins on conflict
What you see
# illustrative output
GET /orders/7 {"order_id":7,"created_at":"2026-01-01T00:00:00Z"} ✓ snake_case, ISO date, UTC
POST /orders {"orderId":7,"x":1} HTTP/1.1 400 unknown property rejected (UnrecognizedPropertyException inside a HttpMessageNotReadableException)
# with the ObjectMapper bean from the trap
Instant field InvalidDefinitionException: Java 8 date/time type java.time.Instant not supported by default
Why Boot builds its mapper from a builder plus an ordered list of customisers. Contributing to that list keeps everything Boot does, and an ordering value decides who wins a conflict.
The fix For the one exception, give it its own mapper rather than weakening the standard.
@Bean RestClient partnerClient(ObjectMapper shared) {
ObjectMapper camel = shared.copy().setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE);
return RestClient.builder()
.messageConverters(c -> c.add(0, new MappingJackson2HttpMessageConverter(camel))) // this client only
.build();
}
Comparison
| Approach | Boot's mapper | spring.jackson.* and other customisers |
|---|---|---|
Define an ObjectMapper bean | Backs off | Lost |
Contribute a customiser at @Order(100) | Kept | Applied first, company policy wins |
| Ask every service to copy properties | Kept | Policy drifts per service |
Land it Customise Boot's mapper, never replace it, and give the exception its own mapper instead of weakening the standard.
- "Requirement change: the partner exception needs to apply to inbound requests on one controller, not an outbound client. What changes?"
The message converter is shared by all controllers, so a per-controller mapper needs a different hook.
The cleanest is a second
HttpMessageConverterregistered for a distinct media type, for exampleapplication/vnd.partner+json, built on the camelCase mapper, and the partner controller declaresconsumesandproduceswith that type.Content negotiation then routes that controller's bodies through the partner converter and everything else through the standard one.
If the partner cannot send a custom media type, the alternative is a
RequestBodyAdviceandResponseBodyAdvicepair scoped to that controller with@ControllerAdvice(assignableTypes = PartnerController.class), which swaps the converter for that handler.I would avoid annotating every DTO field with
@JsonPropertybecause it is invisible policy scattered across classes.- "What would you cut with one day, and what happens to Boot 3 services?"
With one day I would ship the customiser for the Boot line most services run and document the exception path rather than build it; the second Boot line waits for its own day.
For a fleet that is half Boot 3 and half Boot 4, I would publish the library as two artifacts from one repository,
company-json-boot3with the Jackson 2 customiser andcompany-json-boot4with the Jackson 3 one, each with its own imports file, and let the platform starter pick by Boot version.Trying to support both from one jar means both Jackson generations on the classpath, and Boot 4 detects Jackson 2 on the classpath and can auto-configure it too, which produces exactly the confusion the library was meant to end.
- "Why must the customiser run after Boot's property-driven one, and how do you make sure?"
Boot's
StandardJackson2ObjectMapperBuilderCustomizer, or its Jackson 3 equivalent, appliesspring.jackson.*properties and is ordered at 0. Customisers run in@Order, lowest first, so a customiser with a higher value runs later and its settings win on conflicts.For a company policy that should win over a service's stray property, I give my customiser
@Order(100)and document that a service must not set conflictingspring.jacksonproperties. If instead I wanted services to be able to override with properties, I would order mine below 0.I verify with a test that boots a context with a conflicting
spring.jackson.property-naming-strategy=LOWER_CAMEL_CASEand asserts the resulting mapper still writes snake_case, so the ordering is tested rather than assumed.the ordering testruns offline@SpringBootTest(properties = "spring.jackson.property-naming-strategy=LOWER_CAMEL_CASE") class JsonPolicyTest { @Autowired ObjectMapper mapper; @Test void companyPolicyWins() throws Exception { assertThat(mapper.writeValueAsString(new Order(7))).contains("order_id"); // still snake_case } }- "Does rejecting unknown fields break anything you did not expect?"
Yes, two things.
First, forward compatibility between services: if service A adds a field to an event or a response and service B, on the strict mapper, receives it, B now fails to parse, so a deploy of A breaks B. For messages between our own services the policy should be lenient, with unknown fields ignored, and strict only at the public boundary where a client's typo is a bug worth reporting.
Second, Actuator and third-party payloads: some libraries deserialise their own JSON through the shared mapper, and tightening it makes them fail on new fields from their servers.
So the customiser sets
FAIL_ON_UNKNOWN_PROPERTIESonly on the converter used for public request bodies, via a dedicated mapper copy, and leaves the shared mapper lenient.a strict consumer after a producer adds a fieldruns offline# illustrative output service A deploys, event now has {"id":7,"channel":"web"} service B (strict mapper): UnrecognizedPropertyException: Unrecognized field "channel" ✗ B fails to parse, A's deploy broke B
Q40 · Scenario. "A method annotated @Async is supposed to send an email after order placement, but the HTTP response now takes 4 seconds, exactly the email round-trip. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the annotated method is running synchronously on the request thread. Either the async proxy is not being used, or async support is not enabled at all.
- Evidence: log
Thread.currentThread().getName()inside the method; if it printshttp-nio-8080-exec-3rather thantask-1, no executor was involved. Check the application class for@EnableAsync. - Likely causes, ranked:
- Not enabled.
@EnableAsyncis missing, in which case the annotation is inert, since Boot does not enable it by default. - Self-invocation. The call is from another method in the same class, so the proxy is bypassed.
- Not interceptable. The method is private or final, which CGLIB cannot intercept.
- Same bean, transactional caller. The method is in the same bean and called from a
@Transactionalmethod, which is the same self-invocation issue.
- Not enabled.
- Fix:
- Add
@EnableAsync, move the email sender into its own bean and call it through the proxy, make the method public. - Then look at what you have just created: an executor with Boot's default
SimpleAsyncTaskExecutoror a boundedThreadPoolTaskExecutorfromspring.task.execution.*. - Set a queue size and a rejection policy so a burst cannot grow unbounded.
- Handle failures with an
AsyncUncaughtExceptionHandler, because exceptions from avoidasync method vanish otherwise. - With Java 21,
spring.threads.virtual.enabled=truemakes async methods run on virtual threads.
- Add
- Prevention: a test that asserts the send happens on a different thread, and a review checklist item for proxy-based annotations.
// BROKEN — self-invocation again. The call never leaves the object,
// so the async proxy is not involved and the email is sent on the request thread.
@Service
public class OrderService {
public Order place(OrderRequest r) {
Order order = repo.save(toOrder(r));
sendConfirmation(order); // ❌ TRAP: this.sendConfirmation(...) — runs INLINE
return order; // Result: response waits 4 seconds for the mail server
}
@Async
public void sendConfirmation(Order o) { mailer.send(o); }
}
// FIX — cross a bean boundary, and prefer the after-commit event so the email
// is never sent for an order that then rolls back.
@Service
public class OrderService {
private final ApplicationEventPublisher events;
@Transactional
public Order place(OrderRequest r) {
Order order = repo.save(toOrder(r));
events.publishEvent(new OrderPlaced(order.id())); // ✅ FIX: crosses a bean boundary, listener runs after commit
return order;
}
}
@Component
public class OrderNotifier {
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(OrderPlaced e) { mailer.send(e.orderId()); }
}
Two bugs are fixed at once here. Crossing the bean boundary makes @Async take effect; publishing an event and listening after commit makes sure a rolled-back order never produces a confirmation email — which is the failure mode described in Q100.
Picture it The thread name tells whether the proxy was used, shown for the broken call and for the fixed one.
The setup The code below shows the broken self-invocation and the fix.
Make the invisible visible
// what Spring builds around OrderNotifier when @EnableAsync is on
class OrderNotifier$$SpringCGLIB extends OrderNotifier {
@Override public void on(OrderPlaced e) {
executor.submit(() -> super.on(e)); // hop to the task executor and return at once
}
}
// a call through this object is asynchronous; this.sendConfirmation(...) inside OrderService never reaches it
The trace
thread http-nio-8080-exec-3
Controller ──► orderService.place()
└─► this.sendConfirmation(order) ✗ direct call on the real object, async proxy never entered
└─► mailer.send() ✗ 4 s on the request thread
thread http-nio-8080-exec-3 thread task-1
Controller ──► orderService.place()
├─► publishEvent(OrderPlaced)
└─► commit ──► OrderNotifier proxy.on() ───► on() ──► mailer.send() ✓ request thread is free
What you see
# illustrative output, using the code below
before: [http-nio-8080-exec-3] OrderService sending confirmation
[http-nio-8080-exec-3] POST /orders -> 200 in 4012 ms
after: [http-nio-8080-exec-3] POST /orders -> 200 in 38 ms
[task-1] OrderNotifier sending confirmation
Why @Async works only when the call goes through the proxy. A call from inside the same object skips the proxy, so the method simply runs on the caller's thread.
The fix Cross a bean boundary, as in the second class of the code below.
Decision table
| Symptom | Root cause | Action |
|---|---|---|
Thread name is http-nio-...-exec-N inside the method | @EnableAsync missing | Add it to a configuration class |
| Annotation is on, still the request thread | Self-invocation, private or final method | Call through another bean, make the method public |
| Fast response, sometimes no email, no error | Exception swallowed, or the executor discards tasks | AsyncUncaughtExceptionHandler, check the rejection policy |
| Memory grows under overload | Default executor has an unbounded queue | Set queue-capacity and a rejection policy |
Land it @Async has the same two failure modes as @Transactional, not enabled and not through the proxy, plus a third of its own: an unbounded default executor.
- "You added
@EnableAsyncand moved the method to its own bean. Now the email sometimes never sends and there is no error. What next?" Two candidates. The exception is being swallowed: a void
@Asyncmethod's exceptions go to theAsyncUncaughtExceptionHandler, whose default just logs at ERROR, and if the logging configuration filters that logger the failure is invisible.I would register an
AsyncConfigurerwith a handler that logs and increments a metric, or returnCompletableFutureso the caller can attachexceptionally.a handler that is not silentruns offline@Configuration @EnableAsync class AsyncConfig implements AsyncConfigurer { public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (ex, method, params) -> { log.error("async {} failed", method.getName(), ex); failed.increment(); }; } }The other candidate is the executor rejecting the task: with a bounded queue and
AbortPolicy, a burst producesTaskRejectedExceptionat submission time, which propagates to the caller, so that one is loud; but withDiscardPolicyit is silent.Check
spring.task.execution.pool.queue-capacityand the rejection handler, and look at theexecutor.queuedandexecutor.rejectedmetrics if the executor is registered with Micrometer.- "What does Boot's default executor look like as of now, and what would you set?"
As of Aug 2026, without virtual threads Boot auto-configures a
ThreadPoolTaskExecutorfromspring.task.execution.*with core size 8, unbounded max size effectively limited by the queue, and an unbounded queue, so under sustained overload the queue grows until memory is exhausted.With
spring.threads.virtual.enabled=trueit becomes aSimpleAsyncTaskExecutorcreating a virtual thread per task with no queue at all. For a platform-thread pool I would setpool.core-size=8,pool.max-size=32,pool.queue-capacity=1000, andthread-name-prefix=email-, and provide aTaskExecutorCustomizerthat setsCallerRunsPolicyso overload slows the caller rather than losing work.the pool settingsruns offlinespring.task.execution.pool.core-size=8 spring.task.execution.pool.max-size=32 spring.task.execution.pool.queue-capacity=1000 spring.task.execution.thread-name-prefix=email-For virtual threads I would add a
Semaphorein the email sender to cap concurrency against the mail server.- "How does
@Asyncinteract with@Transactionalon the calling method?" The async method runs on a different thread, and a transaction is bound to a thread, so the async work is outside the caller's transaction.
If the caller places the order and then calls the async email method before committing, the email may be sent for an order that then rolls back, or the async code may read the database and not see the uncommitted order.
The correct pattern is to publish an event and handle it with
@TransactionalEventListener(phase = AFTER_COMMIT)combined with@Async, so the email is sent only after the order is durable and on its own thread.If the async method itself is
@Transactional, it opens its own transaction on the executor thread, which is fine as long as the caller does not expect to share it.- "How do you test that a method actually runs asynchronously?"
Two levels.
A slice test with the real proxy:
@SpringBootTestwith the service and a stubbed mail client that records the thread name, calling the method through the injected bean and asserting the recorded thread name starts with the executor's prefix and differs from the test thread.For timing, use Awaitility to wait for the stub to be called rather than a sleep.
For a stricter check, replace the executor in the test with a
SyncTaskExecutorso the behaviour is deterministic, and separately assert that the production configuration wires the async executor, for example by checking the bean is anAsyncTaskExecutorwith the expected prefix.The thread-name assertion is the one that catches a lost
@EnableAsyncor a self-invocation regression.
08 · DrillWeb Layer, Security & Validation — Q41–Q80
The web questions test whether you can follow one request through Tomcat, the filter chain, the DispatcherServlet, and back, and whether you know which of those layers owns each failure. They also cover the capacity arithmetic of thread pools and the choice between platform threads, virtual threads, and WebFlux; validation and error contracts; the Spring Security filter chain and JWT resource servers; and the operational corners of HTTP: timeouts, uploads, streaming, and versioning. Scenarios go in diagnosis order.
These questions test whether you can say who holds the thread at every point of a request, and turn that into numbers.
Q41. "From the moment Tomcat hands a request to the DispatcherServlet, name each object involved in getting to your controller method's parameters, in order."
Reveal answer
Strong answer One request travels this chain, in order.
- Multipart check: The DispatcherServlet's
doDispatchfirst checks for a multipart request and wraps it. - Handler lookup: It then iterates its
HandlerMappings. TheRequestMappingHandlerMappingmatches the path and method against the registry it built at startup from every@RequestMapping. It returns aHandlerExecutionChain: theHandlerMethodplus the applicableHandlerInterceptors. - Interceptors and adapter: Each interceptor's
preHandleruns, and any returning false ends the request. The servlet then finds aHandlerAdapterthat supports the handler; for annotated controllers it is theRequestMappingHandlerAdapter. - Argument resolution: That adapter builds an
InvocableHandlerMethodand, for each parameter, consults its list ofHandlerMethodArgumentResolvers:PathVariableMethodArgumentResolver,RequestParamMethodArgumentResolver,RequestResponseBodyMethodProcessorfor@RequestBody, which selects anHttpMessageConverterby content type and reads the body, then runs validation if@Validis present, and the model attribute resolver for form binding through aWebDataBinder. - Return and unwind: The method is invoked. The return value goes through
HandlerMethodReturnValueHandlers; the same body processor writes a@ResponseBodyresult through a converter chosen by theAcceptheader. Interceptors'postHandleandafterCompletionrun, and exceptions anywhere in this chain go to theHandlerExceptionResolvers.
Picture it one POST request followed hop by hop through the objects that build your controller's arguments.
The setup: a controller with three kinds of parameter. The comments name the resolver that fills each one.
@RestController
class OrderController {
@PostMapping("/orders/{id}/lines")
OrderDto addLine(@PathVariable long id, // PathVariableMethodArgumentResolver
@RequestParam(defaultValue = "1") int qty, // RequestParamMethodArgumentResolver
@Valid @RequestBody LineRequest body) { // RequestResponseBodyMethodProcessor
return service.addLine(id, qty, body);
}
}
Make the invisible visible: what the handler mapping holds after startup, and what it returns for this request.
# illustrative output
registry (built at startup)
POST /orders/{id}/lines -> OrderController#addLine(long, int, LineRequest)
GET /orders/{id} -> OrderController#get(long)
getHandler(POST /orders/7/lines) returns a HandlerExecutionChain
handler = HandlerMethod OrderController#addLine
interceptors = [ AuditInterceptor ]
The trace: one hop per line. Nothing of your code runs until the last step before the call.
Tomcat ──► filter chain ──► DispatcherServlet.doDispatch
├─ checkMultipart not multipart, request unchanged ✓
├─ HandlerMapping → HandlerExecutionChain ✓
├─ interceptor.preHandle() returns true (false would end the request here)
├─ HandlerAdapter RequestMappingHandlerAdapter ✓
│ └─ InvocableHandlerMethod
│ ├─ id ← PathVariableMethodArgumentResolver
│ ├─ qty ← RequestParamMethodArgumentResolver
│ └─ body ← RequestResponseBodyMethodProcessor
│ ├─ HttpMessageConverter chosen by Content-Type, reads the body
│ └─ @Valid runs the validator
├─ controller.addLine(7, 1, body) your code runs only now ✓
├─ return value ← converter chosen by Accept header, writes the response
└─ postHandle, afterCompletion exceptions anywhere go to the HandlerExceptionResolvers
What you see: the same request with an invalid body. The controller method never runs.
# illustrative output
POST /orders/7/lines {"sku": ""}
controller.addLine(...) never called
exception MethodArgumentNotValidException, raised inside the @RequestBody resolver
resolved by DefaultHandlerExceptionResolver -> HTTP 400
Why: argument resolution happens before your method is called, so a failure there is an exception from a resolver, mapped by the exception resolvers, and your method body never sees it.
Land it Every custom parameter type or response type you ever wanted is a resolver or a handler you can register, and knowing the chain tells you where.
- "How would you add support for a custom parameter type, say a
@CurrentTenant Tenantargument?" I implement
HandlerMethodArgumentResolverwith two methods:supportsParameterreturns true when the parameter carries@CurrentTenant, andresolveArgumentreads the tenant from the security context or a request attribute and returns it, throwing a domain exception if absent so the advice can map it to 401 or 403.Then I register it through a
WebMvcConfigurerbean'saddArgumentResolvers. Custom resolvers run after the built-in ones for the same parameter, so a type that a built-in resolver already claims, such as a plainString, cannot be overridden this way; the annotation is what makessupportsParameterunambiguous. For return values the mirror isHandlerMethodReturnValueHandlerandaddReturnValueHandlers.- "Where does the path match actually happen, and what changed with
PathPatternParser?" RequestMappingHandlerMappingkeeps a registry built at startup by scanning every controller for@RequestMappingand storing aRequestMappingInfoper method. On each request it looks up direct-path matches in a map first, then falls back to pattern matches, then sorts candidates by specificity.Since Spring Framework 6 the default matcher is
PathPatternParser, which parses patterns once into a tree and matches without regex per request, so it is faster than the oldAntPathMatcher.It is also stricter: a trailing slash no longer matches by default and
**is allowed only at the end. Boot'sspring.mvc.pathmatch.matching-strategyproperty existed to switch back during migration and was removed in later versions, so trailing-slash behaviour now needs explicit mappings or a redirect.- "What runs between Tomcat and the DispatcherServlet that you did not name?"
The servlet filter chain, in Boot's registration order:
CharacterEncodingFilter.FormContentFilterfor PUT form bodies.RequestContextFilter, which binds the request toRequestContextHolder.- Boot's
WebMvcMetricsFilteror the Observation filter that times the request forhttp.server.requests. - Spring Security's
FilterChainProxyat order -100 if present, plus any application filters.
Before the filters, Tomcat's own valves run: the access log valve and, if configured, the
RemoteIpValve, which rewrites the scheme and client address fromX-Forwarded-*headers. Boot enables it withserver.forward-headers-strategy=native.That valve is why a service behind a load balancer sees
httpsand the real client IP, and forgetting it is why redirects go tohttp.- "How does the multipart wrapping work, and what does it cost?"
DispatcherServlet.checkMultipartasks theMultipartResolver, in Boot theStandardServletMultipartResolver, whether the request ismultipart/form-data.If so, the request is wrapped so that
@RequestPartandMultipartFileparameters can be resolved through the servlet container'sPartAPI. The container parses the body lazily on first access, spooling parts larger thanspring.servlet.multipart.file-size-thresholdto the temp directory set bylocation, and enforcingmax-file-sizeandmax-request-size, which throwMaxUploadSizeExceededException.The cost is the disk write and a temp file per part, cleaned up when the request completes. Setting
spring.servlet.multipart.resolve-lazily=truedefers parsing until a handler actually asks, which lets an advice reject a request without reading a 2 gigabyte body.
Q42. "Filter, HandlerInterceptor, and @ControllerAdvice: give me a rule for which to use, and explain how ordering works among filters."
Reveal answer
Strong answer The rule is by what the code needs to know and when it must run.
- Filter: A servlet
Filterruns outside Spring MVC on raw request and response objects, before and after the whole dispatch; use it for cross-cutting concerns that must apply to every servlet including static resources and error dispatches, or that must run before Security, such as correlation-id propagation, request body caching, compression, and rate limiting at the edge. - Interceptor: A
HandlerInterceptorruns inside the DispatcherServlet and knows the targetHandlerMethod, so use it for anything that depends on which controller is being called or on the authenticated user: per-endpoint timing tags, checking a custom annotation on the method, or setting up a tenant context. - Advice:
@ControllerAdviceis for translating exceptions to responses and for binding customisation, and nothing else.
Ordering among filters:
- Register each as a
FilterRegistrationBeanwith an explicitsetOrder, or put@Orderon the filter bean. Lower values run first. - Spring Security's chain sits at
SecurityProperties.DEFAULT_FILTER_ORDER, which is -100. - A filter that must see the authenticated principal needs an order greater than -100. A filter that must run before authentication needs a smaller one.
Plain @Component filters with no order run after all ordered ones in an unspecified order, which is a bug waiting to happen.
// FILTER — servlet level. Sees EVERY request including static resources and
// requests that never reach a controller (404s, security rejections).
// Can wrap the request/response. Knows nothing about which handler will run.
// ❌ TRAP: a @Component filter with no order runs after all ordered ones, in an unspecified order
@Component
public class CorrelationIdFilter extends OncePerRequestFilter {
@Override protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain chain) throws Exception {
MDC.put("correlationId", correlationId(req));
try { chain.doFilter(req, res); } finally { MDC.clear(); }
}
// ✅ FIX: an explicit order, relative to Security's -100
@Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; }
}
// HANDLER INTERCEPTOR — Spring MVC level. Runs only for mapped handlers, and
// KNOWS WHICH ONE: it receives the HandlerMethod, so it can read annotations.
@Component
public class RateLimitInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest req,
HttpServletResponse res, Object handler) {
if (handler instanceof HandlerMethod hm
&& hm.hasMethodAnnotation(RateLimited.class)) { ... }
return true; // false = stop, do not call the controller
// Result: with false, the response is whatever preHandle wrote; the controller never runs
}
}
// @ControllerAdvice — controller level. Turns exceptions into responses,
// and can bind or validate. Never sees requests that failed before routing.
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderNotFound.class)
ProblemDetail onNotFound(OrderNotFound e) { ... }
}
// ORDERING: filters run in @Order/getOrder() sequence, outermost first, and
// unwind in reverse. Interceptors run in registration order. Security's filter
// chain is itself a filter, so anything that must see an UNAUTHENTICATED
// request has to be ordered before it.
The rule that decides it: use a filter when you need every request or need to wrap the stream, an interceptor when you need to know which handler is about to run, and advice when you are turning an exception into a response body.
Picture it one shared set of three layers, shown against three different requests, so you can see which layer even runs.
The setup: the three classes in the code above, with the correlation filter ordered before Security and a second filter ordered after it.
Make the invisible visible: the order in which the layers wrap one request, outermost first.
# illustrative output
CorrelationIdFilter order HIGHEST_PRECEDENCE + 10 before Security
Spring Security FilterChainProxy order -100
UserAuditFilter order -90 after Security, sees the principal
DispatcherServlet
RateLimitInterceptor.preHandle (knows the HandlerMethod)
OrderController
@RestControllerAdvice (only if the controller threw)
What you see: which layer is reached by each request. The rows are concrete requests; the cells are outcomes.
| Request | Filter before Security | Filter after Security | Interceptor | Advice |
|---|---|---|---|---|
| Anonymous request rejected by Security with 401 | Runs, so its id is in the log | Never runs | Never runs | Never sees it |
GET /orders/9 succeeds | Runs | Runs, principal available | preHandle runs and receives the HandlerMethod | Not involved |
Controller throws OrderNotFound | Runs; sees the finished 404 response | Runs; sees the 404 response | preHandle runs | Handles it and builds the body |
Why: each layer is entered from a different place: filters from the servlet container, interceptors from the DispatcherServlet after a handler is found, and advice from the exception resolvers once something has thrown.
Land it Filters know the servlet, interceptors know the handler, advice knows the exception, and every filter should carry an explicit order relative to Security's -100.
- "A filter needs the authenticated user and also the correlation id set by another filter. How do you order it, precisely?"
Two constraints: after Security, so its order must be greater than -100, and after the correlation-id filter, so its order must be greater than that filter's.
I would give the correlation filter
Ordered.HIGHEST_PRECEDENCE + 10, so it runs before almost everything including Security and its id is available in Security's own logs, and the user-dependent filterSecurityProperties.DEFAULT_FILTER_ORDER + 10, which is -90.Both registered as
FilterRegistrationBeans with explicitsetOrderand URL patterns, and a comment stating the constraint.The verification is a test that sends a request and asserts the MDC contains both fields in the log line written by the second filter; ordering bugs here show up as a null principal on one request in a thousand when someone reorders a bean.
- "What are the mechanical differences between a filter and an interceptor with respect to exceptions and async?"
A filter sees the raw servlet call, so an exception from the handler passes through it as a
ServletExceptionor the wrapped runtime exception only if noHandlerExceptionResolverhandled it; usually the resolver has already turned it into a response, so the filter sees a 500 response, not an exception.An interceptor's
afterCompletionreceives the exception object directly when the handler threw and nothing resolved it, and runs even whenpreHandleof a later interceptor returned false.For asynchronous handlers such as
DeferredResult, the filter'sdoFilterreturns when the request goes async and is invoked again on dispatch only if registered withDispatcherType.ASYNC; an interceptor getsafterConcurrentHandlingStartedinstead ofpostHandleon the first pass, and the full callbacks on the second. Filters that assume one pass per request break under async.- "How do you make a filter apply only to some paths without doing the check inside
doFilter?" FilterRegistrationBean.addUrlPatterns("/api/*")restricts a filter by servlet URL pattern, which is matched by the container before the filter is invoked, so requests to other paths never touch it.For more precise matching than servlet patterns allow, Spring's
OncePerRequestFilterhasshouldNotFilter(request), which I override with aPathPatternRequestMatchercheck; it still costs the invocation but keeps the logic out ofdoFilter.The
FilterRegistrationBeanalso setssetDispatcherTypes(REQUEST)so the filter does not run again on the internal error or async dispatch, which is the source of double-logged requests. Plain@Componentfilters get no URL pattern and all dispatcher types, which is another reason to always register explicitly.- "Why is
OncePerRequestFilterthe right base class, and when is it not?" The servlet container can invoke a filter more than once for one request: on the original dispatch, again on an error page forward, and again on an async dispatch.
OncePerRequestFiltersets a request attribute the first time and skips subsequent invocations, so a filter that opens a span, counts a metric, or wraps the request does so exactly once. It also exposesshouldNotFilterAsyncDispatchandshouldNotFilterErrorDispatch, which default to true.It is the wrong choice when the filter must act on every dispatch, for example a filter that must clean up thread-locals after the async completion, because there the second invocation is the one that matters; in that case I extend
GenericFilterBeanand handle the dispatcher type explicitly.
Q43 · Scenario. "p99 latency spikes to 2 seconds every 5 minutes, like clockwork, then drops back to 40 ms. CPU and database look normal. Walk through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a periodic latency spike with a fixed period. Periodicity means a timer, and the candidates are our own scheduled work, the JVM, the pool, or a neighbour.
- Evidence: overlay the spike timestamps with
jvm.gc.pausefrom Micrometer, withhikaricp.connections.timeoutandcreation, with every@Scheduledmethod's timer, with the log of any cache refresh, and with the Kubernetes node's other pods. Take a thread dump during one spike. - Likely causes, ranked: a
@Scheduled(fixedRate = 300000)job doing heavy work on the request path's resources, for example a cache rebuild that holds a lock or saturates the connection pool, so requests queue behind it; Hikari'smax-lifetimeorkeepalive-timeretiring a batch of connections at once because they were all created together at startup, so a burst of requests pays for reconnection and TLS handshakes; a full garbage collection or a G1 humongous-allocation cleanup on a heap that fills on a 5-minute cycle from a batch of allocations, visible as a pause in the GC metric; a token refresh against an identity provider every 5 minutes under a lock, so every request waits for it; a neighbouring cron job on the same node stealing CPU. - Fix per cause: move the scheduled job off the request-path resources or to a separate deployment; add jitter to connection lifetimes (Hikari does this by default with a small variance, but a large pool created at once still clusters); tune the heap or the allocation; refresh tokens asynchronously ahead of expiry so no request ever waits.
- Prevention: tag the scheduler's metrics and put every periodic task on the latency dashboard, so periodicity is visible instead of inferred.
Picture it the same service at three moments around a spike, with the metrics that expose the timer behind it.
The setup: a heavy job on a five-minute timer that shares the connection pool with the request path.
@Scheduled(fixedRate = 300000) // every 5 minutes, like clockwork
void rebuildCache() {
// ❌ TRAP: loads everything through the same Hikari pool the requests use
cache.putAll(repo.loadEverything()); // holds all 10 connections for about 8 seconds
}
What you see: the overlay of request latency against the timers. Only the pool and the scheduled job move with the spike.
# illustrative output
time p99 hikari active pending jvm.gc.pause max tasks.scheduled.execution
12:04:50 40 ms 6/10 0 8 ms idle
12:05:00 2000 ms 10/10 23 9 ms rebuildCache running
12:05:08 40 ms 6/10 0 8 ms rebuildCache done
The trace: a thread dump taken during the spike shows who is waiting on whom.
# illustrative output
"http-nio-8080-exec-17" WAITING
at com.zaxxer.hikari.pool.HikariPool.getConnection(...) ✗ waiting for a free connection
"scheduling-1" RUNNABLE
at com.example.CacheLoader.rebuildCache(...) holds the connections
Why: the spike is not slow code; it is a timer that takes every connection for a few seconds, so every request queues behind it.
| Symptom at the spike | Root cause | Action |
|---|---|---|
hikaricp.connections.pending rises, scheduled timer overlaps | Job shares the request pool | Move the job to its own pool, or to a separate deployment |
jvm.gc.pause max jumps at the same time | Batch allocation fills the heap on a 5-minute cycle | Find the allocation first; tune or switch collector only if it is truly GC |
hikaricp.connections.creation rate spikes | Connections retired together at max-lifetime | Set keepalive-time below the infrastructure timeout |
| Every thread stuck in a token refresh | Refresh under a lock, every 5 minutes | Refresh asynchronously ahead of expiry |
| Nothing of yours lines up | Timer outside the process: node cron, DNS TTL, checkpoint | Widen to node, network and database metrics |
What you see now: after the job gets its own pool, the same three moments read flat.
# illustrative output
time p99 hikari active pending tasks.scheduled.execution
12:04:50 40 ms 6/10 0 idle
12:05:00 41 ms 6/10 0 rebuildCache running (own pool)
12:05:08 40 ms 6/10 0 rebuildCache done
Land it A clockwork spike is a timer somewhere, and the fastest path is to line up every timer you own against the spike before blaming the infrastructure.
- "The overlay shows nothing of yours lines up with the spikes. What next?"
Then the timer is outside the process. I would widen the search in three directions.
The node:
kubectl describe nodeand the node's CPU throttling and I/O wait metrics at the spike times, plus a list of CronJobs and DaemonSets scheduled on it, because a log-shipping agent that rotates every 5 minutes is a classic.The network path: the load balancer's connection draining or health-check cycle, and DNS TTLs, since a 300-second TTL means every pod re-resolves the database or a partner host at the same moment and a slow resolver adds a second to the first request after expiry.
The database:
pg_stat_activityand checkpoint timing, because a checkpoint every 5 minutes with a large dirty set stalls writes. And I would take the thread dump during a spike anyway, because whatever the cause, the dump shows what the request threads were waiting on.- "How does Hikari's connection retirement actually cluster, and how do you prove it?"
Hikari retires a connection when it reaches
max-lifetime, default 30 minutes, applying a random variance of up to 2.5 percent so retirements spread out.But a pool created at startup opens all
minimum-idleconnections within milliseconds of each other, so the variance spreads a batch of 20 retirements over about 45 seconds, and if the database's own idle timeout or a firewall closes connections at a fixed interval, they die together.The proof is the metric
hikaricp.connections.creationtimer's count rate spiking at the same period as the latency, plus Hikari's DEBUG log lines "connection closed (connection has passed maxLifetime)" clustered in time.The fix is a
keepalive-timebelow the infrastructure timeout and amax-lifetimebelow the database'sidle_session_timeout, and accepting that the first batch clusters.Hikari log lines when connections age out togetherruns offline# illustrative output 12:30:01.112 DEBUG HikariPool-1 - Closing connection PgConnection@1a2b: (connection has passed maxLifetime) 12:30:01.140 DEBUG HikariPool-1 - Closing connection PgConnection@3c4d: (connection has passed maxLifetime) 12:30:01.173 DEBUG HikariPool-1 - Closing connection PgConnection@5e6f: (connection has passed maxLifetime) # the same burst repeats at the same offset every cycle; the creation timer spikes right after- "Which JVM signals would tell you it is garbage collection, and what would you tune first?"
jvm.gc.pausewith tags for action and cause is the first: a spike in the max pause at the same timestamps confirms it, and the cause tag distinguishes a G1 evacuation pause from a humongous allocation or a metadata threshold.jvm.memory.usedfor the old generation shows a sawtooth with the same period if something allocates a large batch on a schedule. With JDK 21 or later I would enable JFR continuously with-XX:StartFlightRecordingand look at the allocation samples in the seconds before the pause.The first tuning is not the collector; it is finding the allocation, typically a scheduled job that loads a large result set into a list.
If it is genuinely GC, on a service with a large heap I would move from G1 to ZGC, which keeps pauses under a millisecond at the cost of some throughput.
- "What would you build so this class of problem is diagnosed in minutes next time?"
A single dashboard row that overlays request latency percentiles with every periodic thing in the process:
jvm.gc.pause,hikaricp.connections.creation, every@Scheduledmethod's timer, which Boot registers automatically astasks.scheduled.executionwhenScheduledTaskObservationsupport is on in Boot 3.3 and later, cache refresh timers, and token refresh. Plus an alert on periodicity itself: a p99 spike that recurs at a fixed interval three times fires a low-priority alert naming the interval, which is a small script over the metrics store. The point is to make the overlay the default view rather than something an engineer assembles during an incident.
Q44 · Design. "Design rate limiting for a public REST API on Boot: 1,000 requests per minute per API key, 10 instances behind a load balancer, with clear feedback to clients."
Reveal answer
Strong answer Requirements: a limit that is global across instances, cheap per request, fair under bursts, and honest to the client. Design: the counting state cannot live in one instance, so it lives in Redis.
- The check: A servlet
Filterordered just after authentication reads the API key from the security context, then runs a token-bucket check as a single Lua script withEVALSHAagainst keyrl:{apiKey}: the script refills tokens by elapsed time, takes one if available, and returns the remaining count and the reset time atomically, so ten instances cannot double-spend. - Bucket and headers: Bucket capacity 1,000, refill 1,000 per 60 seconds, which allows a short burst and then smooths. On success the filter adds
RateLimit-Limit,RateLimit-Remaining, andRateLimit-Resetheaders; on rejection it returns 429 with aRetry-Afterheader and aProblemDetailbody, without ever reaching the controller. - Library: Bucket4j with its Redis extension implements exactly this and saves writing the script.
- Resilience: Resilience: if Redis is unreachable, fail open with a local in-memory limiter per instance at one tenth of the quota and a metric that fires an alert, because blocking every client because the limiter is down is worse than being briefly generous.
- Metrics and trade-offs: Metrics: a counter of rejections tagged by key tier feeds both alerting and the sales team's upsell list. Trade-offs: a Redis round trip of about half a millisecond per request; a per-key sharded design if a few keys dominate.
- What I would not do: What I would not do: rate limit in the controller or with an interceptor after the body has been parsed, since the point is to reject cheaply; or use a fixed window counter, whose boundary lets 2,000 requests through in two adjacent seconds.
Picture it one API key's bucket across a burst, how the atomic script settles a race between two instances, and what the client receives.
The setup: a bucket per API key with capacity 1,000 and a refill of 1,000 per 60 seconds, which is about 16.7 tokens per second.
Make the invisible visible: the state in Redis for one key at three moments.
# illustrative output
t=0s rl:{key-abc} tokens=1000 (full)
t=1s after a burst of 1,000 requests: tokens=0.3 all answered 200
t=1s next request: needs 1 token, has 0.3 -> rejected, 429
The trace: two instances race for the last token. Redis runs one script at a time.
instance A ──► EVALSHA rl:{key-abc} tokens=1 -> take it, tokens=0 ✓ 200
instance B ──► EVALSHA rl:{key-abc} tokens=0 -> reject ✗ 429
(Redis executes the scripts one after the other, so both cannot take the last token)
What you see: the rejected client gets guidance, not a mystery.
# illustrative output
HTTP/1.1 429 Too Many Requests
Retry-After: 1
RateLimit-Limit: 1000
RateLimit-Remaining: 0
RateLimit-Reset: 1
Content-Type: application/problem+json
Why a fixed window is not used: its counter resets on the boundary, so a client can spend a full quota on each side of it.
window 12:00:00-12:00:59 counter reaches 1000 at 12:00:59 ✓ limit met
window 12:01:00-12:01:59 counter resets, reaches 1000 at 12:01:00 ✓ limit met
-> 2,000 requests inside two seconds, and both windows say the limit held
Land it Shared state in Redis with an atomic script gives you one global bucket, and the headers turn a rejection into guidance instead of a mystery.
- "Requirement change: limits now differ per endpoint, and some endpoints cost 10 units. How does the design change?"
The bucket key stays per API key, but the cost per request becomes a parameter to the script: instead of taking one token, the filter passes the endpoint's weight, resolved from a small table keyed by route pattern, and the script takes that many or rejects.
Per-endpoint limits, as opposed to per-endpoint cost, mean multiple buckets per key,
rl:{apiKey}:{routeGroup}, checked in one script call with a Lua loop so it stays atomic.The weight lookup needs the matched route, which a filter does not know, so the check either moves to a
HandlerInterceptorthat sees theHandlerMethodand an annotation like@RateCost(10), accepting the small extra work before rejection, or the filter uses its own path-pattern table.I would pick the interceptor for clarity and keep a coarse per-key filter in front for the cheap rejection of floods.
- "What would you cut under time pressure?"
I would cut the fail-open local limiter, the tiered metrics, and the sharding thought, and ship Bucket4j with its Redis extension, the three response headers, and the 429 with
Retry-After. Bucket4j already implements the atomic refill so no Lua is written.I would keep one thing people skip: the decision of what to do when Redis is down, even if the decision is a one-line "fail open and log at ERROR", because a limiter that fails closed takes the API down during a cache incident and nobody remembers why.
The fail-open local limiter can be added the week after when the on-call engineer has seen the log line once.
- "How does the Lua script guarantee correctness across ten instances, and what is its failure mode?"
Redis executes a script atomically on a single thread, so the read-modify-write of the bucket's token count and timestamp cannot interleave with another instance's call. That is the whole guarantee.
It holds as long as all keys the script touches are on one shard, which the
{apiKey}hash tag ensures in Redis Cluster.The failure modes:
- A script that takes long blocks every other client, so it must be tiny.
- Redis latency adds directly to every request, so a slow Redis is a slow API.
- A failover to a replica can lose the last few writes, which for a limiter means a few extra requests are allowed, which is acceptable.
Clock skew is not an issue because the script uses Redis's own
TIME, not the caller's clock.- "Why is a token bucket better than a sliding window here, and when would you choose the window?"
A token bucket lets a client that has been quiet spend a burst up to the bucket size, then smooths to the refill rate, which matches how real clients behave and how an API wants to be used.
It is one key with two fields, cheap to store and compute. A sliding window log stores every request timestamp for the window, so it is exact but costs memory proportional to the rate, and a sliding window counter approximates by weighting the previous window.
I would choose the sliding window when the contract is literally "no more than N in any 60-second period" for a compliance reason, because a bucket can allow up to 2N in a minute when a full bucket is drained and refilled. For a public API with fairness in mind, the bucket wins.
Q45. "Do the arithmetic: how would you size Tomcat's thread pool for a service whose requests average 50 ms with a 30 ms database call, targeting 2,000 requests per second across 4 instances?"
Reveal answer
Strong answer Little's law says concurrency equals throughput times time in system. Per instance the target is 500 requests per second at 50 milliseconds, which is 25 concurrent requests on average.
- Threads: Averages hide bursts and tails, so I would size for about three times the average, around 75 threads, and keep the default 200 as a ceiling so a downstream slowdown to 200 milliseconds (100 concurrent) does not immediately refuse connections.
- Connection pool: The more important number is the connection pool: each request holds a connection for 30 of its 50 milliseconds, so 500 per second times 0.03 seconds is 15 connections on average; a fixed pool of 20 to 25 per instance covers it, and 4 instances times 25 is 100 connections on the database, which needs checking against its limits and core count.
- Both together: The two pools must be reasoned about together: if the thread pool is 200 and the connection pool is 10, 190 threads can be waiting on connections during a slow query, which is the failure mode from the primer.
- Settings: Set
server.tomcat.threads.max=100,server.tomcat.accept-count=50so a short burst queues rather than fails,hikari.maximum-pool-size=25, andhikari.connection-timeout=2000so a thread fails fast rather than sitting. Then load test, because the model assumes the 30 milliseconds holds at 100 concurrent database sessions, which the database decides, not the application.
Picture it the same service at three moments: healthy, during a partner incident, and the ratio that keeps waiting bounded.
The setup: the settings from the answer, per instance.
server.tomcat.threads.max=100
server.tomcat.accept-count=50
spring.datasource.hikari.maximum-pool-size=25
spring.datasource.hikari.connection-timeout=2000
Make the invisible visible: Little's law at 500 requests per second per instance.
| Quantity | Healthy (30 ms database) | Incident (200 ms database) |
|---|---|---|
| Time per request | 50 ms | about 220 ms |
| Concurrent requests (500 per second x time) | 25 | 110, above the 100-thread ceiling |
| Connections needed (500 per second x database time) | 15 | 100, against a pool of 25 |
| Who waits | nobody | 75 requests wait on getConnection |
What you see: the incident on one instance.
# illustrative output
tomcat.threads.busy 100 (max 100)
hikaricp.connections.active 25 (pool 25)
hikaricp.connections.pending 75
exception after 2 s: SQLTransientConnectionException "HikariPool-1 - Connection is not available, request timed out after 2000ms"
Why: threads outnumber connections 4 to 1, so at most 75 can wait, and each waits at most 2 seconds before failing visibly.
What you see with the wrong ratio: the same incident with a thread pool of 200 and a connection pool of 10.
# illustrative output
tomcat.threads.busy 200 (max 200)
hikaricp.connections.active 10
hikaricp.connections.pending 190 # 190 threads parked, each holding a socket and memory
Land it Size threads from Little's law with headroom, size connections from the same law, and make sure the thread count cannot out-wait the connection count by an order of magnitude.
- "The database call grows to 200 ms during a partner incident. Rerun the numbers and say what breaks first."
Per instance still 500 requests per second, but each now takes about 220 milliseconds, so Little's law gives 110 concurrent requests, above the 100-thread ceiling I set, and the connection demand becomes 500 times 0.2, which is 100 connections against a pool of 25.
The connection pool breaks first: 75 requests are waiting on
getConnectionat any moment, each holding a Tomcat thread, and withconnection-timeout=2000they fail after two seconds withSQLTransientConnectionException. That failure is what I want: a fast, visible error instead of a hang.Then the thread pool fills,
accept-countabsorbs 50 more, and beyond that the kernel refuses. The lesson is that the two numbers, 100 threads and 25 connections, give a 4:1 ratio that keeps the waiting bounded; a 200:10 ratio would let 190 threads wait.- "With virtual threads, does this arithmetic change?"
The thread half disappears and the connection half becomes everything. With
spring.threads.virtual.enabled=true, Tomcat creates a virtual thread per request, so there is no 100-thread ceiling and 110 concurrent requests cost a few hundred kilobytes.But the connection pool is still 25, so under the slow-database scenario 85 virtual threads wait for connections instead of 75 platform threads, and with no thread ceiling the number of waiting requests is bounded only by
server.tomcat.max-connections, default 8,192.That is worse if the pool timeout is long, because thousands of requests can pile up.
So with virtual threads I keep
hikari.connection-timeoutshort, add a bulkhead semaphore around the database-heavy paths at about two times the pool size, and watchhikaricp.connections.pendingas the primary saturation signal.- "How would you validate the model with a load test, and what numbers would you record?"
I would run a closed-loop test with Gatling or k6 against one instance with the production pool settings and a database of production size, stepping from 100 to 800 requests per second in 100-step increments, holding each step for five minutes.
At each step I record p50 and p99 latency,
tomcat.threads.busy,hikaricp.connections.activeandpending, database CPU, and the error rate.The model predicts 25 busy threads and 15 active connections at 500 per second; if the measurement is 40 and 22, the request time is longer than the 50 milliseconds assumed and the pool sizes need revisiting.
I also record the step at which p99 leaves the linear region, which is the real capacity, and set the autoscaler's target at 60 percent of it.
- "Why keep
threads.maxat 100 rather than the default 200 if the average need is 25?" Because more threads than the downstream can serve do not add throughput; they add waiting.
With a pool of 25 connections, the 26th thread that needs a connection waits, and every thread beyond that is a request sitting in memory holding a socket, generating a timeout later rather than a fast rejection now.
A ceiling of 100 gives four times the average for bursts and tolerates a doubling of request time, while making sure that under real overload the excess queues in
accept-countand then fails fast at the kernel, where it is cheapest.The default of 200 was chosen for a generic application with no knowledge of downstream limits; sizing it from the pool is the point of doing the arithmetic.
Q46 · Scenario. "During a flash sale, clients see connection refused and connection reset errors from a service, but the service's own logs show nothing wrong and CPU is at 60 percent. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: failures at the TCP level that never become HTTP requests, so the application never logs them. That points at the accept path: Tomcat's connector limits and the kernel's listen backlog.
- Evidence:
tomcat.threads.busypinned atthreads.max;tomcat.connections.currentatserver.tomcat.max-connections(default 8,192);ss -ltnon the pod showing the listen queue full (Recv-Q at the backlog limit); the load balancer's own 502 and 503 counts. - Cause chain: with all 200 worker threads busy, new connections still get accepted up to
max-connections, then queue in the kernel backlog sized byserver.tomcat.accept-count(default 100). When that fills, the kernel refuses or resets new connections. Nothing in the application sees it. The reason all 200 threads were busy is the next question, usually a downstream call that slowed under load. - Fix: immediately, scale out horizontally, which multiplies the accept capacity. Then fix the actual bottleneck: add timeouts and a bulkhead around the slow dependency so threads are released; consider
spring.threads.virtual.enabled=trueon Java 21 so waiting does not consume worker threads; setaccept-countto absorb a burst of a few seconds rather than 100 connections; and put a queue-aware load shedder in front so overload becomes a fast 503 withRetry-Afterinstead of a reset. - Prevention: alert on
tomcat.threads.busyabove 80 percent of max, and load test to the point of refusal so the number is known before the sale.
Picture it the three queues a connection passes through, and the numbers at the moment the clients start seeing refusals.
The setup: a service with the Boot defaults, a slow downstream, and a flash sale.
The trace: one new connection, hop by hop.
client SYN ──► kernel listen backlog size server.tomcat.accept-count (100)
└─► acceptor thread pulls connections while open count < max-connections (8,192)
└─► poller holds idle connections, no worker thread yet
└─► worker one of server.tomcat.threads.max (200), only while a request runs
backlog full ✗ kernel refuses or resets the new connection; Tomcat and the application never see it
What you see: the evidence at the moment of failure.
# illustrative output
$ ss -ltn
State Recv-Q Send-Q Local Address:Port
LISTEN 100 100 *:8080 # accept queue full
tomcat.threads.busy 200 (max 200)
tomcat.connections.current 7,900 (max 8,192)
$ nstat -az TcpExtListenOverflows TcpExtListenDrops
TcpExtListenOverflows 4213
TcpExtListenDrops 4213
Why: all 200 workers are stuck on the slow dependency, new connections pile up in a queue of 100, and when it is full the kernel refuses them before any application code runs, so nothing is logged.
| Symptom | Root cause | Action |
|---|---|---|
| Refused or reset, nothing in the app log | Backlog full: ListenOverflows rising | Scale out now; size accept-count for a few seconds of burst |
tomcat.threads.busy equals max, same stack in every dump | Slow dependency holds workers | Timeout and bulkhead on that dependency |
| Scaled out, same error rate | Shared dependency still slow | Load shedder at the edge, bulkhead per dependency |
What you see now: with a shedder in front, overload becomes a fast, explicit answer.
# illustrative output
HTTP/1.1 503 Service Unavailable
Retry-After: 1
# instead of: curl: (56) Recv failure: Connection reset by peer
Land it Errors the application never logs are happening before the application, and in Boot that means the connector's thread, connection, and backlog limits.
- "You scaled out and the errors continued at the same rate. What next?"
Then the bottleneck is not per-instance accept capacity; it is shared. The new instances hit the same slow dependency and their threads fill at the same rate, so the cluster-wide accept capacity grew but the drain rate did not.
I would look at the dependency first: the database's connection count, which now has more pools attached and may itself be refusing, and the partner or cache that all instances share. The thread dumps across instances will show the same stack, which names it.
Then I would apply back-pressure at the edge instead of adding capacity: a load shedder that returns 503 when
tomcat.threads.busyexceeds 90 percent, so the load balancer retries elsewhere or the client backs off, and a bulkhead around the slow dependency so unrelated endpoints keep working.- "Explain the three Tomcat numbers and how a request moves through them."
A new TCP connection first lands in the kernel's listen backlog, sized by
server.tomcat.accept-count, default 100, which is the SYN-completed queue Tomcat has not yet calledaccept()on.The acceptor thread pulls connections from it as long as the count of open connections is below
server.tomcat.max-connections, default 8,192 for NIO; above that the acceptor pauses and the backlog fills.An accepted connection is registered with the poller, which waits for data; when a request arrives, the poller hands it to a worker from the pool of
server.tomcat.threads.max, default 200.So a connection can be accepted and idle without a thread, which is why 8,000 connections and 200 threads coexist, and why the failures the client sees, refused and reset, come from the backlog overflowing, not from the thread pool.
- "What does a queue-aware load shedder look like in Boot, concretely?"
A servlet filter at high precedence that reads a cheap saturation signal and rejects early.
The signal can be the Tomcat executor's active count via the
TomcatWebServer'sThreadPoolExecutor, obtained through aWebServerFactoryCustomizerthat captures the protocol handler, or simply aSemaphoreof permits sized just belowthreads.max.If no permit is available within a few milliseconds, the filter writes 503 with
Retry-After: 1and a small problem body, without touching the handler. Spring Framework 7's@ConcurrencyLimitannotation gives the same semaphore behaviour per method for the service layer.The important detail is that the rejection must be much cheaper than the work, so the filter runs before Security and before body parsing.
- "Which metrics and alerts would have warned you before the sale?"
tomcat.threads.busyagainsttomcat.threads.config.max, alerting at 80 percent for five minutes;tomcat.connections.currentagainsttomcat.connections.config.max; and the load balancer's backend connection errors, which are the first external signal. The kernel-level one is harder:ListenOverflowsandListenDropsfromnstator/proc/net/netstaton the node, which the node exporter surfaces asnode_netstat_TcpExt_ListenOverflows, and which counts exactly the refusals the application never saw. Before the sale, a load test to the point of refusal gives the number to put on the dashboard as a line, so the on-call engineer sees how close the sale is running to it.
Q47. "Explain how virtual threads work under a Boot service, what pinning is, and what changed with JDK 24."
Reveal answer
Strong answer A virtual thread is a thread whose stack lives on the heap and which is scheduled by the JVM onto a small pool of carrier threads, one per CPU core by default, in a ForkJoinPool.
- Unmounting: When a virtual thread blocks on I/O, a lock, or sleep, the JVM unmounts it, saving its stack, and mounts another virtual thread on the same carrier; when the I/O completes, it is rescheduled.
- Cost: Creating one costs about a kilobyte and microseconds, so a million can exist.
- Boot: With
spring.threads.virtual.enabled=true, Boot configures Tomcat's executor, the@Asyncexecutor, the scheduler, and Kafka listener containers to run each task on a new virtual thread, so the 200-thread ceiling disappears; blocking JDBC code stays as it is and simply stops occupying carriers while it waits. - Pinning before JDK 24: Pinning is the case where a virtual thread cannot unmount: before JDK 24, blocking inside a
synchronizedblock or while holding a monitor pinned the carrier, and so did native frames. - Why pinning hurt: With a handful of carriers, a library that synchronised around socket reads, as older JDBC drivers did, could pin all carriers and stall everything.
- JDK 24: JDK 24 (JEP 491) reimplemented monitors so that
synchronizedno longer pins, leaving only native calls and class initialisation as pinning cases; on Java 25 the advice is simply to run the JDK's-Djdk.tracePinnedThreadscheck once and move on. - Practical changes: The practical changes: do not pool virtual threads, replace
ThreadLocalcaches with scoped values or explicit passing, and re-examine the connection pool, which becomes the real limit.
Picture it carriers and virtual threads written out as data, the pinning case as a trace, and what each JDK does with it.
The setup: one switch.
spring.threads.virtual.enabled=true
Make the invisible visible: four carrier threads on a 4-core machine serving three virtual threads.
# illustrative output
carrier ForkJoinPool-1-worker-1 mounted: VirtualThread[#41]
carrier ForkJoinPool-1-worker-2 mounted: VirtualThread[#57]
VirtualThread[#41] blocks on a socket read -> unmounted, its stack saved on the heap
carrier ForkJoinPool-1-worker-1 mounted: VirtualThread[#63] # same carrier, next virtual thread
The trace: pinning on JDK 21 to 23: a blocking read inside synchronized.
VirtualThread[#41] mounted on carrier worker-1
└─ synchronized (lock) { monitor held
└─ socket.read() ✗ blocks while holding the monitor: cannot unmount, worker-1 is pinned
VirtualThread[#57] ✓ unmounted on a blocking call, worker-1 is free again
What you see: the JFR event that reports each pinning case.
# illustrative output
jdk.VirtualThreadPinned {
duration = 312 ms
stackTrace = [ com.example.LegacyDriver.read(...) ... ]
}
| Blocking action in a virtual thread | JDK 21 to 23 | JDK 24 and later |
|---|---|---|
Blocking I/O inside synchronized | Pins the carrier | Unmounts, no pinning |
| Blocking inside a native frame | Pins the carrier | Pins the carrier |
| Blocking inside a class static initialiser | Pins the carrier | Pins the carrier |
| Plain blocking I/O, lock or sleep | Unmounts | Unmounts |
Why: a virtual thread can only unmount at a blocking call it controls; a held monitor on old JDKs, or a native frame, ties it to its carrier.
Going deeper One correction to keep the tooling advice current: the -Djdk.tracePinnedThreads system property was removed in JDK 24 along with the monitor rewrite in JEP 491.
The supported way to find remaining pinning is the JFR event jdk.VirtualThreadPinned, enabled by default with a 20-millisecond threshold, so jcmd <pid> JFR.start followed by a look at that event in JDK Mission Control or jfr print --events jdk.VirtualThreadPinned shows the stack of each pinning case.
The remaining pinning cases on JDK 24 and later are native frames (JNI or foreign function calls that block) and blocking inside a class static initialiser.
Two other operational points: the carrier pool size is jdk.virtualThreadScheduler.parallelism, defaulting to the CPU count, and jdk.virtualThreadScheduler.maxPoolSize, default 256, is how many extra carriers may be created to compensate when pinning happens.
And a ThreadLocal is not broken on virtual threads, it is simply expensive at scale because a million threads means a million copies; ScopedValue, final in JDK 25 under JEP 506, is the replacement for the "pass context down the call" use.
Land it Virtual threads make waiting free but not scarce resources plentiful, so the bulkhead moves from the thread pool to whatever you were waiting on.
- "What exactly does Boot switch when I set
spring.threads.virtual.enabled=true, and what does it not switch?" Boot replaces Tomcat's executor with a virtual-thread-per-task executor via a
TomcatProtocolHandlerCustomizer, replaces the auto-configuredapplicationTaskExecutorfor@Asyncand thetaskSchedulerfor@ScheduledwithSimpleAsyncTaskExecutorandSimpleAsyncTaskSchedulerin virtual mode, and configures the Kafka, RabbitMQ, and Pulsar listener containers to use virtual threads.It does not change thread pools you built yourself, any executor a library creates internally, Reactor's schedulers, or the JDBC driver's behaviour. Jetty gets the same treatment; for Netty and WebFlux the setting has no effect because event loops are a different model.
The verification is a thread dump: request threads named like
tomcat-handler-0and marked as virtual, andjvm.threads.livestaying flat under load.- "What breaks in a typical Boot service when you flip it on?"
Three usual things.
First, anything that relied on the thread pool as a concurrency limit: with no ceiling, a burst opens a thousand database requests and the connection pool, or the database, becomes the failure point, so bulkheads must be added where the pool used to be one implicitly.
Second,
ThreadLocal-based caches that assumed a bounded number of threads, such as a per-threadSimpleDateFormator a per-thread buffer, now create one per request.Third, before JDK 24, libraries that block inside
synchronizedpinned carriers; the classic was the PostgreSQL JDBC driver before version 42.6 and some Hikari paths. On JDK 24 and later that is gone. Micrometer'sexecutormetrics also go quiet because there is no pool to measure.- "Should you ever pool virtual threads, and what do you use instead of a pool for limiting?"
No. A virtual thread is cheap to create and expensive to keep idle only in the sense that it holds its stack, so a pool of them gains nothing and reintroduces the ceiling you removed.
The limiting concern is real, though: a pool limited both threads and concurrency, and the concurrency limit still has to live somewhere.
The tool is a
Semaphorearound the scarce resource, sized to what the resource can serve, or Resilience4j's bulkhead, or Spring Framework 7's@ConcurrencyLimit(20)on the method that touches the resource.Structured concurrency, preview in JDK 21 through 24 and final in JDK 25 under JEP 505, gives
StructuredTaskScopefor fan-out with automatic cancellation, which is what most people wanted a pool for.- "How do you verify in production that virtual threads are actually helping?"
Compare the same load on two canaries, one with the flag on.
The signals that should change:
tomcat.threads.busybecomes meaningless andjvm.threads.livedrops to a few dozen carriers; under a slow-dependency test, the platform-thread canary's throughput collapses when the pool fills while the virtual one degrades only on the dependency-bound path; memory per concurrent request drops from about a megabyte of stack reservation to tens of kilobytes.What should not change: p50 latency on CPU-bound endpoints, because virtual threads do not make computation faster. If throughput is identical in both canaries, the service was never thread-bound, and the flag is harmless but also pointless.
Q48 · Design. "Design an idempotent payment endpoint: a client may retry POST /payments after a timeout and must never be charged twice."
Reveal answer
Strong answer Requirements: exactly-once effect under retries, safe under concurrent duplicates, correct even if our process dies mid-request, and a clear contract. Design: the client sends an Idempotency-Key header, a UUID it generates per logical payment and reuses on retry.
- The table: The service keeps an
idempotency_keystable with the key as primary key, plus the request fingerprint (a hash of the body), the state (IN_PROGRESS,DONE), the stored response, and a created-at timestamp. - The flow: The controller flow is one transaction: insert the key with state
IN_PROGRESS; a primary-key violation means a duplicate, so read the existing row. If it isDONE, return the stored response with the same status code. - In flight or different body: If it is
IN_PROGRESS, another request is mid-flight, so return 409 withRetry-After: 1. If the fingerprint differs, return 422, because the same key with a different body is a client bug. - The charge: Otherwise perform the charge, record the payment row and the gateway's own idempotent reference in the same database transaction as the key row's update to
DONEwith the response, and commit. - The gateway: The gateway call is the hard part because it sits outside our transaction: pass our key to the gateway as its idempotency key too, so a crash after the gateway charged but before we committed is repaired by the retry, which asks the gateway for the same key and gets the original result rather than a second charge.
- Housekeeping and trade-offs: Keys expire after 24 hours by a scheduled cleanup. Trade-offs: one extra insert per request; the
IN_PROGRESSstate needs a timeout so a crashed request does not lock a key forever. - What I would not do: What I would not do: rely on a Redis
SETNXalone, because it is not transactional with the payment row; or deduplicate on body hash without a client key, since two legitimate identical payments then collide.
@RestController
public class PaymentController {
@PostMapping("/payments")
ResponseEntity<PaymentResponse> pay(
@RequestHeader("Idempotency-Key") @NotBlank String key,
@Valid @RequestBody PaymentRequest body) {
// The key is the client's, generated once per logical attempt and
// REUSED across retries. The request fingerprint guards against a
// client reusing a key for a different payload.
return service.payOnce(key, fingerprint(body), body);
}
}
@Service
public class PaymentService {
@Transactional
public ResponseEntity<PaymentResponse> payOnce(String key, String fp, PaymentRequest r) {
// 1. Claim the key. The unique index does the concurrency control:
// two simultaneous retries, only one INSERT survives.
try {
attempts.insertClaim(key, fp); // UNIQUE(idempotency_key)
} catch (DuplicateKeyException dup) {
IdempotentAttempt prior = attempts.find(key);
if (!prior.fingerprint().equals(fp)) {
return ResponseEntity.status(422).build(); // same key, different body
}
if (prior.isComplete()) {
return ResponseEntity.ok(prior.response()); // replay the stored result
// Result: a retry after DONE returns the stored response and charges nothing
}
return ResponseEntity.status(409).build(); // still in flight; retry later
}
// 2. Do the work exactly once, then store the response for replay.
// ❌ TRAP: this call is outside our DB transaction; a crash after it but before commit leaves a charge with no row
// ✅ FIX: send the same key to the gateway as its idempotency key, so the retry gets the original charge back
PaymentResponse resp = gateway.charge(r);
attempts.complete(key, resp);
return ResponseEntity.ok(resp);
}
}
Read where the concurrency is handled. It is the database's unique index, not application logic — two retries racing at the same millisecond both attempt the insert and exactly one wins, which no amount of checking-then-inserting in Java can guarantee.
Picture it one key followed through a concurrent duplicate, a replay and a crash, and the rows each leaves behind.
The setup: the code above, called three times with the same Idempotency-Key: K1.
The trace: two requests race, then a client retry arrives after a timeout.
Request A (K1) ──► INSERT idempotency_keys (K1, IN_PROGRESS) ✓ wins
Request B (K1) ──► INSERT idempotency_keys (K1, ...) ✗ DuplicateKeyException
└─► read row: IN_PROGRESS -> 409, Retry-After: 1
Request A ──► gateway.charge(key=K1) -> complete(K1, response) -> DONE
Retry C (K1) ──► INSERT ✗ duplicate -> row is DONE, same fingerprint
└─► 200 with the stored response, no second charge ✓
What you see: without a key table, the client's timeout-and-retry charges twice. With it, the same two attempts leave one charge.
# illustrative output
WITHOUT idempotency key WITH idempotency key
payments idempotency_keys
id amount card key state fingerprint response
p_1 49.00 4242 K1 DONE 9f2c... {"paymentId":"p_1"}
p_2 49.00 4242 <- charged twice payments
id amount gateway_ref
p_1 49.00 K1 <- one row
Why: the primary key on the key column decides the race inside the database, and the stored response lets a retry be answered without repeating the effect.
Land it Idempotency is a client-supplied key stored in the same transaction as the effect, and forwarded to any external system that has its own effect.
- "Requirement change: the gateway has no idempotency support. What changes?"
Then the crash window between the gateway charging and our commit cannot be repaired by asking the gateway for the same key, so I need a reconciliation path.
Before calling the gateway I write the key row with state IN_PROGRESS and our own reference id, and commit that small transaction separately. The gateway call carries our reference in its metadata field, which nearly every gateway has.
If we crash after the charge, the retry finds the row IN_PROGRESS with a reference and, instead of charging again, queries the gateway's transaction search by that reference, finds the charge, and completes the row.
If the search finds nothing, the charge did not happen and the retry proceeds. A background reconciler sweeps IN_PROGRESS rows older than a minute with the same logic. The cost is two commits per payment and a dependency on the gateway's search API.
- "What would you cut with two days?"
I would cut the fingerprint comparison, the stored response replay, and the key expiry job.
I would keep the key table with a primary key, the IN_PROGRESS and DONE states, the single transaction around the charge record and the state change, and forwarding the key to the gateway.
That version prevents double charges, which is the requirement; a retry after DONE returns 200 with the payment id looked up by key rather than a byte-identical response, which clients can live with.
The fingerprint check protects against a client bug, and the expiry protects the table size; both can come next week. What I would not cut is the 409 for IN_PROGRESS, because without it two concurrent duplicates race to the gateway.
- "How do you handle the concurrent-duplicate race precisely, at the database level?"
The insert of the key row is the lock. Both requests attempt
INSERT INTO idempotency_keys (key, state) VALUES (?, 'IN_PROGRESS'); the primary key constraint guarantees exactly one succeeds and the other gets a unique violation, which Spring translates toDataIntegrityViolationException. The loser then reads the row.Under READ COMMITTED it sees IN_PROGRESS and returns 409. There is one subtlety: if the winner is still in its transaction, the loser's insert blocks until the winner commits or rolls back, because the database must know whether the key will exist.
That blocking is bounded by the winner's transaction time, which is the gateway call, so I keep the key insert in its own short transaction before the charge, and the charge and DONE update in a second one, so the loser is released immediately.
two sessions, same keyruns offlinesession A: BEGIN; INSERT INTO idempotency_keys (key, state) VALUES ('K1', 'IN_PROGRESS'); -- ok session B: BEGIN; INSERT INTO idempotency_keys (key, state) VALUES ('K1', 'IN_PROGRESS'); -- blocks, waits for A session A: COMMIT; session B: ERROR: duplicate key value violates unique constraint "idempotency_keys_pkey" # in PostgreSQL B's transaction is now aborted; B must read the row in a new transaction- "Where does the idempotency key live in a system with a gateway and a queue, and who generates it?"
The client generates it, because only the client knows that two attempts are the same logical intent; a server-generated key would be assigned per attempt and defeat the purpose.
For a browser checkout it is generated when the payment form is rendered and stored in the form state. Through an API gateway it passes as a header untouched.
If the payment is later processed by a queue consumer, the message carries the key and the consumer applies the same table check, so the key is the single identity of the payment across HTTP, queue, and the external gateway.
The header name I use is
Idempotency-Key, matching the IETF draft that Stripe's and others' APIs follow, so client libraries already know it.
Q49. "When a controller throws, how does Spring choose which @ExceptionHandler runs, and what is ProblemDetail buying you over a custom error class?"
Reveal answer
Strong answer The DispatcherServlet iterates its HandlerExceptionResolvers in order.
- First resolver, closest type wins: The
ExceptionHandlerExceptionResolverruns first: it looks for@ExceptionHandlermethods in the controller class that threw, then in every@ControllerAdvicebean in@Order, and within a class it picks the handler whose declared exception type is closest in the class hierarchy to the thrown one, so a handler forExceptionloses to one forIllegalStateExceptionif both apply. - Scoping and fallbacks: An advice can be scoped with
basePackagesorassignableTypes. If no handler matches, theResponseStatusExceptionResolverhandlesResponseStatusExceptionand@ResponseStatus-annotated exceptions, and theDefaultHandlerExceptionResolvermaps Spring's own exceptions such asHttpMessageNotReadableExceptionto 400 andHttpRequestMethodNotSupportedExceptionto 405. - Last resort: Anything still unhandled goes to the container's error page, which Boot maps to
/errorandBasicErrorController. - What
ProblemDetailbuys you:ProblemDetailgives you the RFC 9457 shape,application/problem+jsonwithtype,title,status,detail,instance, and extension properties, so every client, gateway, and logging pipeline can parse errors the same way; and when you extendResponseEntityExceptionHandlerin your advice, all of Spring's built-in exceptions already produce it, so your custom errors and the framework's look identical to the client.
@RestControllerAdvice
public class ApiExceptionHandler {
// Spring picks the handler whose parameter type is the CLOSEST match in the
// exception's class hierarchy — most specific wins, not declaration order.
@ExceptionHandler(OrderNotFound.class) // chosen for OrderNotFound
// Result: HTTP 404, Content-Type application/problem+json (see the response below)
ProblemDetail onNotFound(OrderNotFound e) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(NOT_FOUND, e.getMessage());
pd.setType(URI.create("https://errors.example.com/order-not-found"));
pd.setTitle("Order not found");
pd.setProperty("orderId", e.orderId()); // extension member
return pd;
}
@ExceptionHandler(RuntimeException.class) // fallback for everything else
ProblemDetail onUnexpected(RuntimeException e) {
// ❌ TRAP: never put e.getMessage() or a stack trace in the body; it leaks internals
log.error("unhandled", e); // log the detail...
return ProblemDetail.forStatusAndDetail(
INTERNAL_SERVER_ERROR, "Something went wrong."); // ...leak none of it
}
}
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "https://errors.example.com/order-not-found",
"title": "Order not found",
"status": 404,
"detail": "No order with id 4021",
"instance": "/orders/4021",
"orderId": "4021"
}
Read the content type. application/problem+json is what makes this more than a convention — clients and gateways can detect a problem document generically, whereas a bespoke error shape has to be special-cased per API.
Picture it the resolver chain written out, and the choice between two handlers that both match.
The setup: the advice in the code above, with OrderNotFound extends RuntimeException. Both handlers match when a controller throws it.
Make the invisible visible: the resolvers the DispatcherServlet walks, in order.
HandlerExceptionResolverComposite
1 ExceptionHandlerExceptionResolver controller's own @ExceptionHandler, then @ControllerAdvice beans in @Order
2 ResponseStatusExceptionResolver ResponseStatusException, @ResponseStatus
3 DefaultHandlerExceptionResolver Spring's own exceptions: HttpMessageNotReadableException -> 400, 405 for wrong method
unresolved -> container error page /error -> BasicErrorController
The trace: one throw, hop by hop.
controller throws OrderNotFound
└─► ExceptionHandlerExceptionResolver
├─ controller class: no @ExceptionHandler here
├─ ApiExceptionHandler candidates: OrderNotFound (exact match) ✓ closest type wins
│ RuntimeException (farther away) ✗ not chosen
└─► onNotFound(...) returns ProblemDetail -> HTTP 404
What you see: before there was a handler, and after. The "after" is the JSON block above.
# illustrative output
HTTP/1.1 404
Content-Type: application/json
{"timestamp":"2026-03-01T10:15:30.123+00:00","status":404,"error":"Not Found","path":"/orders/4021"}
Why: the resolver compares the thrown type with each handler's declared type and takes the nearest one, so declaration order does not matter, and the body shape is whatever the handler returns.
Land it Handler selection is "nearest type wins, controller before advice", and ProblemDetail makes the framework's errors and yours one contract.
- "Two advices both handle
IllegalArgumentException. Which wins, and how do you make it deterministic?" The first advice in order wins, because
ExceptionHandlerExceptionResolveriterates the advice beans sorted by@Orderand returns on the first whose handler matches. Two advices without explicit order are sorted at the lowest precedence in an unspecified order, which changes between builds.So every advice gets an explicit
@Order, and a domain-specific advice, for example one scoped withbasePackagesto the payments controllers, gets a lower value than the global one so it runs first.I test this with a
@WebMvcTestthat throws the exception from a controller in the scoped package and asserts the domain-specific body.Also worth knowing: within one advice, the resolver picks the handler whose exception type is closest in the hierarchy, and it caches that mapping per exception class after the first lookup.
- "How do you add fields to a
ProblemDetailand control thetypeURI?" The calls, one per concern:
ProblemDetail.forStatusAndDetail(HttpStatus.UNPROCESSABLE_ENTITY, "…")creates it.setType(URI.create("https://api.shop.example/problems/insufficient-stock"))sets the type.setTitlesets a short human label.setProperty("sku", sku)adds an extension member that Jackson serialises as a top-level field.
The
instancedefaults to the request path. Throwing anErrorResponseExceptionsubclass, which carries aProblemDetail, lets the service layer produce the shape without knowing about MVC.For consistency I keep a small registry of type URIs in one class and make the type URL resolve to a real documentation page. For message localisation,
ResponseEntityExceptionHandlerresolvesdetailthrough aMessageSourcewith keys likeproblemDetail.type.…if one is present.- "Does
ResponseEntityExceptionHandlerchange behaviour when you extend it, and is that safe for an existing API?" Yes, it changes the bodies of every Spring-generated error. Before, a malformed JSON body produced Boot's default error map with
timestamp,status,error, andpath; after extending it, the same failure producesapplication/problem+jsonwithtype,title,status, anddetail.Clients parsing the old shape break, so it is an API change. Boot also has
spring.mvc.problemdetails.enabled=true, which registers a defaultResponseEntityExceptionHandlerwithout any code and has the same effect.For an existing API I would introduce it behind a canary with a contract test on the error shape, and I would announce it, because error bodies are the part of the contract nobody documents and everybody parses.
- "What happens to exceptions thrown from inside an
@ExceptionHandler?" The resolver catches it, logs a warning "Failure in @ExceptionHandler", and returns null, meaning "not handled", so the next resolver in the chain gets the original exception, not the new one.
If nothing else handles it, the original exception reaches the container and Boot's
/errorpath renders a generic 500.So a bug in the advice, such as a null dereference while building the body, produces a response in the old default shape rather than a problem body, which is a confusing symptom.
I keep handlers small and defensive, never call services from them, and have a test that throws each mapped exception and asserts the status and content type, which is where a broken handler is found.
a broken handlerruns offline# illustrative output WARN ... Failure in @ExceptionHandler ApiExceptionHandler#onUnexpected(RuntimeException) (NullPointerException while building the body) -> the original exception goes to the next resolver, then to /error HTTP/1.1 500 Content-Type: application/json {"timestamp":...,"status":500,"error":"Internal Server Error",...} <- old shape, not problem+json
Q50 · Scenario. "Your @RestControllerAdvice returns nice ProblemDetail bodies for everything, except expired JWTs, which come back as an empty 401. Product wants the same JSON shape. Diagnose and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: one error class bypasses the advice. Expired-token failures are produced in Spring Security's
BearerTokenAuthenticationFilter, which runs before the DispatcherServlet, so the exception never enters MVC and the advice never sees it. - Evidence: the response carries
WWW-Authenticate: Bearer error="invalid_token", error_description="Jwt expired at ...", which is the signature of Security'sBearerTokenAuthenticationEntryPoint, and no advice log line appears. - Cause: authentication errors are handled by the
ExceptionTranslationFilter, which calls the chain'sAuthenticationEntryPointfor 401 andAccessDeniedHandlerfor 403. Those are the extension points, not the advice. - Fix: configure
oauth2ResourceServer(o -> o.authenticationEntryPoint(entryPoint).accessDeniedHandler(handler))with implementations that write aProblemDetail. To avoid duplicating the advice's formatting, implement the entry point by delegating to theHandlerExceptionResolverbean namedhandlerExceptionResolver: callresolver.resolveException(request, response, null, authException), and add an@ExceptionHandler(AuthenticationException.class)to the advice; the resolver routes the exception into MVC's normal handling even though it came from a filter. Keep theWWW-Authenticateheader, since clients and the OAuth2 spec expect it. - Prevention: a
@WebMvcTestwith@Import(ApiSecurityConfig.class)and an expired token asserting the problem+json content type, so the contract is tested at the edge where it actually lives.
Picture it the path an expired token takes, which never touches MVC, and the response before and after the fix.
The setup: a resource server with the advice you already have, and a request carrying an expired token.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())); // ❌ TRAP: default entry point, empty body
return http.build();
}
The trace: one hop per line. The advice sits in the part of the diagram the request never reaches.
request ──► BearerTokenAuthenticationFilter
└─► JwtDecoder: Jwt expired ✗ AuthenticationException
└─► BearerTokenAuthenticationEntryPoint writes 401 + WWW-Authenticate, empty body
DispatcherServlet ──► never reached ✗ @RestControllerAdvice never sees it
What you see: the response as the client gets it today.
# illustrative output
HTTP/1.1 401
WWW-Authenticate: Bearer error="invalid_token", error_description="Jwt expired at 2026-03-01T10:00:00Z"
Content-Length: 0
# no advice log line appears
Why: authentication errors are born in a servlet filter and handled by the entry point, and the advice only handles exceptions thrown inside the DispatcherServlet.
The fix: an entry point that hands the exception to the same resolver the DispatcherServlet uses, plus a handler in the advice.
@Component
class ProblemEntryPoint implements AuthenticationEntryPoint {
private final HandlerExceptionResolver resolver;
ProblemEntryPoint(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver) {
this.resolver = resolver;
}
@Override public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException ex) {
resolver.resolveException(req, res, null, ex); // ✅ FIX: route the filter's exception into the advice
}
}
// in the security config: .oauth2ResourceServer(o -> o.jwt(...).authenticationEntryPoint(entryPoint).accessDeniedHandler(handler))
// in the advice: @ExceptionHandler(AuthenticationException.class) ProblemDetail onAuth(AuthenticationException e) { ... }
What you see now: the same request, now with the contract body.
# illustrative output
HTTP/1.1 401
Content-Type: application/problem+json
{"title":"Unauthorized","status":401, "detail": "..."}
# Result: body is correct; add the WWW-Authenticate header yourself (see the follow-up below)
Land it Security errors are born outside MVC, so bridge them in through the entry point and the exception resolver rather than hoping the advice catches them.
- "You wired the entry point through the resolver and now the 401 has a problem body but the
WWW-Authenticateheader is gone. What next?" The original
BearerTokenAuthenticationEntryPointwas what wrote that header, and my delegating entry point replaced it entirely.The fix is to compose rather than replace: my entry point first calls the original bearer entry point's header logic, which is simplest by building the header string myself from the
OAuth2AuthenticationException's error code and description, sets it on the response, then delegates to theHandlerExceptionResolverfor the body.The resolver writes the body through the advice, which must not reset headers;
ResponseEntityfrom the advice merges headers, so the header survives.The test asserts both the
application/problem+jsoncontent type and aWWW-Authenticatestarting withBearer error="invalid_token", because clients such as OAuth libraries key their refresh behaviour on that header.the header went missingruns offline# illustrative output before the change: HTTP/1.1 401 WWW-Authenticate: Bearer error="invalid_token", ... Content-Length: 0 after replacing the entry point: HTTP/1.1 401 Content-Type: application/problem+json <- no WWW-Authenticate ✗ after composing (header set first, then resolver): both Content-Type and WWW-Authenticate are present ✓- "Why is the resolver bean named
handlerExceptionResolversafe to call from a filter at all?" It is the composite
HandlerExceptionResolverCompositethat theDispatcherServletitself uses, containing the exception-handler resolver, the response-status resolver, and the default resolver.Calling
resolveException(request, response, null, ex)from a filter runs the same chain with a null handler, and the advice-based resolver works without a handler since Spring 5.What it cannot do from a filter is anything that needs the
HandlerMethod, such as controller-local@ExceptionHandlermethods, so only@ControllerAdvicehandlers apply. The security filter runs before the request attributes MVC sets, so a handler that reads a path variable will not find one.It is a bridge, not a full dispatch, and that is enough for formatting an error body.
- "What about 403 from method security, does that reach the advice?"
It depends where it is thrown.
@PreAuthorizeon a service method throwsAccessDeniedExceptioninside the controller's call stack, which is inside MVC, so the advice sees it and a plain@ExceptionHandler(AccessDeniedException.class)formats it.But the
AuthorizationFilter's URL-rule denial and the@PreAuthorizeon a controller method that is evaluated by the security interceptor still throw inside MVC in the second case and outside it in the first.So there are two 403 paths: the filter path handled by the chain's
AccessDeniedHandler, and the MVC path handled by the advice. The consistent approach is to wire theAccessDeniedHandlerto the same resolver trick, so both paths end in the same advice method.- "How would you test this at the edge without spinning up a real identity provider?"
With
spring-security-test. A@WebMvcTestthat imports the security configuration and replaces theJwtDecoderwith a@MockitoBeanthat throwsJwtValidationExceptionwith an expired-token error for a given token string.The test sends a request with
Authorization: Bearer expiredthroughMockMvcand asserts status 401, content typeapplication/problem+json, adetailmentioning expiry, and theWWW-Authenticateheader. For the happy path,jwt()fromSecurityMockMvcRequestPostProcessorsinjects a fake JWT with chosen claims.That covers the filter, the entry point, and the advice in one fast test with no network, which is exactly the layer where the bug lived.
This group tests the edges of the web layer: where validation really runs, how bodies are read and written, and what an outbound call costs you.
Q51. "Explain validation groups, nested validation, and method-level validation in a Boot service, and where each is enforced."
Reveal answer
Strong answer Jakarta Bean Validation runs wherever a Validator is invoked, and Spring invokes it in two places.
- Controller:
@Validor@Validatedon a@RequestBodyor model attribute runs the validator after binding and before the method. Failures becomeMethodArgumentNotValidException, mapped to 400. - Nested objects: Nested objects are validated only if the containing field also carries
@Valid; without it, aList<LineItem>inside the order passes untouched, which is the most common validation hole. - Container elements and parameters: Since Spring 6.1, a controller parameter of type
List<@Valid LineItem>works directly through the container-element constraint, and constraints on plain parameters such as@RequestParam @Min(1) int pageare enforced by the built-in method validation, throwingHandlerMethodValidationException. - Groups: Groups let one class carry different rules for different operations:
@NotNull(groups = OnUpdate.class) Long id, and the controller selects with@Validated(OnUpdate.class); plain@Validmeans theDefaultgroup only. - Method validation on any bean: The second enforcement point is method validation on any bean: annotate the class with
@Validated, and aMethodValidationPostProcessorproxies it so constraints on method parameters and return values are checked on every call through the proxy, throwingConstraintViolationException. - Why it matters: That is how a service called from Kafka or a scheduler gets the same protection, and it has the same self-invocation caveat as every proxy.
Picture it one request body that slips through, the fix, and a table of which exception each validation path raises.
The setup: a nested list without @Valid.
record OrderRequest(@NotBlank String customer,
List<LineItem> items) {} // ❌ TRAP: no @Valid, items are never checked
record LineItem(@NotBlank String sku, @Min(1) int qty) {}
@PostMapping("/orders") OrderDto create(@Valid @RequestBody OrderRequest request) { ... }
// ✅ FIX: @Valid @NotEmpty List<LineItem> items
What you see: the same body, before and after.
# illustrative output
before the fix: controller runs with sku="" qty=0 -> 201 Created ✗ bad data accepted
after the fix: MethodArgumentNotValidException -> 400
field errors: items[0].sku (must not be blank), items[0].qty (must be greater than or equal to 1)
Why: the validator descends into a nested object only where the field carries @Valid, so each level has to say so.
| Code and call | Outcome |
|---|---|
@Valid @RequestBody body fails a constraint | Throws MethodArgumentNotValidException, 400 |
@RequestParam @Min(1) int page with page=0 on a controller | Throws HandlerMethodValidationException, 400 |
Service method of a @Validated bean called through the proxy with a bad argument | Throws ConstraintViolationException; unmapped, it becomes 500 |
The same method called as this.method(...) inside the service | Silently not applied |
Nested List<LineItem> field without @Valid | Silently not applied |
Land it Validation runs only where something invokes the validator, and @Valid on the outer object does not descend unless you say so at every level.
- "Why do the controller path and the method-validation path throw different exceptions, and how do you make the responses identical?"
They are produced by different machinery. Controller body validation runs inside the
WebDataBinderand reports through aBindingResult, so it throwsMethodArgumentNotValidException, which carries field errors.Method validation runs in the
MethodValidationInterceptorproxy and throwsConstraintViolationExceptionwith a set of violations whose property paths look likecreateOrder.request.items[0].sku. Since Spring 6.1, controller method validation of parameters throws a third type,HandlerMethodValidationException.To unify them, the advice has a handler for each that converts to the same
ProblemDetailwith anerrorsextension listing field and message;ResponseEntityExceptionHandleralready handles the first and third, so I add theConstraintViolationExceptionone and strip the method-name prefix from the property path.- "How do you validate a record-based request body with cross-field rules?"
Field constraints go on the record components, and Bean Validation reads them from the component's accessor or field.
Cross-field rules, such as "end date after start date", need a class-level constraint: a custom annotation with a
ConstraintValidator<ValidRange, DateRange>whoseisValidreads both components, or a method in the record annotated@AssertTruesuch asboolean isRangeValid(), which is validated as a property namedrangeValid.I prefer the custom annotation because the error can be attached to a specific field with
context.buildConstraintViolationWithTemplate(...).addPropertyNode("endDate"), so the client sees which field to fix.Validation groups work on records exactly as on classes, and the record's compact constructor is the wrong place for validation because it throws before the validator can collect all errors.
- "What is the cost of method validation on a hot service method, and where is it enforced in a native image?"
Each call through the proxy resolves the method's constraint metadata, cached after the first call, then evaluates each constraint reflectively; for a few simple constraints that is a few microseconds, negligible for anything that touches a database and noticeable only on a pure in-memory method called millions of times.
In that case I move the constraint to the boundary and keep the internal method plain.
In a native image, Hibernate Validator needs reflection hints for the validated types and constraint validators; Spring AOT registers hints for types reachable from
@Validatedbeans and controller signatures, but a constraint on a type only reached through a generic can be missed, with the symptom being a validator that silently finds no constraints.The test for that is the
nativeTestrun asserting a violation is thrown.- "Where does validation run for a Spring Data repository save or a Kafka listener payload?"
JPA entities are validated by Hibernate ORM's integration at
persistandupdatetime, in the pre-insert and pre-update event listeners. That needsjakarta.validationon the classpath andjakarta.persistence.validation.modenot set tonone.A violation surfaces as a
ConstraintViolationExceptionat flush, which is inside the transaction commit and therefore late.Kafka listener payloads are validated if a
Validatoris set on the listener container factory's message handler method factory, with@Validor@Payload @Validon the parameter. Failures go to the error handler, not to any advice.Neither is automatic in the way controllers are, which is why the reliable position is to validate at every boundary explicitly and treat the entity-level validation as a last line.
Q52 · Scenario. "A @Validated service method with @NotNull on a parameter accepts nulls in production but rejects them in a unit test. The controller path works fine. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: method validation applies in one call path and not another, with the same class. That smells like the proxy again: validation is applied by a proxy, and some caller reaches the method without going through it.
- Evidence: in the production path, add a log of
this.getClass()at the call site; check whether the caller is in the same class as the validated method, or whether the caller got the bean throughnewor through a@Beanmethod that built it manually instead of through injection. - Likely causes, ranked: self-invocation within the service, so the
@Validatedproxy is bypassed; the production caller constructs the service directly, for example in a legacy factory, so there is no proxy at all; the method isfinalor package-private so CGLIB could not intercept it, and the unit test, which is not really a unit test, happens to go through a different overload; or the parameter annotation is on an interface method while the implementation is called by class, which the validator's hierarchy rules may not apply. - Fix: route the call through an injected reference to a separate bean; remove the manual construction; make the method public and non-final; put constraints on the implementation or ensure the bean is injected by its interface type consistently. Add an explicit null check with
Objects.requireNonNullat the boundary regardless, because validation is a proxy feature and a null is a programming error. - Prevention: enable JSpecify
@NullMarkedon the package so the IDE and static analysis flag null passing at compile time, which Spring Framework 7 supports across its own APIs.
Picture it the proxy written out, a call trace where one path skips it, and the exception you get once the call goes through the proxy.
The setup: a validated service whose batch method calls its own single method.
@Service @Validated
public class PricingService {
public Money quote(@NotNull String sku) { ... }
public void quoteAll(List<String> skus) {
for (String sku : skus) {
this.quote(sku); // ❌ TRAP: this is the raw object, the validating proxy is bypassed
}
}
}
Make the invisible visible: what the proxy Spring builds around it does, as pseudo-Java.
class PricingService$$SpringCGLIB$$0 extends PricingService {
Money quote(String sku) { validateParameters(this, "quote", sku); // MethodValidationInterceptor
return target.quote(sku); }
void quoteAll(List<String> skus) { /* no constraints on this method */
target.quoteAll(skus); }
}
The trace: one hop per line.
controller ──► proxy.quote(null) validation runs ✓ ConstraintViolationException
controller ──► proxy.quoteAll([null]) nothing to validate on this method
└─► target.quoteAll
└─► this.quote(null) ✗ direct call on the real object; proxy never entered, null accepted
unit test ──► Validator.forExecutables() no proxy involved ✓ rejects null
What you see: the two outcomes for the same null.
# illustrative output
production: quote(sku=null) executed, returned a price # no exception
unit test: ConstraintViolationException: quote.sku: must not be null
The fix: call the validated method through an injected bean, and keep the cheap null check in the method.
@Service
class BatchPricing {
private final PricingService pricing; // injected: this is the proxy
BatchPricing(PricingService pricing) { this.pricing = pricing; }
void quoteAll(List<String> skus) { skus.forEach(pricing::quote); } // ✅ FIX: goes through the proxy
}
// and inside quote(): Objects.requireNonNull(sku, "sku");
What you see now: the same call path.
# illustrative output
production: ConstraintViolationException: quote.sku: must not be null # same as the unit test
Land it Any annotation that works in one path and not another is the proxy telling you which path bypassed it.
- "You made the caller go through an injected reference and it still accepts null. What next?"
Then the bean itself is not proxied for validation. I would check three things. Whether
MethodValidationPostProcessorexists in the context, which requiresspring-boot-starter-validationon the classpath; without Hibernate Validator the post-processor is not auto-configured and@Validatedis inert.Whether the class-level
@Validatedis present on the implementation class, not only on an interface, because the post-processor's pointcut matches on the class annotation.And whether the bean was created after the post-processor: a bean pulled early by a non-static
@Beanpost-processor method gets the "not eligible" warning and no proxy.AopUtils.isAopProxy(bean)in a test gives the direct answer.If it is not a proxy, the log at startup will usually have the eligibility warning naming it.
- "How does the constraint on an interface parameter behave versus on the implementation?"
Bean Validation's method-validation rules forbid strengthening preconditions in a subtype, so parameter constraints must be declared once in the hierarchy, and Hibernate Validator throws
ConstraintDeclarationExceptionat first invocation if both the interface and the implementation declare parameter constraints on the same method.Return-value constraints may be added in the implementation. If only the interface has the parameter constraints, they are found and enforced when the proxy intercepts the call, regardless of whether the proxy is JDK or CGLIB, because the validator walks the hierarchy.
The failure the scenario hints at is a mixed state after a refactor: constraints moved from the interface to the class on one overload and not the other, so one path is validated and one is not.
- "Why do you still add
Objects.requireNonNullif validation is in place?" Because validation is an aspect applied by the container and the null check is part of the method.
The aspect disappears whenever the method is reached without the proxy, in a unit test that constructs the class, in a static factory, in a future refactor that inlines a call, and in a native image where a hint is missing.
A
requireNonNullwith a message, or a JSpecify@NullMarkedpackage with a static checker, holds in all of those cases.There is also a semantic difference: a null here is a programming error, which should be a
NullPointerExceptionin a stack trace pointing at the bug, not a validation error dressed as a client mistake with a 400.Validation is for input that a client can get wrong; nulls between our own classes are ours.
- "How would you make method validation itself testable without booting the whole context?"
Two levels. The pure level: obtain a
ValidatorfromValidation.buildDefaultValidatorFactory()and callvalidator.forExecutables().validateParameters(bean, method, args), which exercises the constraints with no proxy and no Spring.The wiring level: an
ApplicationContextRunnerwithValidationAutoConfigurationand the service bean, calling the method through the context and assertingConstraintViolationException, which boots in well under a second and proves the proxy is applied in the real bean configuration.The scenario's "works in a unit test" was probably the first kind, which never involved the proxy, which is why it could not have caught the production path.
Q53. "How does Spring choose the message converter for a response, and how would you stream a 500 MB CSV export without holding it in memory?"
Reveal answer
Strong answer Two questions: which converter writes the body, and how to stream a big one.
- Negotiate: Content negotiation starts with the request's
Acceptheader, optionally overridden by a path extension or a query parameter if you enable them. It produces an ordered list of acceptable media types. - Pick a converter: The return value handler then walks the registered
HttpMessageConverters in order and picks the first whosecanWrite(type, mediaType)is true for one of those types: the Jackson converter for JSON, the string converter for text, the byte-array and resource converters for binary. - The memory problem: For a 500 megabyte export, returning a
List<Row>materialises everything and Jackson then serialises it into an in-memory buffer, so the process needs gigabytes. - The tool: The right tool is a
StreamingResponseBody, a callback that receives the rawOutputStreamand writes to it as rows arrive from a JDBCStreamor a paged query; set the content type andContent-Dispositionon theResponseEntityand let the servlet write chunked transfer encoding. - Async caveats: Because the callback runs asynchronously on the MVC async executor (
spring.mvc.async.request-timeoutapplies), the transaction and the JDBC cursor must be opened inside the callback, and the repository query must be a streaming one withfetchSizeset, since Postgres returns everything at once otherwise. - WebFlux and open-in-view: On WebFlux the same job is a
Flux<DataBuffer>. Either way, disableopen-in-viewso the entity manager is not held for the whole download.
// BROKEN — builds the whole file in heap, then writes it. 500 MB of List plus
// 500 MB of serialised bytes, per concurrent request.
// ❌ TRAP: List<OrderDto> is fully materialised before Jackson writes the first byte
@GetMapping("/export")
public ResponseEntity<List<OrderDto>> exportAll() {
return ResponseEntity.ok(repo.findAll().stream().map(OrderDto::from).toList());
}
// CORRECT — StreamingResponseBody writes directly to the socket. Constant memory.
// ✅ FIX: stream the query and the response together
// Result: heap stays flat; the first row reaches the client within milliseconds
@GetMapping(value = "/export", produces = "text/csv")
public ResponseEntity<StreamingResponseBody> export() {
StreamingResponseBody body = out -> {
var writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));
writer.write("id,customer,total\n");
// Stream from the database too, or findAll() loads everything anyway.
try (Stream<Order> rows = repo.streamAll()) { // @QueryHints fetchSize
rows.forEach(o -> {
writer.write(o.id() + "," + o.customer() + "," + o.total() + "\n");
em.detach(o); // keep the persistence context empty
});
}
writer.flush();
};
return ResponseEntity.ok()
.header(CONTENT_DISPOSITION, "attachment; filename=orders.csv")
.body(body);
}
Both halves are required. Streaming the response while findAll() still materialises every row changes nothing — the repository must stream and the entities must be detached, or the persistence context becomes the leak instead of the response buffer.
Picture it the converter walk written out as a trace, and the memory of the broken and the streaming handler side by side.
The setup: the two handlers in the code above.
The trace: converter selection for GET /orders with Accept: application/json and a List<OrderDto> return value.
return value List<OrderDto>, acceptable types [application/json]
├─ ByteArrayHttpMessageConverter canWrite(List, application/json)? ✗
├─ StringHttpMessageConverter canWrite(List, application/json)? ✗
├─ Resource converters canWrite(List, application/json)? ✗
└─ Jackson JSON converter canWrite(List, application/json)? ✓ first match wins, writes JSON
What you see: the same export, 500 MB of data, both ways.
# illustrative output
BROKEN (List) CORRECT (StreamingResponseBody)
heap during the export about 1 GB: 500 MB list + 500 MB bytes flat, tens of MB
first byte at the client after the query and serialisation within milliseconds
under concurrent exports java.lang.OutOfMemoryError: Java heap space unaffected
Why: a returned List must exist completely before the converter runs, whereas a streaming body writes each row to the socket as the cursor produces it.
Land it The converter picks by Accept header and type, and a large body must be written as it is produced, which means streaming the query and the response together.
- "The streaming export stops after exactly 30 seconds with a truncated file. What next?"
Thirty seconds is the async request timeout,
spring.mvc.async.request-timeout, whose default depends on the container and is 30 seconds on Tomcat. AStreamingResponseBodyruns as an async request, and when the timeout fires the container completes the response, which truncates the stream mid-write.Set the timeout above the longest export, or per handler by returning a
WebAsyncTaskwith its own timeout. Then check the layers in front: a load balancer or ingress idle timeout of 60 seconds, which truncates the same way, and Tomcat'sserver.tomcat.connection-timeout.A truncated CSV is the worst outcome because it looks complete, so I also write a trailer line or a content-length when known, and the client checks it.
the truncated downloadruns offline# illustrative output t=0s GET /export 200, chunked, rows streaming t=30s async request timeout fires, container completes the response client received 4,812,331 bytes; the last line is cut mid-row: "8842,Acme Co,12" the file opens fine in a spreadsheet and is silently incomplete ✗- "How do you keep the JDBC cursor open across the async boundary without open-in-view?"
The callback runs on a different thread than the controller, so a transaction or entity manager opened in the controller is not there.
Inside the callback I open the scope explicitly: a
TransactionTemplatewithreadOnlywrapping the whole write loop, and inside it the repository's streaming method,Stream<Row> streamAll()annotated@QueryHints(@QueryHint(name = HINT_FETCH_SIZE, value = "1000")), in a try-with-resources so the cursor closes.For PostgreSQL the fetch size only takes effect inside a transaction with autocommit off, which the template guarantees. For JPA entities I call
entityManager.detachevery few thousand rows or use a projection orJdbcClientinstead, because the persistence context otherwise accumulates every row it has seen.- "What does the converter lookup cost per request, and how do you make a JSON endpoint pick a custom converter?"
The lookup walks the converter list, typically eight to ten entries, calling
canWriteon each until one matches, which is a few type checks and negligible.Ordering matters: converters are tried in registration order, and the first that can write the type for an acceptable media type wins.
To make a custom converter win for JSON, register it before the Jackson one by overriding
WebMvcConfigurer.extendMessageConvertersand inserting at index 0, or scope it to a distinct media type so the choice is made byAcceptrather than order.Boot's
HttpMessageConvertersbean is the assembly point, and its ordering of custom converters first is why a bean of typeHttpMessageConverterdeclared in the application takes precedence.- "How does this look on WebFlux, and what about back-pressure to a slow client?"
The handler returns
Flux<DataBuffer>orFlux<String>withproduces = "text/csv", fed by a reactive repository stream or by wrapping a blocking cursor withFlux.fromStreamonboundedElastic.Reactor Netty writes each buffer as it is emitted and requests more only when the socket's write buffer drains, so a slow client slows the producer instead of filling memory; that is the back-pressure MVC does not have, where the servlet
OutputStreamblocks the writing thread instead.Both work; the difference is that MVC holds a thread per slow download, which with virtual threads is cheap, whereas WebFlux holds no thread. Either way the query must stream, because the database cursor is the part that materialises rows.
Q54 · Design. "Design a file upload endpoint that accepts files up to 2 GB, virus-scans them, and stores them in object storage, on Boot, without taking the service down."
Reveal answer
Strong answer Large bodies must never sit in heap, and the upload thread must not be held for minutes.
- Requirements and principle: large bodies must never sit in heap, the upload thread must not be held for minutes, scanning must be asynchronous, and the client must get a handle immediately. Design: do not proxy the bytes through the service at all.
- Step 1, ask for a slot: The client calls
POST /uploadswith the file's name, size, and content type; the service validates them, creates anuploadrow in statePENDING, and returns a pre-signed PUT URL for S3-compatible object storage, valid for 15 minutes and constrained to the declared size. - Step 2, upload and scan: The client uploads directly to storage. Storage emits an object-created event to a queue; a Boot consumer downloads the object to a scanning sidecar or calls the scanner with the object's URL, updates the row to
CLEANorREJECTED, and publishes a domain event. - Step 3, poll: A
GET /uploads/{id}returns the state. - If the bytes must pass through the service: If the product requires the bytes to pass through the service, then
spring.servlet.multipart.max-file-size=2GBandmax-request-sizego up, the multipart resolver spools to disk abovefile-size-threshold, and the controller reads theMultipartFileas anInputStreamand streams it to storage with a multipart upload; that path holds a Tomcat thread for the whole transfer, so virtual threads or a dedicated pod pool are needed and aserver.tomcat.connection-timeoutthat tolerates slow clients. - Trade-offs and what I would not do: Trade-offs: pre-signed URLs put a small integration burden on clients and require the storage to be reachable from them. What I would not do: accept the file into a
byte[], scan synchronously in the request, or store files on the pod's disk.
Picture it who talks to whom in the pre-signed flow, the state the upload row passes through, and what a client sees at each moment.
The setup: the service hands out a pre-signed PUT URL bound to the declared size and type.
@PostMapping("/uploads")
UploadTicket create(@Valid @RequestBody UploadRequest req) {
var put = PutObjectRequest.builder().bucket(bucket).key("incoming/" + id)
.contentLength(req.size()).contentType(req.contentType()).build();
var signed = presigner.presignPutObject(r -> r.signatureDuration(Duration.ofMinutes(15)).putObjectRequest(put));
uploads.save(new Upload(id, UploadState.PENDING));
return new UploadTicket(id, signed.url().toString());
}
The trace: the 2 GB never touches the service.
client ──► POST /uploads {name,size,type} service validates, row PENDING, returns pre-signed URL ✓
client ──► PUT <signed url> (2 GB) straight to object storage; the service is idle ✓
storage ──► object-created event ──► queue ──► Boot consumer
consumer ──► scanner row becomes CLEAN or REJECTED
client ──► GET /uploads/{id} {"state":"CLEAN"}
What you see: the row and what the client reads, over time.
# illustrative output
t upload.state client sees
0 s PENDING 201 + signed URL
40 s PENDING PUT in progress; no request reaches the service
41 s PENDING storage answers 200, event queued
45 s CLEAN GET /uploads/{id} -> CLEAN
Why: pre-signing moves the heavy transfer to storage and leaves the service with two tiny requests.
Land it The best upload endpoint moves no bytes through the service; if it must, stream to storage on a thread you can afford to lose for minutes.
- "Requirement change: clients are on a private network with no route to object storage. What changes?"
The bytes now must pass through the service, so the streaming path becomes the main path and it has to be built to hold connections for minutes.
I would give uploads their own deployment with its own Tomcat settings:
spring.servlet.multipart.enabled=falseso nothing is spooled, the controller readsHttpServletRequest.getInputStream()directly and pipes it into the storage SDK's multipart upload in 16 megabyte parts, virtual threads on so a thousand slow uploads do not exhaust a pool, andserver.tomcat.connection-timeoutand the ingress idle timeout raised for that route only.A size cap is enforced by counting bytes as they stream and aborting at 2 gigabytes plus a margin. Scanning stays asynchronous from the object-created event. The dedicated deployment is the point: an upload storm must not touch the API pods.
- "What would you cut with one week?"
I would cut the event-driven scanner pipeline and the state machine, and ship the pre-signed URL flow with a synchronous scan triggered by a client-side
POST /uploads/{id}/completecall that scans and marks the row in one request, with a 60-second budget and a 202 plus polling for anything larger. I would keep the pre-signed URL, because it is the decision that keeps bytes out of the service, and the size constraint on the signed URL, because it is the only limit the service can enforce on a direct upload. The queue and the state machine are the second week's work once the first version shows how long scans really take.- "How do you enforce the 2 GB limit on a direct-to-storage upload the service never sees?"
Through the signature. An S3-style pre-signed POST policy can include a
content-length-rangecondition, so storage rejects anything larger before it is written.A pre-signed PUT cannot carry that condition on most providers, so for PUT I sign with the declared
Content-Lengthas part of the signed headers, which makes the upload fail if the client sends a different length.As defence in depth, the object-created event carries the size, and the consumer rejects and deletes anything over the limit before scanning. Bucket lifecycle rules delete objects in the upload prefix after a day, so an abandoned or rejected upload does not cost storage forever.
- "What are the Tomcat and Boot settings that bite on large uploads when bytes do pass through?"
spring.servlet.multipart.max-file-sizeandmax-request-size, default 1 megabyte and 10 megabytes, which produce aMaxUploadSizeExceededExceptionmapped to 413 unless raised.server.tomcat.max-swallow-size, default 2 megabytes, which is how much of a rejected request body Tomcat will read before closing the connection; if a 2 gigabyte upload is rejected early and this is small, the client sees a connection reset instead of the 413.server.tomcat.max-http-form-post-sizefor form bodies.The multipart
locationtemp directory, which must have space for concurrent spools and is often the container's tiny writable layer. And the ingress body size limit, for example nginx'sproxy-body-size, which returns its own 413 before the service is involved.what the client sees with a small swallow sizeruns offline# illustrative output max-file-size exceeded early, max-swallow-size too small (2 MB default, upload is 2 GB): curl: connection reset by peer ✗ the 413 never reaches the client max-swallow-size large enough, or the request fits: HTTP/1.1 413 (MaxUploadSizeExceededException) ✓
Q55. "RestTemplate, RestClient, WebClient, and @HttpExchange interfaces: which do you use in 2026 and how do you set timeouts correctly on each?"
Reveal answer
Strong answer Pick the client, then say where the timeouts live.
- RestTemplate:
RestTemplateis in maintenance mode and should not appear in new code. - RestClient:
RestClient, introduced in Spring 6.1, is the synchronous client with a fluent API, works on platform and virtual threads, and is the default choice for a blocking Boot service; Boot auto-configures aRestClient.Builderthat already carries observation, so every call gets metrics and trace propagation. - WebClient:
WebClientis the reactive client for WebFlux applications, or for a blocking application that genuinely needs streaming or thousands of concurrent outbound calls without virtual threads. @HttpExchange:@HttpExchangedeclarative interfaces sit on top of either: you declare an interface with@GetExchange("/prices/{sku}"), and anHttpServiceProxyFactorygenerates the implementation; Boot 4 and Spring Framework 7 make registration one annotation,@ImportHttpServices, with per-group client configuration.- Timeouts: Timeouts live on the underlying request factory, not on the fluent API: for
RestClientbuild it from aClientHttpRequestFactorySettings(Boot 3.4 and later) withconnectTimeoutandreadTimeout, or in properties withspring.http.client.connect-timeoutandread-timeout; the factory can be the JDKHttpClient, Apache HttpComponents 5 with pooling, or Jetty. - WebClient timeouts: For
WebClientuse Reactor Netty'sHttpClient.responseTimeoutand the connect option. No client has a sane default: the JDK client waits forever on read. - What a senior answer states: A senior answer states that every outbound call needs a connect timeout of about 1 second, a read timeout matched to the dependency's p99 plus margin, and a bounded connection pool.
// ❌ TRAP: the default is NO timeout on either connect or read. A hung downstream
// then holds your request thread until the client gives up, which is never.
// This is the single most common cause of a service dying because of a
// dependency it only calls occasionally.
@Bean
RestClient paymentClient(RestClient.Builder builder, PaymentProperties props) {
var factory = new SimpleClientHttpRequestFactory();
// ✅ FIX: both timeouts on the request factory
factory.setConnectTimeout(Duration.ofSeconds(2)); // TCP handshake
factory.setReadTimeout(Duration.ofSeconds(5)); // waiting for bytes
return builder
.baseUrl(props.gatewayUrl())
.requestFactory(factory)
.defaultHeader("X-Correlation-Id", MDC.get("correlationId"))
.defaultStatusHandler(HttpStatusCode::is5xxServerError,
(req, res) -> { throw new GatewayUnavailable(res.getStatusCode()); })
.build(); // Result: a call that waits more than 5 s fails with ResourceAccessException
}
// Declarative alternative — an interface, implemented for you.
public interface PaymentApi {
@PostExchange("/charges")
ChargeResponse charge(@RequestBody ChargeRequest r);
}
@Bean PaymentApi paymentApi(RestClient client) {
return HttpServiceProxyFactory
.builderFor(RestClientAdapter.create(client))
.build()
.createClient(PaymentApi.class);
}
As of 2026 the choice is simple: RestClient for synchronous calls, WebClient only when you are genuinely reactive, and RestTemplate for existing code you are not rewriting. What matters far more than which you pick is that both timeouts are set, on every client, always.
Picture it one slow partner call sent through each client, showing which ones give up.
The setup: a partner endpoint GET /prices/A1 that answers after 60 seconds, and a connect timeout of 2 seconds and read timeout of 5 seconds where configured.
What you see: the outcome per client and configuration. The rows are code lines.
| Code | Outcome |
|---|---|
| Builder from Boot with the request factory above | Throws ResourceAccessException after 5 s |
RestClient.create() | Blocks until the partner answers, 60 s; no read timeout, no metrics, no trace span |
WebClient with Reactor Netty responseTimeout(Duration.ofSeconds(5)) | The Mono errors after 5 s with WebClientRequestException caused by a read timeout |
WebClient with no responseTimeout | Waits for the partner: the default is none |
Why: timeouts are properties of the request factory or the Netty client, not of the fluent API, so a client built without them has none.
What you see in a thread dump: a service whose client has no timeout, during the partner slowdown.
# illustrative output
"http-nio-8080-exec-41" RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method) ✗ waiting for the partner, no end
at org.springframework.web.client.RestClient ...
Land it RestClient by default, WebClient for reactive, declarative interfaces on top, and timeouts configured on the request factory or nothing protects you.
- "What does the auto-configured
RestClient.Builderalready contain, and what happens if you callRestClient.create()instead?" Boot's builder carries the message converters from the context, the
ClientHttpRequestFactorybuilt fromspring.http.client.*settings including timeouts and redirects, the observation convention so every call produceshttp.client.requestsmetrics and a trace span, and anyRestClientCustomizerbeans, which is where a platform starter adds authentication or default headers.The builder is prototype-scoped, so each injection gets a fresh copy to customise.
RestClient.create()bypasses all of it: no metrics, no trace propagation, the JDK's default factory with no read timeout, and none of the customisers, so a call through it is invisible in dashboards and can hang forever.That is the version I look for in code review when a dependency has no timeline in the trace.
- "How do you set different timeouts for two clients in one service?"
Two ways. Programmatically, build each client's factory explicitly:
ClientHttpRequestFactoryBuilder.detect().build(ClientHttpRequestFactorySettings.defaults().withConnectTimeout(Duration.ofSeconds(1)).withReadTimeout(Duration.ofSeconds(3)))and pass it to that client's builder withrequestFactory(...).Declaratively, with Spring Framework 7 and Boot 4's
@ImportHttpServices(group = "partner", types = PartnerApi.class)and properties underspring.http.client.service.group.partner.connect-timeoutandread-timeout, each group gets its own factory.The second is what I would use in new code because the timeouts live in configuration next to the base URL and can differ per environment.
Either way the check is a test with a stub server that sleeps longer than the read timeout and asserts the exception type.
- "When is WebClient in a blocking MVC service still the right call, and what does
.block()cost?" When the outbound pattern is genuinely streaming, such as consuming a server-sent event stream or relaying a large body chunk by chunk with back-pressure, or when a library only offers a WebClient integration.
Calling
.block()on aMonoinside an MVC handler parks the request thread until the response arrives, which is the same as a synchronous call and fine on a platform or virtual thread, but it must never be done on a Reactor thread and it adds Reactor's scheduling overhead for nothing.If the only reason is "we wanted async",
RestClienton a virtual thread is simpler and produces the same metrics. Both clients need the same discipline:responseTimeouton Reactor Netty'sHttpClientfor WebClient, because the default is none.- "How does connection pooling work under each client, and what pool settings matter?"
The JDK
HttpClientkeeps a small keep-alive pool with limited configuration.Apache HttpComponents 5, which Boot prefers when present, has a
PoolingHttpClientConnectionManagerwithmaxTotal, default 25, anddefaultMaxPerRoute, default 5, which is the number that bites: five concurrent calls to one host, and the sixth waits for a connection with its own timeout, which appears as latency with no error.I raise
defaultMaxPerRouteto match the bulkhead for that dependency and set the pool'sconnectionRequestTimeoutso waiting fails fast. Reactor Netty'sConnectionProviderhasmaxConnections, default 500, andpendingAcquireTimeout, 45 seconds by default, which is far too long and I set to a second or two.All three expose metrics if you ask: Apache via Micrometer's binder, Reactor Netty via
metrics(true).
Q56 · Scenario. "A partner API started responding slowly. Within two minutes our service stopped serving even endpoints that never call the partner. Explain the chain and the fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a dependency's latency became a total outage, including unrelated endpoints. That is the classic shared-resource cascade: the slow calls consumed a resource every request needs.
- Evidence:
tomcat.threads.busyat max; a thread dump showing most threads inSocketInputStream.readinside the partner client; the partner's call timer showing p99 at 30 seconds or more; possiblyhikaricp.connections.pendingrising if the partner call happens inside a transaction. - Cause chain: the partner client had no read timeout, or a long one; each request to the partner-calling endpoint held a Tomcat thread for tens of seconds; at 200 held threads, no thread was free for any endpoint; if the call was inside
@Transactional, it also held a connection, so the pool emptied too. - Fix, immediately: restart or scale to get threads back, and short-circuit the partner call with a feature flag if one exists. Properly: set connect and read timeouts on the client at about the partner's p99 plus margin, say 2 seconds; wrap it in a Resilience4j bulkhead of, say, 20 concurrent calls so the partner can never take more than 10 percent of threads; add a circuit breaker so a failing partner is skipped for 30 seconds; and never call an external system inside a database transaction.
- Prevention: a dependency inventory listing timeout and bulkhead for every outbound client, enforced by a shared
RestClientcustomiser that refuses to build a client without them, and a chaos test that adds 30 seconds of latency to one dependency in staging.
Picture it the chain from one slow partner to a dead service, in numbers and a thread dump, and the same minute after the fix.
The setup: one endpoint calls the partner inside a transaction; the client has no read timeout.
@Transactional
public Quote quote(String sku) {
var cart = carts.load(); // holds a Hikari connection from here on
return partnerClient.price(sku); // ❌ TRAP: slow external call inside the transaction, no read timeout
}
@Bulkhead(name = "partner") // ✅ FIX: at most 20 concurrent partner calls
@CircuitBreaker(name = "partner") // ✅ FIX: skip a failing partner for 30 s
public Quote quote(String sku) { return partnerClient.price(sku); } // call made outside any transaction, 2 s timeouts
The trace: 200 workers, all busy.
200 Tomcat threads
├─ 150 × GET /quotes ──► partnerClient.price() ✗ blocked in SocketInputStream.read, partner at 30 s
├─ 50 × GET /quotes ──► waiting on Hikari ✗ connection held by the others
└─ GET /health, GET /orders (never call the partner) ✗ no free thread: queue, then refused
What you see: the metrics over the two minutes.
# illustrative output
time tomcat.threads.busy hikari pending partner call p99
t=0 12 / 200 0 200 ms
t=60s 200 / 200 14 30 s
t=120s 200 / 200 60 30 s <- unrelated endpoints time out too
What you see now: the same slowdown after the fix.
# illustrative output
time tomcat.threads.busy hikari pending partner call p99
t=60s 32 / 200 0 2 s (timeout)
BulkheadFullException for the 21st concurrent quote
CallNotPermittedException while the breaker is open (30 s)
/actuator/circuitbreakers partner: OPEN
Land it Without timeouts and a bulkhead, one slow dependency owns your thread pool, and a thread pool is shared by every endpoint you have.
- "You added timeouts and a bulkhead. During the next partner slowdown, the partner endpoint is fine but the checkout endpoint still degrades. What next?"
Then the two endpoints share something besides threads.
The likely candidate is the database connection pool: the partner-calling endpoint, now failing fast at two seconds, still holds a connection for those two seconds if the call is inside a transaction, and with 20 concurrent partner calls that is 20 of 25 connections.
I would confirm with
hikaricp.connections.pendingrising during the slowdown and a thread dump showing checkout threads inHikariPool.getConnection. The fix is to move the partner call outside the transaction: fetch what is needed, commit, call the partner, then open a new transaction to record the result.The general check is to list every shared resource, threads, connections, the HTTP client pool per route, caches with locks, and confirm the bulkhead covers each one, not only the thread pool.
pool during the second slowdownruns offline# illustrative output hikaricp.connections.active 25 / 25 # 20 partner calls hold a connection for 2 s each hikaricp.connections.pending 11 "http-nio-8080-exec-9" WAITING at com.zaxxer.hikari.pool.HikariPool.getConnection(...) <- a checkout thread- "How do you choose the bulkhead size and the breaker thresholds, with numbers?"
The bulkhead is the maximum concurrent calls to the partner, and I size it from Little's law on the partner's healthy behaviour: at 50 calls per second and a p99 of 200 milliseconds, healthy concurrency is 10, so a bulkhead of 20 allows a doubling and caps the damage at 20 threads out of 200.
The breaker: Resilience4j's
slidingWindowSize=50calls,failureRateThreshold=50percent,slowCallDurationThreshold=1swithslowCallRateThreshold=50so slowness trips it as well as errors,waitDurationInOpenState=30s, andpermittedNumberOfCallsInHalfOpenState=5. The read timeout of 2 seconds sits above the slow-call threshold so the breaker sees slow calls before the timeout fires. These go inresilience4j.circuitbreaker.instances.partner.*and are visible on/actuator/circuitbreakers.- "What does the chaos test look like, and how do you run it safely?"
In staging, a fault injection at the network layer rather than in code: a service-mesh fault rule or a Toxiproxy instance between the service and the partner, adding 30 seconds of latency to 100 percent of calls for five minutes.
During the test I watch the unrelated endpoints' p99 and error rate,
tomcat.threads.busy, and the breaker state, and the pass criterion is that unrelated endpoints stay within 10 percent of baseline and the partner endpoint fails fast within the read timeout.Safety comes from running it in staging with production-like load from a generator, and from a kill switch that removes the fault rule in one command.
The value is that the numbers from the previous answer become measured rather than argued, and the test is rerun after every change to the client configuration.
- "How do you make the shared customiser refuse to build a client without a timeout?"
A
RestClientCustomizercannot see whether a timeout is set on a factory, so the enforcement goes one level down. Three layers:- The platform starter provides its own
ClientHttpRequestFactoryBuilderbean that applies default timeouts of 1 second connect and 5 seconds read unless overridden. - A
BeanPostProcessorinspects everyRestClient.BuilderandWebClient.Builderbean at creation, checks that the factory or the Netty client has a non-zero read timeout, and throws aBeanCreationExceptionwith a clear message if not. - For clients built by hand with
RestClient.create(), an ArchUnit rule forbids the call outside the platform package.
Between the default, the check, and the rule, a client without a timeout cannot reach production by accident.
- The platform starter provides its own
Q57. "In WebFlux, what actually happens when someone calls a blocking JDBC repository inside a controller, and how would you detect it?"
Reveal answer
Strong answer Event loops must never block, and one blocking call breaks that.
- The model: WebFlux on Reactor Netty runs requests on a small number of event-loop threads, typically one per core, named
reactor-http-nio-N. Each loop serves many connections by never blocking: it handles a readiness event, runs the non-blocking pipeline, and moves on. - The trap: A blocking JDBC call inside that pipeline parks the loop thread for the duration of the query. Every other connection assigned to that loop stalls, so with 4 cores and 4 concurrent slow queries the whole server stops responding, even though CPU is idle.
- Why it ships: Throughput under light load looks fine, which is why it ships.
- Detection: Detection: BlockHound, a Java agent that instruments blocking JDK calls and throws when one happens on a thread marked non-blocking, run in the integration tests; in production, thread dumps showing
reactor-http-niothreads insidesocketRead, and a latency profile where p50 is fine and p99 collapses under modest concurrency. - Fix: Fix: either use a reactive driver such as R2DBC with Spring Data R2DBC, or isolate the blocking call with
Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic()), which moves it to a separate bounded thread pool, accepting that you now have a thread-per-blocking-call design hidden inside a reactive one. - Honest alternative: If most of the application is blocking, the honest answer is to use WebMVC with virtual threads instead.
Picture it four event loops, four blocked queries, and the thread dump, BlockHound error and thread names before and after.
The setup: a WebFlux controller that calls a blocking repository.
@GetMapping("/orders/{id}")
Mono<OrderDto> get(@PathVariable long id) {
return Mono.just(repo.findById(id).orElseThrow()); // ❌ TRAP: JDBC runs on reactor-http-nio-N, the event loop
}
@GetMapping("/orders/{id}")
Mono<OrderDto> get(@PathVariable long id) {
return Mono.fromCallable(() -> repo.findById(id).orElseThrow())
.subscribeOn(Schedulers.boundedElastic()); // ✅ FIX: blocking call on a separate bounded pool
}
The trace: 4 cores, 4 loops, 4 concurrent 2-second queries.
reactor-http-nio-1 ──► repo.findById(...) ✗ parked in JDBC for 2 s; every connection on this loop frozen
reactor-http-nio-2 ──► repo.findById(...) ✗ same
reactor-http-nio-3 ──► repo.findById(...) ✗ same
reactor-http-nio-4 ──► repo.findById(...) ✗ same
5th request ──► lands on a blocked loop, waits in the socket buffer
What you see: a thread dump during load, and the BlockHound failure in the integration tests.
# illustrative output
"reactor-http-nio-2" RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at org.postgresql.core.VisibleBufferedInputStream.read(...)
reactor.blockhound.BlockingOperationError: Blocking call! java.net.SocketInputStream#socketRead0
latency: p50 fine, p99 collapses once 4 slow queries overlap; CPU idle
What you see now: the same load after the fix.
# illustrative output
"boundedElastic-3" RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method) <- blocking happens here, not on the loop
"reactor-http-nio-2" RUNNABLE (epoll wait) <- loop is free
BlockHound: no error
Land it One blocking call on an event loop stalls every request on that loop, so WebFlux is all-or-nothing, and BlockHound is how you find the "nothing".
- "What does
boundedElasticactually bound, and what happens when it is full?" Schedulers.boundedElastic()is a pool capped at ten times the CPU count threads by default, so 40 on a 4-core box, with a queue of 100,000 deferred tasks per thread, and idle threads expire after 60 seconds.When all threads are busy, new tasks queue, and if the queue is full the subscription fails with
RejectedExecutionException. So it protects the event loop but it does not protect the downstream: 40 threads blocked on a slow database is 40 connections demanded.The queue is also the danger, because a hundred thousand queued database calls is a memory and latency bomb with no visible error.
I set a dedicated
Schedulers.newBoundedElastic(20, 500, "jdbc")per blocking dependency so the cap matches the connection pool and the queue is small enough to fail fast.- "How do you run BlockHound, and what does it cost in production?"
BlockHound is installed with
BlockHound.install()at test startup, typically in a JUnit extension or a static initialiser in the test base class, and needs-XX:+AllowRedefinitionToAddDeleteMethodson JDK 13 and later because it instruments JDK classes.It throws
BlockingOperationErrorwhenever a blocking JDK method is called on a thread that Reactor marks as non-blocking, which the Netty event loops and parallel scheduler threads are.I run it in the integration tests only; in production the instrumentation of core JDK methods adds overhead on every blocking call and the error would crash a request rather than help.
The production signal is instead the thread dump and a Micrometer gauge on
reactor.netty.eventloop.pending.tasks, which grows when loops are stalled.BlockHound failureruns offline# illustrative output reactor.blockhound.BlockingOperationError: Blocking call! java.net.SocketInputStream#socketRead0 at reactor.blockhound.BlockHound$Builder.lambda$install$8(...) at com.example.OrderRepository.findById(...) <- the offending caller, in the test run (thread: reactor-http-nio-1)- "Why is 'a few concurrent slow queries stall the whole server' true with, say, 4 cores and 8 loops?"
Reactor Netty creates one event loop per core by default, and each connection is assigned to one loop for its lifetime. A blocked loop cannot process any event for any of its connections: no reads, no writes, no timeouts.
With 4 loops, 4 concurrent blocking calls of 2 seconds each freeze every connection on the server for 2 seconds; the fifth request, if it lands on one of those loops, waits in the socket buffer and then experiences the same stall.
CPU shows idle because the threads are waiting, not computing. This is why the symptom is a cliff rather than a slope: below 4 concurrent slow calls, latency is fine; at 4, everything stops. Increasing loops only raises the cliff a little.
- "When would you choose R2DBC over reverting to MVC with virtual threads?"
When the rest of the service is genuinely reactive and benefits from it, meaning it streams, fans out to many non-blocking calls per request, or must hold tens of thousands of connections, and the team already thinks in Reactor. R2DBC then keeps the whole pipeline non-blocking.
The costs I weigh: no JPA, so no lazy loading, dirty checking, or second-level cache, and the Spring Data R2DBC repository model is simpler than JPA's; transaction handling through
TransactionalOperatoror reactive@Transactional; and driver maturity, which is good for PostgreSQL and MySQL and thinner elsewhere.For a typical CRUD-heavy service with JPA already in place, MVC with virtual threads gets the concurrency benefit for one property change, and that is the honest default in 2026.
Q58 · Scenario. "A team rewrote a service on WebFlux for 'performance'. Benchmarks show the same throughput as the old MVC version and p99 got 3x worse under load. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: no throughput gain and a worse tail. The gain WebFlux offers is in concurrency with many slow I/O waits, not in raw throughput; a worse tail says the event loops are being blocked.
- Evidence: thread dumps during load showing event-loop threads inside JDBC, a blocking HTTP client, a file read, or a
Mono.block(); BlockHound in a test run; Micrometer showingreactor.nettypending tasks growing; and the dependency list still containingspring-boot-starter-data-jpa. - Likely causes, ranked: JPA or JDBC still used behind reactive signatures via
Mono.fromCallableon the default scheduler; a synchronous library, such as a cloud SDK or a logging appender doing network I/O, called on the loop;.block()somewhere in a service layer; or CPU-heavy JSON serialisation of large bodies on the loop, which reactive does nothing for. - Fix: if the database is relational and stays JDBC, revert to MVC on Java 21 with virtual threads, which gives the concurrency benefit without the paradigm cost; if staying reactive, move to R2DBC, move any unavoidable blocking calls to
boundedElasticwith a cap, and run BlockHound in CI. - Prevention: before adopting a reactive stack, a written check of every dependency for a non-blocking driver, and a benchmark that measures the tail at the target concurrency rather than the mean.
Picture it one endpoint written five ways, with the outcome of each under the same load.
The setup: an endpoint that reads one row through JDBC, driven at 500 concurrent requests with a 100 ms query.
| Code line | Outcome |
|---|---|
WebFlux: Mono.just(repo.findById(id)) | Runs on the event loop; 4 slow queries stop the server; p99 collapses |
WebFlux: Mono.fromCallable(() -> repo.findById(id)), no subscribeOn | Still runs on the loop thread: same collapse |
WebFlux: same with .subscribeOn(Schedulers.boundedElastic()) | Loop is free, but two thread hops per request; throughput about MVC's |
MVC with spring.threads.virtual.enabled=true: repo.findById(id) | Direct call, no hops; concurrency benefit without the paradigm cost |
WebFlux with R2DBC: repo.findById(id) returning a Mono | Non-blocking all the way; no extra pool |
What you see: the benchmark the team ran, and what a thread dump during it shows.
# illustrative output
MVC (200 threads) WebFlux + JDBC on the loop
throughput 4,100 req/s 4,000 req/s <- no gain
p99 120 ms 360 ms <- 3x worse
thread dump http-nio-8080-exec-* reactor-http-nio-* inside JDBC ✗
Why: the gain from WebFlux comes from many slow waits that cost no thread, and a blocking call on the loop turns each wait back into a stalled loop.
The fix: either keep JDBC and return to MVC, or go non-blocking all the way and guard it in CI.
// Option 1: MVC on Java 21, same repository code, no Mono
// spring.threads.virtual.enabled=true
// Option 2: stay reactive
// spring-boot-starter-data-r2dbc, any unavoidable blocking call on a capped boundedElastic scheduler
// BlockHound.install() in the integration tests
Land it Reactive does not make code faster; it makes waiting cheaper, and only if nothing in the path actually waits on a thread.
- "They moved every blocking call to
boundedElasticand the tail improved but throughput is now lower than MVC. Why, and what next?" Because the service is now doing thread-per-blocking-call with extra hops: each request crosses from an event loop to a bounded elastic thread and back, which costs two context switches and Reactor's scheduling, on top of the same JDBC work MVC did directly on its thread.
The reactive machinery adds overhead and removes none of the waiting.
Next, I would measure where time goes with a profiler: if it is in Reactor operators and scheduling, the answer is to stop pretending and move to MVC with virtual threads, which does the same thread-per-wait model without the hops.
If the team insists on staying reactive, then the database access must become non-blocking with R2DBC so the elastic pool disappears; anything in between is the worst of both.
- "What benchmark would have told them the truth before the rewrite?"
A benchmark at the target concurrency measuring the tail, not the mean. Run the existing MVC service at the expected concurrent-request count, say 500 in flight, with the real dependency latencies, and look at p99 and thread usage.
If p99 is fine and threads are below the ceiling, there is no concurrency problem for WebFlux to solve. If threads are the ceiling, try
spring.threads.virtual.enabled=trueon the same code, which takes an afternoon, and rerun.Only if that is insufficient, which happens for streaming and massive fan-out, is a reactive rewrite justified. The rewrite here was justified by a throughput number from a benchmark with no slow I/O, which measures CPU and JSON, where neither stack has an advantage.
- "What does the Reactor Netty metric set look like when loops are blocked, so you can tell from a dashboard?"
With
metrics(true)on the server and Micrometer, the useful ones are:reactor.netty.eventloop.pending.tasks, the count of tasks queued on each loop, which climbs when a loop is stalled.reactor.netty.http.server.data.received.timeandresponse.time, whose percentiles separate before it does.reactor.netty.connection.provider.pending.connectionson the client side.
Combined with
jvm.threads.statesshowingreactor-http-niothreads inBLOCKEDorWAITINGrather thanRUNNABLEin the thread dump, the picture is unambiguous.If I have Reactor's
Hooks.enableAutomaticContextPropagation()and tracing on, the span for the blocking call shows on the event-loop thread name, which is the smoking gun in a trace.- "Is there anything in WebFlux that makes CPU-bound work worse, or is that neutral?"
It is worse if done on the loop. Serialising a 5 megabyte JSON response with Jackson takes tens of milliseconds of CPU, and on an event loop that is tens of milliseconds during which every connection on that loop waits, exactly like a blocking call.
MVC spends the same CPU but on a thread dedicated to that request, so other requests proceed on other threads.
The reactive answer is to move heavy CPU work to
Schedulers.parallel(), which is another hop, or to stream the body with aFluxof chunks so no single task holds the loop long.That is real engineering work that MVC never asked for, which is one more reason the reactive stack only pays off when the workload is dominated by waiting.
Q59 · Design. "Design a streaming endpoint that relays tokens from an LLM provider to a browser as they arrive, on Boot, for 2,000 concurrent chats per instance."
Reveal answer
Strong answer Streaming is a concurrency problem: 2,000 long-lived connections, each with a slow trickle.
- Requirements: each chat is a long-lived connection, typically 5 to 60 seconds, with a slow trickle of small events; 2,000 open at once; the client must see tokens with low latency; provider failures must end the stream cleanly.
- Design: server-sent events, since the traffic is one-way and SSE reconnects natively in browsers. Two viable stacks.
- MVC option: On WebMVC with
spring.threads.virtual.enabled=true, the controller returns anSseEmitter; the handler opens the provider's streaming HTTP response withRestClienton a virtual thread, reads it line by line, and callsemitter.send(event)per token; 2,000 virtual threads waiting on sockets cost a few megabytes, and Tomcat's connection limit is raised to cover 2,000 open responses. - WebFlux option: On WebFlux, the controller returns a
Flux<ServerSentEvent<String>>fed byWebClient'sbodyToFluxagainst the provider, with backpressure end to end and no threads waiting at all. I would pick MVC with virtual threads for a mostly-blocking codebase and WebFlux for a service built only for this. - In both: In both, set the async request timeout (
spring.mvc.async.request-timeout) above the longest expected generation, send a heartbeat comment every 15 seconds so proxies do not close idle connections, handleonTimeoutandonCompletionto cancel the upstream call, and put a per-user concurrency cap in a filter. - Observability and trade-offs: Observability: a gauge of open streams and a timer from first byte to last. Trade-offs: SSE is unidirectional; use WebSocket only if the client must also stream.
- What I would not do: What I would not do: buffer the whole completion and return JSON, or use platform threads with a 200-thread ceiling for 2,000 streams. Module 06 of this course covers the provider side of the same stream.
Picture it what travels on the wire, the code that relays and cancels, and a table from symptom to cause.
The setup: an SseEmitter controller on virtual threads that relays provider tokens and cancels upstream when the client leaves.
@GetMapping(value = "/chat/{id}/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
SseEmitter stream(@PathVariable String id) {
var emitter = new SseEmitter(Duration.ofMinutes(2).toMillis());
Future<?> upstream = executor.submit(() -> { // virtual-thread executor
try {
int n = 0;
for (String token : provider.tokens(id)) { // blocking read, line by line
emitter.send(SseEmitter.event().id(String.valueOf(++n)).data(token));
}
emitter.complete();
} catch (Exception e) { emitter.completeWithError(e); }
});
emitter.onCompletion(() -> upstream.cancel(true)); // ✅ FIX: tab closed, stop paying the provider
emitter.onTimeout(() -> upstream.cancel(true));
return emitter;
}
What you see: the bytes on the wire for one chat.
HTTP/1.1 200
Content-Type: text/event-stream
id: 1
data: Hel
id: 2
data: lo
: heartbeat
id: 3
data: !
The trace: one reconnect after the instance died, using the stored tokens.
browser ──► GET /chat/42/stream instance A dies after token 17
browser ──► GET /chat/42/stream Last-Event-ID: 17 ✓ automatic SSE reconnect
└─► handler reads tokens 18..N from Redis, then continues live or restarts generation
| Symptom | Root cause | Action |
|---|---|---|
| Tokens arrive in one burst at the end | A proxy buffers the response | Disable proxy buffering for this route, and flush each event |
| Stream cuts at a fixed time | Async request timeout or proxy idle timeout | Raise spring.mvc.async.request-timeout, send a heartbeat comment every 15 s |
| Provider requests keep running after tabs close | No onCompletion or onTimeout cancel | Cancel the upstream call in both callbacks |
| New chats fail near a few hundred streams | Platform threads, or max-connections or file descriptors reached | Virtual threads, raise the Tomcat limit, check ulimit -n |
Land it Streaming is a concurrency problem, not a throughput one, and either virtual threads or Flux solve it as long as nothing buffers in the middle.
- "Requirement change: the browser must also send messages mid-stream to steer the generation. What changes?"
Then the channel becomes bidirectional and SSE no longer fits; the choices are WebSocket or a pair of channels, SSE down and plain POSTs up.
I would start with the pair, because it keeps the streaming path unchanged and the upstream messages are ordinary requests that carry the chat id, and the handler for the stream reads a per-chat queue between tokens to apply steering.
That avoids WebSocket's operational costs: sticky routing or a shared broker so the message reaches the instance holding the stream, a different security model where the handshake authenticates and the frames do not, and idle-timeout handling at every proxy.
If latency of steering must be under 100 milliseconds or messages are frequent, WebSocket with
spring-boot-starter-websocketand a Redis-backed message relay across instances is the next step.- "What would you cut with three days?"
The per-user concurrency cap, the open-stream gauge, and the heartbeat would be the first things cut, in that order, though the heartbeat comes back the first time a corporate proxy drops a 40-second stream, which will be day four. I would keep
SseEmitteron virtual threads with the async timeout raised, theonTimeoutandonCompletioncallbacks that cancel the upstream provider call, and the raised Tomcat connection limit. The cancellation is the one I would refuse to cut, because without it a user closing a tab leaves a provider request running to completion, and at 2,000 streams that is real money and real capacity leaked on every abandoned chat.- "How does
SseEmitteractually work under MVC, and where does the 2,000 limit bite?" Returning an
SseEmitterstarts servlet async mode, so the request thread is released and the response stays open. Eachsendwrites an event to the response's output stream and flushes; the writing thread is whichever thread callssend, here the virtual thread reading the provider.Tomcat keeps the connection registered with its poller, and the servlet async timeout is the clock.
The limits:
server.tomcat.max-connections, default 8,192, which covers 2,000 but not with headroom for regular traffic on a busy instance; the ingress and load balancer's concurrent connection and idle limits; and file descriptors, since each open stream is a socket, so the container'sulimit -nmust exceed the sum.Memory per stream is small, a few kilobytes of buffers plus the virtual thread's stack.
- "How do you make the stream resumable if the instance dies mid-generation?"
SSE has a built-in reconnection contract: the browser reconnects automatically and sends
Last-Event-IDwith the id of the last event it received.So each token event gets a monotonically increasing id, the tokens are written to a short-lived store keyed by chat id, Redis with a five-minute expiry, as they arrive from the provider, and the handler for a reconnect with a
Last-Event-IDreplays from the store and then continues live if generation is still running on another instance, or restarts generation if it is not.The provider call itself cannot be resumed, so the store is what makes the client's experience continuous. Without this, an instance restart during a deploy cuts every active chat, which is the failure users notice most.
Q60. "Where should CORS be handled in a Boot service, and why does the answer change once Spring Security is present?"
Reveal answer
Strong answer Cross-origin resource sharing is the browser's rule that a page from one origin may call an API on another only if the API says so in response headers, and that for non-simple requests the browser first sends an OPTIONS preflight with no credentials.
Without Security, Spring MVC handles it with @CrossOrigin on controllers or a global WebMvcConfigurer.addCorsMappings, and the DispatcherServlet's CorsFilter-like processing answers preflights before the handler runs.
With Security present, the security filter chain runs before MVC, and the preflight arrives with no credentials.
An authentication filter would reject it with 401 before MVC ever adds the CORS headers; the browser then reports a CORS error that looks like a misconfiguration.
That is why Security must own CORS: register a CorsConfigurationSource bean and call http.cors(Customizer.withDefaults()), which inserts a CorsFilter early in the security chain that answers preflights and adds headers on actual responses before authentication runs.
The source should list explicit origins rather than * when credentials are allowed, since the specification forbids the wildcard with credentials.
In a deployment with an API gateway or ingress that already handles CORS, the service should not add headers a second time, because duplicated Access-Control-Allow-Origin headers are rejected by browsers.
Picture it a browser SPA POSTing to an API behind Spring Security, with the preflight that gets rejected before MVC and the same call after Security owns CORS.
The setup: the SPA at https://app.shop.example calls POST https://api.shop.example/orders with an Authorization header and a JSON body. That is not a simple request, so the browser sends a preflight first.
Make the invisible visible: the preflight the browser sends on its own, with no credentials:
OPTIONS /orders HTTP/1.1
Host: api.shop.example
Origin: https://app.shop.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization, content-type
(no Authorization header, no cookie)
The trace: where the preflight dies when Security does not know about CORS:
Browser ──► OPTIONS /orders
└─► FilterChainProxy (security chain)
├─► ... BearerTokenAuthenticationFilter no token found, request stays anonymous
├─► AuthorizationFilter anyRequest().authenticated() ✗ denied
└─► ExceptionTranslationFilter ✗ 401 written here
DispatcherServlet / CorsProcessor ✗ never reached, CORS headers never added
What you see: the server answered 401, the browser reports CORS:
# illustrative output
Access to fetch at 'https://api.shop.example/orders' from origin 'https://app.shop.example'
has been blocked by CORS policy: Response to preflight request doesn't pass access
control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Network tab: OPTIONS /orders 401 (no Access-Control-* response headers)
Why: the preflight carries no credentials by design, so any authentication rule rejects it before MVC can attach CORS headers.
The fix: let Security answer preflights first by exposing a CorsConfigurationSource and enabling http.cors():
@Bean
CorsConfigurationSource corsConfigurationSource() {
var cfg = new CorsConfiguration();
cfg.setAllowedOrigins(List.of("https://app.shop.example")); // explicit, not "*"
cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
cfg.setAllowedHeaders(List.of("Authorization", "Content-Type"));
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cfg);
return source;
}
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http.cors(Customizer.withDefaults()) // CorsFilter now runs before authentication
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.build();
}
What you see now: the same preflight, answered by CorsFilter without touching authentication:
# illustrative output
OPTIONS /orders 200
Access-Control-Allow-Origin: https://app.shop.example
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
POST /orders 201 (real request, now authenticated normally)
Land it CORS must be answered by whatever runs first, and once Security is present, that is Security.
- "How exactly does Spring Security's
CorsFilterbehave on a preflight versus an actual request?" It sits near the front of the chain, after the header writer and before authentication.
For a preflight, meaning an
OPTIONSrequest withOriginandAccess-Control-Request-Methodheaders, it consults theCorsConfigurationSourcefor the path; if the origin, method, and requested headers are allowed, it writes theAccess-Control-Allow-*headers and ends the request with 200 without calling the rest of the chain, so no authentication is attempted.If not allowed, it responds 403 "Invalid CORS request". For an actual cross-origin request it adds
Access-Control-Allow-Originand, if configured,Allow-CredentialsandExpose-Headersto the response and lets the chain continue, so authentication and authorisation apply normally.That is why the security layer is the correct owner: it answers preflights before it demands credentials.
- "What is the exact configuration for a browser SPA that sends a cookie and a custom header?"
A
CorsConfigurationSourcebean built from aUrlBasedCorsConfigurationSourceregistering aCorsConfigurationon/**withsetAllowedOrigins(List.of("https://app.shop.example")), an explicit list because credentials are involved;setAllowedMethodslistingGET, POST, PUT, PATCH, DELETE, OPTIONS;setAllowedHeaders(List.of("Authorization", "Content-Type", "X-XSRF-TOKEN"));setAllowCredentials(true);setExposedHeadersfor anything the browser script must read, such asLocation; andsetMaxAge(3600)so preflights are cached an hour. Thenhttp.cors(Customizer.withDefaults())picks up the bean by type.setAllowedOriginPatternsis for wildcarded subdomains with credentials, since*is forbidden there.- "The gateway already adds CORS headers and the browser reports 'multiple values' errors. What do you do?"
Pick one owner and remove the other. Browsers reject a response whose
Access-Control-Allow-Originhas two values, which is what happens when both the gateway and the service add it.If the gateway owns CORS, the service removes its configuration entirely and also removes
http.cors(), or configures the gateway to strip upstream CORS headers, which most gateways can do. If the service owns it, the gateway passesOPTIONSthrough untouched.I prefer the gateway when there is one, because it is the single place that knows every origin, and the service then treats CORS as not its concern.
What I would not do is keep both and rely on header order, because the failure only shows in browsers, not in any API test.
response with two ownersruns offline# illustrative output HTTP/1.1 200 Access-Control-Allow-Origin: https://app.shop.example added by the gateway Access-Control-Allow-Origin: https://app.shop.example added again by the service ✗ browser rejects the response- "Does CORS protect the API from anything, and what does it not protect against?"
It protects users of browsers from having their ambient credentials, cookies, used by a malicious page on another origin: without an allow header, the browser withholds the response from the script.
It protects nothing against non-browser clients, which ignore it entirely, so it is not access control.
It also does not stop the request from reaching the server for simple requests; a cross-origin POST with a form content type is sent and executed, and only the response is withheld, which is why CSRF protection is still needed for cookie-authenticated state changes.
And a misconfigured allow-all with credentials undoes the protection completely. So the accurate statement is that CORS is a browser-side policy for reading responses, and the server's own authentication and CSRF controls are what protect the data.
These questions test whether you know what the filter chain does on every request, where identity lives, and how it survives threads, tenants, and rotation.
Q61. "Describe what Spring Security's filter chain does on a single request to a JWT-protected endpoint, and how multiple SecurityFilterChain beans are selected."
Reveal answer
Strong answer One servlet filter, FilterChainProxy, is registered as springSecurityFilterChain.
On each request it walks its list of SecurityFilterChain beans in @Order and picks the first whose RequestMatcher matches, so a chain for /actuator/** with order 1 can permit health checks while the chain for /** at order 2 demands tokens; only one chain runs per request.
Inside the chosen chain, the filters run in a fixed order:
DisableEncodeUrlFilter: keeps session ids out of URLs.SecurityContextHolderFilter: loads any existing context.HeaderWriterFilter: writes the security headers.CorsFilterandCsrfFilter: present only if enabled.LogoutFilter.BearerTokenAuthenticationFilter: extracts the bearer token and hands it to theJwtAuthenticationProvider, which decodes and validates it with theJwtDecoderand converts claims to authorities; on success it sets aJwtAuthenticationTokenin theSecurityContextHolder.ExceptionTranslationFilter: wraps the rest and turns anAuthenticationExceptioninto the entry point's 401 and anAccessDeniedExceptioninto 403.AuthorizationFilter: evaluates theauthorizeHttpRequestsrules against the authenticated principal.
Only if that passes does the request continue to the DispatcherServlet. On the way out, the context is cleared because the policy is stateless.
Picture it one request entering FilterChainProxy, the chain that gets picked, the filters in the order they run, and the three ways the request can end.
The setup: two chain beans, selected by matcher and order:
@Bean @Order(1)
SecurityFilterChain actuator(HttpSecurity http) throws Exception {
return http.securityMatcher("/actuator/**")
.authorizeHttpRequests(a -> a.anyRequest().permitAll()).build();
}
@Bean @Order(2)
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http.securityMatcher("/**")
.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
Make the invisible visible: what FilterChainProxy holds, as a registry:
# illustrative output
[0] order 1 matcher /actuator/** filters: 9 (no BearerTokenAuthenticationFilter)
[1] order 2 matcher /** filters: 12 (includes BearerTokenAuthenticationFilter)
GET /api/orders -> [0] does not match, [1] matches -> chain [1] runs, chain [0] never sees it
GET /actuator/health -> [0] matches -> chain [1] never runs
The trace: one authenticated request and the two refusals:
GET /api/orders Authorization: Bearer eyJ...
FilterChainProxy ──► chain[1]
├─► SecurityContextHolderFilter loads empty context
├─► HeaderWriterFilter adds headers
├─► BearerTokenAuthenticationFilter decode + validate JWT ✓ sets JwtAuthenticationToken
├─► ExceptionTranslationFilter wraps the rest
├─► AuthorizationFilter authenticated() ✓
└─► DispatcherServlet ──► controller 200
no token : AuthorizationFilter throws AccessDeniedException (anonymous) ──► entry point ✗ 401
bad scope : AuthorizationFilter throws AccessDeniedException (authenticated) ──► denied handler ✗ 403
What you see: the same decision from the log when FilterChainProxy is at TRACE:
# illustrative output
Securing GET /api/orders
Invoking DisableEncodeUrlFilter (1/12)
Invoking SecurityContextHolderFilter (2/12)
Invoking BearerTokenAuthenticationFilter (7/12)
Invoking AuthorizationFilter (12/12)
Secured GET /api/orders
Land it Say "one chain chosen by matcher, authentication filter sets the context, authorization filter checks it, exception translation formats the refusals" and you have the whole model.
- "Two chains both match
/api/orders. Which runs, and how do you find out in production?" The one with the lowest
@Ordervalue, becauseFilterChainProxyiterates chains in that order and takes the first whose matcher accepts the request; there is no merging.Chains without an explicit order sort last in unspecified order, and since Spring Security 6.1 the framework logs a warning at startup when a chain with a universal matcher,
/**, is ordered before a more specific one, because the specific one can never match.To see the decision in production, set
logging.level.org.springframework.security.web.FilterChainProxy=TRACEfor one request: it logs "Securing GET /api/orders" and then each filter invoked with its position, such as "Invoking BearerTokenAuthenticationFilter (7/12)", which names the chain by its filter list.The count of filters is usually enough to tell which chain it was.
- "Where does the authenticated principal go after the request, and what changes if the policy is not stateless?"
The
SecurityContextHolderis a thread-local by default, populated by the authentication filter and cleared bySecurityContextHolderFilterin its finally block when the request ends, so the worker thread returns to the pool clean.With a stateless policy, that is the whole story: every request re-authenticates from its token.
With
IF_REQUIREDorALWAYS, theSecurityContextRepositoryisHttpSessionSecurityContextRepository, which saves the context into the HTTP session at the end of the request and loads it at the start of the next, keyed by the session cookie.Since Security 6 the save is explicit rather than automatic in some flows, which is why a custom login must call
securityContextRepository.saveContext(...), a frequent migration surprise.- "How do you insert a custom filter at a precise point in the chain, and what goes wrong with the naive way?"
http.addFilterBefore(myFilter, BearerTokenAuthenticationFilter.class),addFilterAfter, oraddFilterAtplace it relative to a known filter class; Security keeps a fixed registry of known filter positions, and unknown positions fail with an exception.The naive mistake is declaring the filter as a
@Component: Boot then registers it as a servlet filter in the servlet container as well, so it runs twice, once in the container's chain and once inside Security's, with the container invocation happening before Security and without any security context.The fix is either to not make it a bean, or to declare a
FilterRegistrationBeanfor it withsetEnabled(false)so the container registration is suppressed while the Security chain still uses the instance.- "What does
ExceptionTranslationFilterdo differently for an anonymous user versus an authenticated one?" When
AuthorizationFilterthrowsAccessDeniedException, the translation filter checks whether the current authentication is anonymous or a remember-me token.If so, it treats the denial as "not logged in" and invokes the
AuthenticationEntryPoint, producing a 401 with a challenge, or a redirect to the login page in form-login setups, so the user gets a chance to authenticate.If the user is fully authenticated, it invokes the
AccessDeniedHandler, producing 403, because more credentials would not help.That distinction is why an API without a token gets 401 while a token lacking the scope gets 403, and why the entry point and the denied handler both need the problem-detail treatment from Q50 to get consistent bodies.
Q62 · Scenario. "After enabling method security, every POST from the web front end fails with 403, but GETs work and Postman POSTs work. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: state-changing requests from a browser fail, non-browser clients succeed, reads succeed. That fingerprint is CSRF protection, not method security; enabling method security probably came with a security configuration rewrite that lost the CSRF setting.
- Evidence: the 403 body or log says "Invalid CSRF token found" or the
CsrfFilterlogs at DEBUG; the request has a session cookie but noX-XSRF-TOKENheader; Postman has no cookie so it looks like a token client to Security, or it sends a bearer token, which Security exempts from CSRF checks. - Cause:
CsrfFilterrequires a token on POST, PUT, PATCH, and DELETE whenever the chain has CSRF enabled, which is the default. The front end used to work because the old chain disabled CSRF or the front end used to read the cookie. - Fix depends on the auth model. If the front end authenticates with a session cookie, keep CSRF on and fix the client: use
CookieCsrfTokenRepository.withHttpOnlyFalse()so the SPA can read theXSRF-TOKENcookie and echo it in the header, and since Security 6, theCsrfTokenRequestAttributeHandlerto handle the deferred token. If the front end sends a bearer token in theAuthorizationheader and no cookie, the chain is stateless and CSRF should be disabled for it, since there is no ambient credential to forge. - Prevention: an integration test that performs a POST with the browser flow, and a rule that CSRF settings are decided per chain with a comment explaining the auth model.
// CAUSE: Spring Security enables CSRF protection by default. It requires a
// token on every state-changing request. Postman does not send cookies, so it
// is treated as a non-browser client and is unaffected — which is exactly why
// "it works in Postman" is the diagnostic clue, not a counter-argument.
// FIX A — a stateless API authenticated by a bearer token. CSRF does not apply,
// because the browser does not attach the credential automatically.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.securityMatcher("/api/**")
.csrf(csrf -> csrf.disable()) // safe ONLY with no cookie auth
.sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
// FIX B — a cookie-authenticated app. Keep CSRF ON and hand the token to the SPA.
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()))
.build();
}
// The SPA then reads the XSRF-TOKEN cookie and echoes it in the X-XSRF-TOKEN header.
The decision rule is what the credential is. If the browser attaches it automatically — a cookie or basic auth — you need CSRF protection. If the client must attach it deliberately, as with a bearer token, an attacking site cannot forge the request and the protection is redundant.
Picture it the same POST sent by three clients, the filter that stops one of them, and what the request must carry for it to pass.
The setup: the chain has CSRF on (the default) and authenticates the browser by session cookie. The fix code is in the block below.
The trace: where the browser POST dies and where Postman does not:
Browser POST /api/orders Cookie: JSESSIONID=... (no X-XSRF-TOKEN)
└─► CsrfFilter state-changing method, no matching token ✗ AccessDeniedHandler ──► 403
(AuthorizationFilter, method security, controller: never reached)
Browser GET /api/orders safe method, CsrfFilter skips the check ✓ 200
Postman POST /api/orders Authorization: Bearer ... hits a chain with csrf disabled ✓ 201
What you see: the evidence in the response and the DEBUG log:
# illustrative output
POST /api/orders -> 403 Forbidden
DEBUG o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost:8080/api/orders
DEBUG ...AccessDeniedHandlerImpl : Responding with 403 status code
| Request | Credential sent | Result |
|---|---|---|
| GET from the browser | session cookie | Works (safe method, no token needed) |
| POST from the browser, no header | session cookie only | Throws AccessDeniedException, 403 |
POST from the browser with X-XSRF-TOKEN | cookie plus echoed token | Works |
| POST from Postman with bearer token on a stateless chain | Authorization header | Works (CSRF disabled for that chain) |
Why: a browser attaches cookies by itself, so Security demands a token the attacker's page cannot read; a bearer header is added only by code, so there is nothing to forge.
The fix: the two options are in the code below: FIX A for a bearer-token chain, FIX B for a cookie chain.
What you see now: after FIX B the browser echoes the token:
# illustrative output
POST /api/orders
Cookie: JSESSIONID=...; XSRF-TOKEN=7c1e...
X-XSRF-TOKEN: 7c1e...
-> 201 Created
Land it 403 on browser writes only is CSRF, and the right fix follows from whether the credential is a cookie the browser sends on its own or a header the client must add.
- "You switched to
CookieCsrfTokenRepository.withHttpOnlyFalse()and the SPA still gets 403 on the first POST after login. What next?" Since Spring Security 6 the token is deferred: the cookie is only written when something reads the token during a request, so a login followed immediately by a POST may find no cookie has been set yet.
The fix is to make the token load on every request: configure the
CsrfTokenRequestAttributeHandlerand add a smallOncePerRequestFilterafter theCsrfFilterthat callscsrfToken.getToken()from the request attribute, which forces the cookie to be written. Spring Security's documentation shows this exact filter for single-page applications.Also check that the SPA's HTTP library actually reads
XSRF-TOKENand sendsX-XSRF-TOKEN; Axios does by default,fetchdoes not. And checkSameSiteand domain on the cookie, because a cookie the browser did not store cannot be echoed.- "Why does Security exempt bearer-token requests from CSRF, mechanically?"
It does not exempt them by token type; it exempts them by the chain's configuration and by request matching.
In the resource server configuration the recommended chain disables CSRF because there is no cookie-based ambient credential, and in a chain where CSRF is on,
CsrfFilteruses aRequestMatcherthat requires a token for every non-safe method regardless of headers.So Postman POSTs working in the scenario means one of two things: the chain that matched Postman's request had CSRF disabled, or Postman sent no session cookie and the request was rejected for a different reason that happened to succeed on a permit-all path.
The key insight is that CSRF is about whether the browser attaches a credential automatically; a bearer header is attached only by code, so it cannot be forged by another site.
- "What is the BREACH protection in Security 6's CSRF handling, and does it matter for JSON APIs?"
BREACH is an attack that recovers a secret from a compressed HTTPS response by measuring size changes, and a CSRF token echoed in HTML responses is such a secret.
Security 6's
XorCsrfTokenRequestAttributeHandlermasks the token with a random XOR per response so the same token looks different every time it is rendered, defeating the size measurement.For a JSON API where the token travels in a cookie and a header rather than in the response body, the masking still applies to the value written to the request attribute but the cookie value is the raw token, so the SPA can echo it unchanged.
The practical effect is that a client comparing the header value with what it sees in an HTML page would find them different, which confuses people during migration but is correct.
- "How do you write the integration test that reproduces the browser flow?"
With
MockMvcandspring-security-test: perform a GET to any endpoint to receive theXSRF-TOKENcookie, extract the cookie from the result, then perform a POST with the session cookie, theXSRF-TOKENcookie, and anX-XSRF-TOKENheader set to the cookie's value, asserting 200.A second test posts without the header and asserts 403, so the protection is proven to be on.
SecurityMockMvcRequestPostProcessors.csrf()is the shortcut that injects a valid token, but for this scenario I want the real cookie round trip, because the bug was in the cookie handling.The test runs in a
@WebMvcTestwith the security configuration imported and no database, so it is fast enough to run on every commit.
Q63. "What exactly does the OAuth2 resource server validate on an incoming JWT, how does key rotation work, and what do you do about clock skew?"
Reveal answer
Strong answer With issuer-uri configured, Boot fetches the issuer's OpenID discovery document at startup, reads the jwks_uri, and builds a NimbusJwtDecoder.
On each request the decoder runs these steps in order:
- Parse: read the token and its
kidheader. - Verify: look up the matching public key in its cached JSON Web Key Set and check the signature.
- Time:
JwtTimestampValidatorchecksexpandnbfwith a default 60-second clock skew allowance. - Issuer:
JwtIssuerValidatorchecks thatissequals the configured issuer.
Audience is not checked by default; add spring.security.oauth2.resourceserver.jwt.audiences or a custom JwtClaimValidator, and a senior answer says that a missing audience check is how a token for one API is replayed against another.
Key rotation: the identity provider publishes new keys in the JWKS alongside old ones before switching signing; when a token arrives with an unknown kid, the decoder refetches the JWKS once, so rotation needs no restart, and the cache also refreshes on a timer.
Clock skew: the 60-second default covers normal drift; if pods run NTP, keep it; if tokens are minted by a partner with a badly set clock, widen it deliberately with a custom JwtTimestampValidator(Duration.ofMinutes(2)) rather than disabling expiry.
The converted authorities come from the scope or scp claim with a SCOPE_ prefix, and a JwtAuthenticationConverter customises that when roles live in a different claim.
Picture it a real token taken apart, the checks the decoder runs on it in order, and the one check that is missing by default.
The setup: a token minted by the same identity provider but meant for a different API:
// header
{ "alg": "RS256", "kid": "key-2026-09" }
// payload
{ "iss": "https://idp.shop.example", "sub": "partner-7", "aud": "billing-api",
"scope": "orders:read", "exp": 1789000000 }
Make the invisible visible: the decoder's key cache and the checks, in the order they run:
# illustrative output
JWKS cache: kid key-2026-09 -> RSA public key, kid key-2026-06 -> RSA public key
1. parse token, read kid -> key-2026-09
2. verify signature with cached key ✓
3. JwtTimestampValidator (exp, nbf, 60s) ✓
4. JwtIssuerValidator (iss == issuer-uri) ✓
5. audience not checked by default ✗ token for billing-api accepted by orders-api
What you see: the refusal for an expired token, and the silent acceptance of the wrong audience:
# illustrative output
expired token: 401
WWW-Authenticate: Bearer error="invalid_token", error_description="Jwt expired at 2026-09-12T10:03:00Z"
aud=billing-api against orders-api, no audience validator: 200 (the vulnerability)
Why: signature, expiry and issuer prove who minted the token, not which API it was minted for.
The fix: state the audience:
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://idp.shop.example
spring.security.oauth2.resourceserver.jwt.audiences=orders-api
What you see now: the same token:
# illustrative output
aud=billing-api -> 401
WWW-Authenticate: Bearer error="invalid_token", error_description="The aud claim is not valid"
aud=orders-api -> 200
| Check | Default with issuer-uri | How to change |
|---|---|---|
Signature by kid | Yes | JWKS refetch on unknown kid handles rotation |
exp and nbf | Yes, 60 second skew | new JwtTimestampValidator(Duration.ofMinutes(2)) |
iss | Yes | n/a |
aud | No | jwt.audiences property or a JwtClaimValidator |
Land it Signature, expiry, and issuer are checked for you; audience is yours to add, and rotation just works because the decoder refetches on an unknown key id.
- "The identity provider is down at startup. What happens to the service, and how do you make it survive?"
With
issuer-uri, Boot'sJwtDecoderbean fetches the discovery document lazily since Boot 2.x through aSupplierJwtDecoder, so startup succeeds and the first request that needs a token triggers the fetch; if the provider is still down, that request fails with a 401 and an error mentioning the issuer, and the decoder retries on the next request.With
jwk-set-uriconfigured directly the same lazy behaviour applies. Where it bites is a readiness or warm-up step that decodes a token at startup, which then fails.To survive a longer outage I cache the JWKS across restarts: a custom
NimbusJwtDecoderbuilt with aJWKSourcethat falls back to a file or Redis copy of the last good key set, refreshed on a timer, so tokens stay verifiable for the key lifetime even when the provider is unreachable.- "How does the JWKS cache actually behave, and what is the attack if refetch-on-unknown-kid is abused?"
Nimbus's
JWKSourceBuilder, used byNimbusJwtDecoder, caches the key set with a default time-to-live of 5 minutes and a refresh-ahead, and refetches once when a token arrives with an unknownkid, with a rate limit so an attacker sending randomkidvalues cannot make the service hammer the provider; the default rate limit is one refetch per 30 seconds.The attack without that limit is a denial of service by JWKS flooding, and a secondary one is forcing a refetch at a moment the provider is compromised. With the limit, a burst of unknown key ids is rejected cheaply.
Verifying it: the
http.client.requestsmetric for the JWKS URI should show at most a couple of calls per minute even under a test that sends garbage tokens.- "How do you add the audience check and a custom claim check, and how do you test them?"
The property
spring.security.oauth2.resourceserver.jwt.audiences=orders-apiadds aJwtClaimValidatoronaud. For a custom claim I build the decoder myself:NimbusJwtDecoder.withIssuerLocation(issuer).build(), thendecoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefaultWithIssuer(issuer), new JwtClaimValidator<String>("tenant_id", Objects::nonNull))), keeping the defaults so expiry and issuer are still checked.Testing does not need the provider: generate an RSA key pair in the test, sign tokens with Nimbus's
JWSObject, and configure the decoder with that public key, then assert a token with the wrong audience is rejected withJwtValidationExceptionand a correct one produces the expected authorities.This is a unit test on the decoder, not an HTTP test.
- "When would you use opaque tokens with introspection instead of JWTs?"
When immediate revocation matters more than latency, or when the token must not reveal claims to the client.
An opaque token is a random string; the resource server calls the provider's introspection endpoint per request with
spring.security.oauth2.resourceserver.opaquetoken.introspection-uri, gets the active flag and claims, and can cache the result briefly. Revocation is then as fast as the cache expiry, versus JWT's expiry time.The costs are a network call per request, or per cache miss, which makes the provider a latency and availability dependency, and higher load on the provider.
A hybrid is common: short-lived JWTs of five minutes for the fast path, and a small revocation list checked locally for the rare emergency, which is what Q64 does.
Q64 · Design. "Design authentication and authorisation for a B2B API where partner systems call us machine-to-machine, some partners have read-only access, and we must be able to revoke one partner within a minute."
Reveal answer
Strong answer Requirements: no user present, partner identity per call, coarse permissions by partner tier, fast revocation, and auditable access. Design: OAuth2 client credentials.
The design has five parts:
- Identity: each partner is a client in our authorisation server (Keycloak, or Spring Authorization Server if we host it), with a client id and either a secret or, better, a private key JWT or mutual TLS credential.
- Token: the partner obtains a short-lived access token, 5 minutes, carrying
scopeclaims such asorders:readororders:writeand apartner_idclaim. - Resource server: our Boot service validates it as in Q63, with the audience validator set to our API's identifier, and a
JwtAuthenticationConverterthat maps scopes to authorities and exposespartner_idas the principal name. - Authorisation, layered: URL rules in the chain for coarse method-by-path checks, and
@PreAuthorize("hasAuthority('SCOPE_orders:write')")on service methods for the fine ones. Data-level tenancy filters onpartner_idmean a partner cannot read another's orders even with a valid scope. - Revocation within a minute: the 5-minute token lifetime plus disabling the client at the authorisation server, since a disabled client cannot get a new token. For true immediate revocation, the service also checks a small in-memory set of revoked partner ids refreshed from a cache every 30 seconds, which is cheaper than token introspection on every call.
Audit: every request logs partner id, scope, and outcome as structured fields. Trade-offs: short tokens mean more token calls from partners, which is a fair price.
What I would not do: long-lived static API keys in a database, since they cannot express scope or expiry, or per-call introspection, which makes the authorisation server a latency dependency.
Picture it a partner token as the service sees it, a revocation timeline in numbers, and a table from symptom to action.
The setup: partner 7 holds a read-only client; its token is the whole identity:
{ "iss": "https://auth.shop.example", "sub": "client-7", "aud": "orders-api",
"scope": "orders:read", "partner_id": "p-7", "exp": 1789000300 } // 5 minute lifetime
Make the invisible visible: what the resource server derives from it:
# illustrative output
principal name : p-7
authorities : [SCOPE_orders:read]
GET /orders -> authority present, rows filtered to partner_id = p-7 ✓
POST /orders -> @PreAuthorize needs SCOPE_orders:write ✗ 403
The trace: revoking partner 7 at minute 0, with and without the local list:
# illustrative output
t=0:00 client p-7 disabled at the authorisation server; it can no longer get new tokens
t=0:00 token minted at t=-0:04 is still valid for 1 more minute (token lifetime only)
t=0:30 revoked-partner set refreshed from cache: p-7 present ✗ every call from p-7 now rejected
t=5:00 last possible token has expired; revocation complete even without the local set
| Symptom | Root cause | Action |
|---|---|---|
| Partner still calls after being disabled | Existing token valid up to 5 minutes | Check revoked set; shorten lifetime if the business needs less |
| Token endpoint spikes from one client | Partner fetches a token per request | Tell the partner to cache until about 80 percent of expires_in |
| Partner A reads partner B's orders | Scope checked but no data-level filter | Filter on partner_id (see Q68), test as A against B's data |
| Token for another API accepted | No audience validator | Set the audience to our API identifier |
Land it Client credentials with short tokens gives you identity, scope, and expiry in one mechanism, and revocation becomes a matter of token lifetime plus one cached list.
- "Requirement change: a partner must be able to delegate access to a sub-contractor with a subset of its permissions. What changes?"
That is delegation, and OAuth2 token exchange, RFC 8693, is the standard mechanism: the partner presents its own token to the authorisation server and asks for a token for the sub-contractor's client with a narrowed scope, and the resulting token carries an
actormay_actclaim naming the delegation chain.Our resource server then reads two identities: the subject is the sub-contractor, and the actor chain shows the partner it acts for, which the tenancy filter uses to scope data to the partner's rows.
The authorities are computed from the exchanged token's scopes, which the server has already narrowed. Revocation of the partner revokes the chain because the exchanged tokens are short-lived and cannot be renewed once the partner's client is disabled.
Spring Authorization Server supports token exchange since version 1.3, and Keycloak has it as well.
- "What would you cut with one week?"
The local revocation list, the mTLS or private-key-JWT credential, and the structured audit fields. I would ship client credentials with a client secret, a five-minute token lifetime, scope-to-authority mapping, the audience validator, and
@PreAuthorizeon the write paths.Revocation within a minute is not met by that version, only within five, so I would say that out loud and ask whether five minutes is acceptable for launch, which it often is for a partner API.
The audience validator is the one I would refuse to cut, because without it any token issued by the same provider for any other API is accepted here, and that is a real vulnerability rather than a missing feature.
- "How does the tenancy filter on
partner_idwork so a valid scope cannot read another partner's data?" The
JwtAuthenticationConverterputs thepartner_idclaim on the principal, and a servlet filter after authentication copies it into a request-scoped tenant context.Every repository query that touches partner-owned tables is then constrained in one of three ways, from weakest to strongest: a
WHERE partner_id = :currentthe developer writes, a Hibernate@TenantIddiscriminator on the entities so Hibernate adds the predicate automatically, or PostgreSQL row-level security policies keyed on a session variable set at connection checkout, which the database enforces regardless of the query.I use the second plus the third, as in Q68, so a missed predicate returns nothing rather than everything. An integration test runs each endpoint as partner A against data seeded for partner B and asserts empty results.
- "How do partners handle the token lifecycle, and what do you tell them in the onboarding document?"
Partners call the token endpoint with their client id and secret, receive a token with
expires_in, cache it, and refresh a little before expiry; the document says to refresh at 80 percent of the lifetime, to retry on 401 withinvalid_tokenexactly once with a fresh token, and to never fetch a token per request, because that turns the authorisation server into a bottleneck. It also lists the scope names and their meaning, the audience they must request, theWWW-Authenticateerror codes we return and what to do for each, and the rate limit per client. On our side, the token endpoint's request rate per client is a metric, and a partner fetching a token per request shows up as a spike I can raise with them before it becomes an incident.
Q65. "How does @PreAuthorize get enforced, what can its expression reach, and what are the two ways it silently fails to apply?"
Reveal answer
Strong answer @EnableMethodSecurity registers an AuthorizationManagerBeforeMethodInterceptor for @PreAuthorize and an after-interceptor for @PostAuthorize, applied through the standard AOP proxy machinery.
On a call through the proxy, the interceptor evaluates the SpEL expression against a MethodSecurityExpressionRoot: it can reach the current authentication and principal, the built-in checks hasRole, hasAuthority, hasAnyAuthority, isAuthenticated, the method's parameters by name with #orderId, and any bean by @beanName.method(...), which is how you write @PreAuthorize("@orderAccess.canView(#id, principal)") and keep logic out of strings.
@PostAuthorize can additionally reference returnObject, and @PostFilter and @PreFilter filter collections, which is expensive and better done in the query.
The two silent failures are the two proxy failures:
- Self-invocation: a method in the same class calls the annotated one on
this, so the call never enters the proxy. - Unproxied method: the annotation sits on a method that is private, final, or on a class the container never created.
A third, less silent, failure is a missing @EnableMethodSecurity, in which case nothing is enforced anywhere and only a test catches it.
Spring Security 6.3 and later can also apply @PreAuthorize to whole classes via @AuthorizeReturnObject and to Spring Data via @Query integration, but the core mechanism is the same interceptor.
@Service
public class OrderService {
// The expression can reach: the authentication, method arguments by name,
// the returned object (with @PostAuthorize), and any bean via @beanName.
@PreAuthorize("hasRole('ADMIN') or #order.customerId == authentication.name")
public void cancel(Order order) { ... }
@PreAuthorize("@orderPermissions.canView(#id, authentication)") // a bean
public Order find(String id) { ... }
@PostAuthorize("returnObject.customerId == authentication.name") // after the call
public Order load(String id) { ... }
}
// SILENT FAILURE 1 — method security not enabled at all. The annotations are
// just annotations; nothing is enforced and every call succeeds.
@Configuration
@EnableMethodSecurity // REQUIRED. Without it, @PreAuthorize does nothing.
public class SecurityConfig { }
// SILENT FAILURE 2 — the proxy cannot intercept the method. Same rule as
// @Transactional: it is proxy-based, so all of these are unenforced:
@PreAuthorize("hasRole('ADMIN')") private void x() { } // private
@PreAuthorize("hasRole('ADMIN')") final void y() { } // final
@PreAuthorize("hasRole('ADMIN')") static void z() { } // static
public void caller() { this.cancel(order); } // self-invocation
Both failures are silent and both fail open. That is the important property: a misconfigured @Transactional loses data noisily, while a misconfigured @PreAuthorize grants access quietly — which is why authorisation needs a test that asserts a forbidden call is actually rejected.
Picture it what the @PreAuthorize proxy looks like written out, and the call paths that reach the method without going through it.
The setup: the OrderService in the code above, with cancel(Order) guarded by hasRole('ADMIN') or ownership.
Make the invisible visible: the generated proxy, written as pseudo-Java:
// illustrative: what the container injects instead of the real object
class OrderService$$SpringCGLIB extends OrderService {
OrderService target;
@Override public void cancel(Order order) {
authorizationManagerBefore.check(currentAuthentication, "hasRole('ADMIN') or #order.customerId == authentication.name");
// denied -> throws AccessDeniedException, target is never called
target.cancel(order);
}
}
The trace: the working call and the silent ones:
Controller ──► proxy.cancel(order) interceptor evaluates the SpEL expression
├─► denied ✗ AccessDeniedException, method body never runs
└─► allowed ✓ target.cancel(order)
Controller ──► proxy.caller() no annotation here
└─► target.caller()
└─► this.cancel(order) ✗ raw object, no interceptor, no check
@PreAuthorize on private/final/static ✗ proxy cannot override it, no check
What you see: a test calling the service as a user without the role:
# illustrative output
@EnableMethodSecurity present : AccessDeniedException: Access Denied
@EnableMethodSecurity missing : no exception, cancel() ran and the order is cancelled
Why: the check lives in the proxy, so any path that does not enter the proxy skips it.
The fix: enable method security, annotate public non-final methods called from outside the bean, and prove it with a test:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class OrderSecurityTest {
@Autowired OrderService service;
@Test @WithMockUser(authorities = "SCOPE_orders:read")
void writeIsRejected() {
assertThrows(AccessDeniedException.class, () -> service.cancel(someOrder()));
}
}
Land it Method security is an AOP interceptor, so it inherits every proxy rule, and a test that calls the method without a principal and expects AccessDeniedException is the only proof it is on.
- "How does
@beanName.method(...)in the expression get resolved, and what does it cost per call?" The expression is parsed once per method by the SpEL parser and cached on the method's
ExpressionAttribute.Evaluation runs against a
MethodSecurityExpressionRootwhose bean resolver is aBeanFactoryResolver, so@orderAccessis a bean lookup by name, cached by the factory, followed by a reflective method call with the argument values.The cost is a few microseconds, dominated by whatever
canViewdoes; if it queries the database, that is the cost. For expressions used on hot paths, Spring Security can compile SpEL whenSpelCompilerMode.IMMEDIATEis set through a customDefaultMethodSecurityExpressionHandler, which turns evaluation into bytecode.In practice the discipline that matters is that the bean method does one cheap check and never a remote call, because it runs on every invocation.
- "What is the difference between
hasRoleandhasAuthority, and where does theROLE_prefix come from?" hasAuthority("X")checks for aGrantedAuthoritywhose string is exactlyX.hasRole("ADMIN")checks for the authorityROLE_ADMIN, adding the prefix, and rejects an argument that already starts withROLE_.The prefix is the
GrantedAuthorityDefaultsbean's value, which can be changed by declaring one with an empty prefix, but changing it globally breaks libraries that assume the default.For JWTs, scopes arrive as
SCOPE_orders:writeby default, sohasAuthority("SCOPE_orders:write")is the correct check andhasRolewould look forROLE_SCOPE_orders:write. If roles live in a claim such asrealm_access.roles, aJwtGrantedAuthoritiesConverterwith theROLE_prefix maps them sohasRoleworks.- "How do you test that method security is actually on without booting the web layer?"
A
@SpringBootTestwithwebEnvironment = NONEthat injects the service and calls the annotated method with@WithMockUser(authorities = "SCOPE_orders:read"), expectingAccessDeniedExceptionfor a write, and a second call with the write authority expecting success.Add a third call with no security context at all, using
@WithAnonymousUseror simply no annotation, expectingAuthenticationCredentialsNotFoundException. If@EnableMethodSecurityis missing, the first and third calls succeed, which is the failure the test exists to catch.For speed, the same can run in an
ApplicationContextRunnerwith the service and the method security configuration only, which avoids the database.- "What does
@AuthorizeReturnObjectadd, and when is it worth it?" Added in Spring Security 6.3, it wraps the returned object in a proxy so that the object's own annotated methods, for example
@PreAuthorize("hasRole('ADMIN')")onOrder.getInternalNotes(), are enforced when the caller invokes them, even though the domain object is not a Spring bean.It extends method security from services to the objects they return, which is useful for field-level authorisation on rich domain models.
The costs: every returned object of that type is proxied, which for a list of a thousand orders means a thousand proxies, and it needs CGLIB-proxyable classes.
I use it for a small number of sensitive accessor methods on aggregate roots, and for bulk data I prefer projections that omit the field at the query level.
Q66 · Scenario. "An audit log records the acting user on every write. After moving the write to an @Async method, the audit rows show user 'anonymous'. Diagnose and fix without passing the user manually."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the security context is missing on the async thread. The
SecurityContextHolderuses aThreadLocalstrategy by default, so a new thread has an empty context. - Evidence: log the thread name and
SecurityContextHolder.getContext().getAuthentication()at the start of the async method; it prints atask-Nthread and null. - Cause:
@Asynchands the call to an executor; nothing copies the thread-local context unless the executor is decorated to do so. - Fix: wrap the executor with
DelegatingSecurityContextAsyncTaskExecutor, or, in Boot, register aTaskDecoratorbean that captures the context and the logging MDC before submission and restores them inside the task; Boot's auto-configuredThreadPoolTaskExecutorpicks up aTaskDecoratorbean automatically. Spring Security 6 also supports aSecurityContextHolderStrategybased on Reactor context or explicit propagation for reactive code. For virtual threads the same decorator approach works, and Micrometer's context-propagation library can carry security, tracing, and MDC together across executors. - Prevention: a test that calls the async method with a mock principal and asserts the audit row's user, and a standard executor bean in the platform starter that already carries the decorator.
// BROKEN — SecurityContextHolder uses a ThreadLocal by default. The @Async
// method runs on a pool thread, where that ThreadLocal is empty.
@Async
public void writeAudit(String action) {
var auth = SecurityContextHolder.getContext().getAuthentication();
audit.save(action, auth == null ? "system" : auth.getName()); // always "system"
}
// FIX A — propagate the context to async threads, application-wide.
@Configuration
public class AsyncSecurityConfig {
@Bean
static MethodInvokingFactoryBean securityContextStrategy() {
var b = new MethodInvokingFactoryBean();
b.setTargetClass(SecurityContextHolder.class);
b.setTargetMethod("setStrategyName");
b.setArguments(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
return b;
}
// For an explicit executor, wrap it instead — this also works with pools,
// where INHERITABLETHREADLOCAL does not, because pool threads are reused:
@Bean Executor taskExecutor(ThreadPoolTaskExecutor delegate) {
return new DelegatingSecurityContextExecutor(delegate);
}
}
// FIX B — the one I prefer: do not depend on ambient state at all.
// Capture the user on the request thread and pass it as an argument.
public void placeOrder(Order o) {
String actor = SecurityContextHolder.getContext().getAuthentication().getName();
auditService.writeAudit(o.id(), actor); // explicit, testable, thread-agnostic
}
Read why INHERITABLETHREADLOCAL is not sufficient on its own. It copies the context when a thread is created, and a thread pool creates its threads once and reuses them — so the second task on a pooled thread inherits whatever the first one left behind, which is worse than an empty context.
Picture it two threads, the thread-local each one holds, and the hop where the identity is lost.
The setup: the writeAudit method in the code below, called from placeOrder on the request thread.
Make the invisible visible: what each thread's SecurityContextHolder contains at the moment of the call:
# illustrative output
thread http-nio-8080-exec-3 SecurityContext -> JwtAuthenticationToken(name=alice)
thread task-1 SecurityContext -> (empty)
The trace: the hop that loses it, and the same hop with a decorated executor:
http-nio-8080-exec-3: controller ──► orderService.placeOrder() user = alice ✓
└─► proxy.writeAudit() @Async: submit Runnable to executor
╰─► task-1: target.writeAudit()
getAuthentication() = null ✗ ThreadLocal of task-1 is empty
audit row user = "system"
with TaskDecorator / DelegatingSecurityContextAsyncTaskExecutor:
submit: capture alice ──► task-1: set alice, run, clear ✓ audit row user = "alice"
What you see: one log line in the async method before the fix and after:
# illustrative output
before: [task-1] writeAudit auth=null
after : [task-1] writeAudit auth=alice
audit table: id 41 action=ORDER_PLACED user=system -> id 42 action=ORDER_PLACED user=alice
Why: @Async hands the call to another thread, and a thread-local never crosses threads unless something copies it.
The fix: the code below shows the executor wrapper (FIX A) and the explicit argument (FIX B).
Land it Identity lives in a thread-local, so every hop to another thread needs a decorator that carries it, and the same goes for the trace id.
- "You added the
TaskDecoratorand the audit user is right, but the trace id is still missing in the async logs. What next?" The decorator copies what I told it to copy, and the trace context lives in a different place from the security context. With Micrometer Tracing, the current span is in a thread-local managed by the tracer, and MDC is populated from it.
The clean fix is Micrometer's
context-propagationlibrary: Boot 3.2 and later auto-configure aContextPropagatingTaskDecoratorwhen the library is present, which captures every registeredThreadLocalAccessor, tracing and MDC among them.If I already have a custom decorator, compose them with a
CompositeTaskDecorator, since only one decorator bean is picked up by the auto-configured executor.Security's context needs its own accessor, which Spring Security 6.x provides, so with both registered a single decorator carries identity, trace, and MDC together.
- "How does propagation work on virtual threads and with
ScopedValue?" Thread-locals work on virtual threads exactly as on platform threads, so the decorator approach is unchanged when
spring.threads.virtual.enabled=true; the auto-configuredSimpleAsyncTaskExecutorhonours theTaskDecoratorbean.ScopedValue, final in JDK 25, is inherited automatically by child threads created inside aStructuredTaskScope, which removes the need for a decorator for fan-out within one request, but it is not inherited across an executor submission, because the executor's thread is not a child of the scope.Spring Security's
SecurityContextHolderstill uses a thread-local strategy by default; aScopedValue-based strategy is possible throughSecurityContextHolderStrategybut not yet the default as of Aug 2026, so the decorator remains the portable answer.- "Why is capturing the security context at submission time the right moment rather than at execution time?"
Because the submitting thread is the request thread that holds the identity; by execution time the request may have finished and its context cleared, and the executor thread never had one.
DelegatingSecurityContextAsyncTaskExecutorand aTaskDecoratorboth readSecurityContextHolder.getContext()whensubmitis called and close over it, then set it on the worker before the task and clear it after.The clearing matters: without it, a pooled thread keeps the previous task's identity and the next task, submitted with no context, runs as the wrong user.
That is a worse bug than "anonymous" and it is why I test the decorator with two sequential submissions from different principals and assert each audit row.
- "What are the alternatives to relying on thread propagation at all for an audit field?"
Make the identity part of the data. The request-thread code resolves the acting user once and passes it into the command object that the async method receives, so the audit write has the user as a plain field with no ambient context.
That is more explicit, works across any executor, queue, or service boundary, and is trivially testable. The reason the scenario asked for a fix without passing the user is usually that dozens of call sites would change; the decorator fixes them all at once.
My position is both: the decorator as the safety net for everything that reads ambient context, and explicit passing for new code and for anything that crosses a process boundary, where thread propagation cannot reach anyway.
Q67. "A stateless API service is suddenly creating HTTP sessions and memory is growing. What creates them, how do you stop it, and when would you use Spring Session instead?"
Reveal answer
Strong answer Sessions are created by anything that calls request.getSession() with create allowed.
Spring Security's default policy is IF_REQUIRED, so once a request is authenticated, the SecurityContextRepository saves the context in a new session; form login, basic auth, and the CSRF token repository all touch the session too.
Each session then holds the security context and any attributes for the 30-minute default timeout, so an API receiving 1,000 requests per second from bearer-token clients that never send the cookie back creates 1,000 sessions per second that live for 30 minutes: about 1.8 million objects.
Stop it with sessionManagement(s -> s.sessionCreationPolicy(STATELESS)), which also switches to a request-attribute security context repository, and make sure no controller or view technology calls getSession().
When you genuinely need server-side state for browser users, in-memory sessions break across instances and on restarts; Spring Session stores the session in Redis or a JDBC table keyed by the cookie, with spring.session.store-type or the starter's auto-configuration, so any instance can serve any user and a deploy does not log everyone out.
You would still avoid it for machine-to-machine APIs, where the token is the state, and you would keep sessions small because every request deserialises the whole session.
Picture it one bearer-token request that leaves a session behind, the cookie and metrics that prove it, and the same request with a stateless chain.
The setup: a token API with Security's default session policy and clients that never send the cookie back.
The trace: what creates the session:
Client ──► GET /api/orders Authorization: Bearer ... (no cookie)
└─► BearerTokenAuthenticationFilter authenticates ✓
└─► SecurityContextHolderFilter policy IF_REQUIRED, saves context
└─► HttpSessionSecurityContextRepository.saveContext
└─► request.getSession(true) ✗ new session, cookie ignored by client, lives 30 min
What you see: the response header and the meters, before and after:
# illustrative output
before: HTTP/1.1 200
Set-Cookie: JSESSIONID=9F3A...; Path=/; HttpOnly on every response
tomcat.sessions.active.current 1,800,000 (climbing)
tomcat.sessions.created +1,000/s
after: (no Set-Cookie header)
tomcat.sessions.active.current 0
tomcat.sessions.created flat
Why: IF_REQUIRED means Security creates a session whenever it has something to save, and a stateless client never reuses it.
The fix: declare the chain stateless:
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
return http
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
What you see now: the "after" lines above: no Set-Cookie, flat session metrics.
Land it A token API must be declared stateless or Security will faithfully build a session per request, and only browser-facing state earns a session store.
- "You set the policy to STATELESS and sessions are still being created. What next?"
Something outside Security is calling
getSession(). I would find it with a breakpoint or aHttpSessionListenerbean that logs a stack trace insessionCreated; the trace names the caller within one request.The usual culprits are a view technology such as Thymeleaf or a flash-attribute redirect,
RedirectAttributesin a controller, the CSRF token repository if it is still the session-based one, the OAuth2 login's authorization request repository, Spring'sLocaleResolveror theme resolver configured for session, and a metrics or tracing filter that stores state in the session.sessionCreated listenerruns offline# illustrative output java.lang.Exception: session created at com.shop.config.SessionTracer.sessionCreated(SessionTracer.java:14) at org.apache.catalina.session.StandardSession.tellNew(StandardSession.java:...) at org.springframework.web.servlet.mvc.support.DefaultFlashMapManager ... <- the caller is named hereFor a pure API each of those is removable. As a last line, a
ServletContextInitializerthat sets the session cookie config or a filter wrapping the request to throw ongetSession(true)makes the next offender fail in tests rather than in production.- "What is the actual memory per session, and how did you get to 1.8 million?"
At 1,000 requests per second with a 30-minute timeout, the steady state is 1,000 times 1,800 seconds, which is 1.8 million live sessions, since each lives 30 minutes and they are created continuously.
Each Tomcat
StandardSessioncosts a few hundred bytes of its own plus the attribute map, and the security context inside it holds theAuthenticationwith its authorities and the principal, aJwtobject with its claims map and the raw token string, which is easily 2 to 5 kilobytes.So 1.8 million sessions is several gigabytes, which is the memory growth in the symptom. The verification is
tomcat.sessions.active.currentandtomcat.sessions.createdin Micrometer, both exposed by Boot's Tomcat metrics binder, and a heap histogram dominated byStandardSession.- "How does Spring Session change the cost model, and what settings matter?"
The session moves to Redis or JDBC, so the JVM holds nothing between requests, and every request that has a session cookie reads and deserialises the session from the store and writes it back if changed.
The costs become a Redis round trip per request, serialisation, and store memory.
Settings:
spring.session.timeout, which should be as short as the product allows;spring.session.redis.flush-mode=on-saveto write once per request rather than per attribute change;spring.session.redis.namespaceper application to avoid key collisions; and a JSON serialiser instead of Java serialisation, configured via aRedisSerializerbean, so a class change does not make old sessions unreadable.Keep the session small, because a 50 kilobyte session is 50 kilobytes moved on every request.
- "For a browser-facing app, session versus JWT in a cookie: your position?"
Sessions with Spring Session for a first-party browser application. A server-side session can be revoked instantly by deleting it, keeps the token out of the browser entirely, and holds state that a JWT would have to carry on every request.
The cookie is
HttpOnly,Secure, andSameSite=Lax, and CSRF protection stays on.A JWT in a cookie has the same CSRF exposure but cannot be revoked before expiry and grows with claims, and a JWT in local storage is readable by any script, which is the worst option.
The backend-for-frontend pattern is the modern form: the BFF holds the OAuth2 tokens in the session and the browser only ever sees the session cookie, which Spring Security's OAuth2 client support does out of the box.
Q68 · Design. "Design a multi-tenant Boot service where 500 tenants share the code, some large tenants need their own database, and no query may ever return another tenant's rows."
Reveal answer
Strong answer Requirements: tenant identity on every request, strict data isolation, two storage models (shared schema with a tenant column for most, dedicated database for a few), and per-tenant configuration.
Design: tenant resolution happens once, in a servlet filter ordered after authentication, which reads the tenant from the JWT's tenant_id claim, never from a header the client controls, and stores it in a TenantContext backed by a ScopedValue on Java 21 or a ThreadLocal with a TaskDecorator for propagation; the filter clears it in a finally.
Storage routing uses a DataSource that extends AbstractRoutingDataSource, whose determineCurrentLookupKey returns the tenant's pool key: shared for most tenants and tenant-42 for dedicated ones, with pools created lazily from a tenant registry and sized small.
For the shared schema, isolation is enforced below the application code: Hibernate's @TenantId discriminator (Hibernate 6.2 and later) adds WHERE tenant_id = ? to every query for annotated entities and stamps inserts, and PostgreSQL row-level security policies keyed on a session variable set at connection checkout provide defence in depth so a missed filter still returns nothing.
Migrations run per database with Flyway on a loop over the registry. Per-tenant configuration is a cached lookup, not beans.
Testing: an integration test that runs every repository query as tenant A and asserts zero rows of tenant B. Trade-offs: routing at the DataSource level means a transaction cannot span tenants, which is correct; a noisy tenant on the shared pool can starve others, mitigated by a per-tenant concurrency limit in the filter.
What I would not do: schema-per-tenant for 500 tenants, because migrations and connection counts explode; trust a tenant header; or rely on developers remembering the WHERE clause.
Picture it one request followed from token to row, the query Hibernate sends, and a table from symptom to action.
The setup: tenant 42 calls GET /orders; tenant 7 has rows in the same shared table.
The trace: where the tenant is resolved, used and cleared:
GET /orders Authorization: Bearer (tenant_id=42)
├─► JWT filter authenticated ✓
├─► TenantFilter TenantContext = 42 (from the claim, not a header)
│ ├─► AbstractRoutingDataSource lookup key "shared" (tenant 42 is not dedicated)
│ ├─► Hibernate @TenantId adds and tenant_id = 42
│ └─► PostgreSQL row-level policy tenant_id = current_setting('app.tenant')
└─► finally: TenantContext cleared ✓
What you see: the SQL for a normal query and for a native query that forgot the predicate:
# illustrative output
orders table: id | tenant_id query: select * from orders where tenant_id=42 -> row 1
1 | 42 (HQL via @TenantId)
2 | 7
native query written without WHERE: select * from orders
with row-level security -> row 1 only ✓ without it -> rows 1 and 2 ✗ leak
| Symptom | Root cause | Action |
|---|---|---|
| A tenant sees another tenant's row | Native SQL or JdbcTemplate bypassed @TenantId | Row-level security underneath; test each query as A against B's data |
| Tenant id appears wrong on async work | Context is a thread-local not propagated | Propagate with a TaskDecorator or ScopedValue |
| Connection count explodes | Dedicated pool per tenant | Pools only for large tenants, small, created lazily, evicted when idle |
| Migrations drift between databases | Run from application startup | Separate job over the registry; app refuses to route to a behind database |
Land it Resolve the tenant from the token once, route the connection by tenant, and enforce isolation in Hibernate and the database so the application code cannot forget.
- "Requirement change: a support user must be able to act across tenants. How does the design change?"
The tenant context gains an explicit override that is only settable from a privileged path.
The support user's token carries a role,
support, and notenant_id; a dedicated endpoint prefix,/support/tenants/{id}/…, is protected byhasRole('SUPPORT')and its filter sets the tenant from the path, not from the token.The Hibernate discriminator and the row-level security still apply, so the support user sees exactly one tenant at a time, and there is no "all tenants" mode in the application code.
Cross-tenant reports run from a separate read replica with its own credentials and no row-level policy, outside the request path. Every support access is audited with the support user, the tenant, and the reason field from the request.
Making cross-tenant access a separate path rather than a flag keeps the default path incapable of it.
- "What would you cut with two weeks?"
The dedicated-database routing and the per-tenant concurrency limit. I would ship the shared schema with the
@TenantIddiscriminator, the row-level security policies, and the JWT-based tenant filter, because those are the isolation guarantees and they do not depend on the number of databases.The large tenants run on the shared database for now, with the
AbstractRoutingDataSourcedesigned but returning the shared key, so adding a dedicated database later is a registry entry and a migration.I would refuse to cut the row-level security, because it is the only control that holds when a developer writes a native query, and native queries appear in the second month of every project.
- "How does Hibernate's
@TenantIdwork mechanically, and what does it not cover?" An entity field annotated
@TenantIdmakes Hibernate treat that column as a discriminator: aCurrentTenantIdentifierResolverbean, registered throughhibernate.tenant_identifier_resolver, supplies the current tenant, Hibernate addsAND tenant_id = ?to every HQL and criteria query on that entity and to lazy loads, stamps the value on insert, and throws if an entity loaded with one tenant is flushed under another. It does not cover native SQL queries,JdbcTemplateorJdbcClient, bulk HQL updates in some versions, or other tables reached through joins on entities without the annotation. Those gaps are why the database policy sits underneath: PostgreSQL'sCREATE POLICY … USING (tenant_id = current_setting('app.tenant')::uuid), with the setting applied by a Hikari connection customiser or aSET LOCALat transaction start.- "How do you keep 500 tenants' dedicated pools from exhausting the database, and what about migrations at scale?"
Dedicated pools exist only for the few large tenants, each sized small, five connections, and created lazily on first request with an idle eviction after ten minutes so a quiet tenant costs nothing. The count of dedicated databases is what limits it: at twenty dedicated tenants and ten instances, that is a thousand connections at most, which needs a pooler such as PgBouncer in front of each database. Migrations run from a separate job, not from application startup, iterating the tenant registry and running Flyway per database with a concurrency of four, recording each tenant's schema version; the application checks at startup that every database it may route to is at the expected version and refuses to route to one that is behind, rather than migrating in the request path.
Q69. "How should passwords be stored in a Boot service, what does DelegatingPasswordEncoder do, and how do you migrate from an old hash?"
Reveal answer
Strong answer Passwords are never stored; a slow, salted hash of them is. Spring Security's PasswordEncoderFactories.createDelegatingPasswordEncoder() returns a DelegatingPasswordEncoder whose default is bcrypt, with argon2, scrypt, and pbkdf2 available.
The delegating encoder prefixes every hash with an identifier in braces, {bcrypt}$2a$10$..., so a stored value carries the algorithm that produced it.
On matches, it reads the prefix and delegates to the right encoder, which is what makes migration possible: old rows keep working with their old algorithm while new rows use the current one.
Migration without forcing a reset: on successful login, check upgradeEncoding(storedHash); if true, re-hash the just-verified plaintext with the current encoder and save it, which Spring's DaoAuthenticationProvider does automatically when the UserDetailsPasswordService is implemented.
Legacy unsalted hashes such as MD5 or SHA-1 cannot be matched by any secure encoder, so the delegating map is extended with a custom encoder under an id like {legacy} that is only ever used to match, never to encode, and rows are upgraded on login.
Cost tuning: bcrypt strength 10 takes about 100 milliseconds on a modern core, which is the target for a login, and that CPU cost means logins should be rate-limited so an attacker cannot use the hash cost as a denial-of-service lever.
Picture it the password column before and after the migration, the login that upgrades a row, and why raw MD5 rows need a prefix.
The setup: a users table with three generations of hashes and a delegating encoder whose default is bcrypt.
Make the invisible visible: what the column holds:
# illustrative output
before after the next successful login
id | password id | password
1 | 5f4dcc3b5aa765d61d8327deb882cf99 (MD5) 1 | {bcrypt}$2a$10$N9qo8uLO...
2 | {bcrypt}$2a$10$N9qo8uLO... 2 | {bcrypt}$2a$10$N9qo8uLO... (unchanged)
after migration prefix: 1 | {legacy}5f4dcc3b5aa765d61d8327deb882cf99
The trace: one login for user 1:
DaoAuthenticationProvider
├─► loads UserDetails, stored = {legacy}5f4d...
├─► DelegatingPasswordEncoder.matches(raw, stored) reads "{legacy}" -> legacy encoder ✓ match
├─► upgradeEncoding(stored) prefix is not the current default id ✓ true
└─► UserDetailsPasswordService.updatePassword(user, encoder.encode(raw))
└─► row 1 now {bcrypt}$2a$10$... ✓ upgraded
Why: the prefix makes the algorithm part of the stored data, and the raw password exists only during a successful login, which is the only moment the row can be re-hashed.
Land it The prefix makes the algorithm part of the data, so you can change your mind later without a mass reset.
- "Argon2 or bcrypt in 2026, and what parameters?"
As of Aug 2026, Spring Security's factory default is still bcrypt, and OWASP's guidance ranks Argon2id first, then scrypt, then bcrypt.
Argon2id resists GPU attacks better because it is memory-hard:
Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8()uses 16 megabytes of memory, 2 iterations, parallelism 1, which is close to OWASP's minimum; a stronger setting is 64 megabytes and 3 iterations, and the trade-off is that memory cost multiplied by concurrent logins is real RAM on the login service.For a new system I choose Argon2id with the delegating encoder so the id
{argon2}is recorded, and bcrypt at strength 12 if memory per login is a concern.Either way the login endpoint is rate-limited, because the hash cost is a lever an attacker can pull.
- "Walk me through the upgrade-on-login mechanism in Spring Security precisely."
DaoAuthenticationProviderauthenticates by loading theUserDetails, callingpasswordEncoder.matches(raw, stored), and on success callingpasswordEncoder.upgradeEncoding(stored).DelegatingPasswordEncoder.upgradeEncodingreturns true if the stored value's prefix is not the current default id, or if the current encoder itself says its parameters are weaker than configured, whichBCryptPasswordEncoderdoes by comparing the strength in the hash.If true and a
UserDetailsPasswordServicebean exists, the provider callsupdatePassword(user, encoder.encode(raw)), which the application implements by saving the new hash.The raw password is available only at that moment, which is why the upgrade can only happen on a successful login and why a mass migration without logins is impossible for salted hashes.
- "How do you handle a legacy unsalted MD5 table safely during the migration window?"
Register a
{legacy}encoder in the delegating map whosematchescomputes MD5 of the raw value and compares it constant-time withMessageDigest.isEqual, and whoseencodethrows, so nothing new is ever written with it.Prefix every existing row with
{legacy}in one migration so the delegating encoder can route them. Each successful login upgrades the row to the current algorithm as above.After a defined window, say 90 days, the remaining
{legacy}rows belong to inactive users; force a reset for them by invalidating the hash, and remove the legacy encoder so the code cannot verify MD5 anymore.During the window, the legacy rows are an elevated risk if the table leaks, so the window is short and the table's access is audited.
- "What does the
{id}prefix cost in storage and what if an old system reads the same column?" The prefix adds a few bytes,
{bcrypt}is eight characters, and the column needs room: a bcrypt hash is 60 characters plus the prefix, an Argon2 encoded hash is around 100, so aVARCHAR(255)is comfortable.If a legacy system reads the same column and expects a bare hash, it breaks on the braces. Options are a view or a second column for the transition, or configuring the legacy system's reader to strip the prefix.
What I would not do is skip the prefix by using a bare
BCryptPasswordEncoder, because that decision is what makes the next algorithm change a mass reset, and the prefix costs nothing in comparison.
Q70 · Scenario. "A penetration test report says /actuator/env and /actuator/heapdump are reachable from the internet on one service, and that responses lack security headers. Prioritise and fix."
Reveal answer
Strong answer In diagnosis order:
- Severity first:
heapdumpis critical, because a heap contains live tokens, credentials, and customer data;envis high, because masking is heuristic; missing headers are medium. Rotate any secrets that were in that process's environment, since you must assume they were read. - Evidence:
management.endpoints.web.exposure.include=*in the service's configuration, probably copied from a local profile, and no separate management port; the security chain permits/actuator/**entirely. - Immediate fix, same day: set
include=health,info,prometheus, move management tomanagement.server.port=8081which the ingress does not route, and change the security rule torequestMatchers(EndpointRequest.to("health","info")).permitAll()withEndpointRequest.toAnyEndpoint().hasRole("OPS")for the rest. Confirm with a request from outside. - Headers: Spring Security adds
X-Content-Type-Options,X-Frame-Options, cache control, and, on HTTPS,Strict-Transport-Securityby default, so their absence suggests someone calledheaders(h -> h.disable())or the service has no security chain. Restore defaults and add aContent-Security-Policyviaheaders(h -> h.contentSecurityPolicy(...))if the service serves HTML, plusReferrer-Policy. - Prevention: the platform starter from Q5 ships the safe Actuator defaults so a service has to work to expose more; a CI check greps deployed configuration for
exposure.include=*; and an external scanner runs weekly against every public hostname.
Picture it the same three requests from outside the network before and after the fix, and the header block that shows what Security adds.
The setup: a service with management.endpoints.web.exposure.include=* and a chain that permits /actuator/**.
What you see: what an outsider gets today and after the same-day fix:
# illustrative output
before after
GET /actuator/health 200 GET /actuator/health 200
GET /actuator/env 200 {property sources} GET /actuator/env 404 (not exposed)
GET /actuator/heapdump 200 (binary, 480 MB) GET /actuator/heapdump 404
management port 8080 (same as app) management port 8081, not routed by the ingress
The fix: narrow the exposure, move the port and lock the rest:
management:
server.port: 8081
endpoints.web.exposure.include: health,info,prometheus
endpoint.env.show-values: never
What you see now: response headers from an API route with the default Security header writer restored:
# illustrative output
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000 ; includeSubDomains (HTTPS requests only)
Land it Treat an exposed heapdump as a breach, close the port before the endpoint, and make the safe configuration the default so nobody has to remember it.
- "The fix is deployed but the scanner still reaches
/actuator/env. What next?" Check whether the request is reaching the same port and the same configuration. First,
curl -si https://host/actuator/envfrom outside and read the response headers: a Tomcat error page or a Spring Security 401 tells me which layer answered.Second,
/actuator/envon the pod's management port from inside to confirmmanagement.endpoints.web.exposure.includeresolved to the new value, because a higher-priority source such as aMANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDEenvironment variable in the deployment may still say*.Third, check whether the ingress has a second route, or whether a service mesh exposes the management port under a different hostname.
Fourth, confirm the management port change actually applied by looking for "Tomcat started on port 8080 (http) with context path ''" and a second line for 8081 in the startup log.
- "Why do you rotate secrets rather than just close the hole?"
Because I cannot prove the hole was not used. The pen test found it, and the environment endpoint shows values that masking may have missed, while the heap dump endpoint hands out everything in memory including decrypted secrets, session tokens, and database credentials in Hikari's configuration.
Access logs might show whether
/actuator/heapdumpwas fetched, but logs are often sampled or retained briefly, and a single successful fetch is a full compromise. The rotation cost is bounded: database credentials, API keys for partners, and the JWT signing key if the service holds one.The alternative, hoping, is not a security control. I would also add an alert on any request to the heapdump path in the ingress logs from now on, so a future exposure is noticed in minutes.
- "Which security headers does Spring Security set by default, and which do you add for an API?"
By default:
Cache-Control: no-cache, no-store, max-age=0, must-revalidatewithPragmaandExpires,X-Content-Type-Options: nosniff,X-Frame-Options: DENY,X-XSS-Protection: 0, and on HTTPS requestsStrict-Transport-Securitywith a one-year max age and subdomains.For a JSON API I add
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'so an error page cannot execute anything,Referrer-Policy: no-referrer, and I remove theServerheader at the Tomcat level withserver.server-headerleft unset.For a service serving HTML, the CSP is the real work and needs nonces for inline scripts. If the service has no security chain at all, none of these are set, which is often the root cause of the "missing headers" finding.
- "How do you make the safe configuration the default across the fleet, mechanically?"
In the platform starter: an auto-configuration that sets default properties through an
EnvironmentPostProcessoradding a low-priority property source withmanagement.server.port=8081,management.endpoints.web.exposure.include=health,info,prometheus, andmanagement.endpoint.env.show-values=never, so a service that says nothing gets the safe values but can override deliberately.Plus a
SecurityFilterChainat a fixed low order forEndpointRequest.toAnyEndpoint()requiring an operations role except health and info. Plus a CI policy check, Conftest or a simple script, that fails a deployment whose rendered configuration containsexposure.include=*or a management port equal to the server port.And a weekly external scan against every public hostname, so the control is verified from the outside, not only asserted from the inside.
The last web group tests the operational corners: contracts and versions, reading bodies twice, errors that leak, timeouts on the server side, and long-running work.
Q71. "What are the ways to version a REST API in Spring, and what did Spring Framework 7 add?"
Reveal answer
Strong answer Traditionally you had three patterns, each done by hand:
- URL versioning:
/v1/orders, a path prefix on the controller mapping, obvious and cacheable but it forks the whole surface per version. - Header versioning: a custom
API-Version: 2header or a media-type parameterAccept: application/vnd.shop.v2+json, which keeps URLs stable and is matched with theheadersorproducesattributes of@RequestMapping. - Query-parameter versioning:
?version=2, the least clean.
All three relied on you writing the matching, and none had a notion of "the latest version" or deprecation.
Spring Framework 7 and Boot 4 added first-class API versioning: @RequestMapping(version = "1.1") on handlers, an ApiVersionStrategy configured through spring.mvc.apiversion.use.header, .path-segment, .query-param, or media-type parameter, with a supported list and a default version, semantic-version comparison so a request for 1.2 can fall through to the highest handler at or below it, and @RequestMapping(version = "1.1+") for baseline mappings.
Requests with an unsupported version get a 400 with a ProblemDetail, and the resolved version is available to RestClient on the calling side too, through the same ApiVersionInserter.
The senior position is to version rarely, add fields rather than change them, and use the built-in strategy so the resolution and the error handling are one place.
Picture it one controller written under each versioning scheme, and what each request is routed to.
The setup: the same GET /orders/42, which in version 1.1 gains a currency field.
// URL versioning: two copies of the surface
@GetMapping("/v1/orders/{id}") OrderV1 getV1(@PathVariable long id) { ... }
@GetMapping("/v2/orders/{id}") OrderV2 getV2(@PathVariable long id) { ... }
// media type versioning: same URL, matched by produces
@GetMapping(value = "/orders/{id}", produces = "application/vnd.shop.v2+json") OrderV2 getV2(...)
// Spring Framework 7: version attribute, resolution done by the framework
@GetMapping(path = "/orders/{id}", version = "1.0") OrderV1 getV1(@PathVariable long id) { ... }
@GetMapping(path = "/orders/{id}", version = "1.1+") OrderV2 getV2(@PathVariable long id) { ... }
| Request | Outcome |
|---|---|
API-Version: 1.0 | Works, handler version 1.0 |
API-Version: 1.1 | Works, handler 1.1+ |
API-Version: 2.0 | Works, falls to the highest baseline at or below 2.0, which is 1.1+ |
API-Version: 3.0 | Throws InvalidApiVersionException, 400 (not in the supported list) |
no header, required=true | Throws MissingApiVersionException, 400 |
What you see: the error body for an unsupported version:
# illustrative output
GET /orders/42 API-Version: 3.0
-> 400 Content-Type: application/problem+json
{"type":"about:blank","title":"Bad Request","status":400,"detail":"..."}
Land it Pick header or media-type versioning for a stable URL space, and on Boot 4 use the framework's version attribute so resolution and errors are consistent across every endpoint.
- "Show me the Boot 4 configuration for header-based versioning and what a request with no version gets."
In properties:
spring.mvc.apiversion.use.header=API-Version,spring.mvc.apiversion.supported=1.0,1.1,2.0,spring.mvc.apiversion.default=1.0, andspring.mvc.apiversion.required=false. Withrequired=falseand a default, a request with no header resolves to 1.0 and hits the handler mapped for that version or the baselineversion = "1.0+".With
required=trueand no header, the request fails with a 400 and a problem body fromMissingApiVersionException. A header naming an unsupported version fails withInvalidApiVersionException, also 400. The same properties exist underspring.webflux.apiversionfor reactive.Programmatically, a
WebMvcConfigurer.configureApiVersioning(ApiVersionConfigurer)does the same and also lets me plug in a customApiVersionParserfor non-semantic versions like dates.- "How does the handler selection work when a request asks for 1.2 and handlers exist for 1.0 and 1.1?"
The
ApiVersionStrategyparses 1.2 into a comparable version and checks it against the supported list; if 1.2 is not listed, the request is rejected before mapping.If it is listed, the
RequestMappingInfomatching treats a handler's fixedversion = "1.1"as matching only 1.1, and a baselineversion = "1.1+"as matching 1.1 and anything higher, so the 1.2 request goes to the 1.1+ handler.When several baseline handlers match, the one with the highest baseline at or below the requested version wins, which is what lets a new version add one changed endpoint while every other endpoint continues to be served by its older baseline handler.
Without a baseline handler at or below 1.2, the request gets a 404 style not-found for that version.
- "What are the caching and gateway consequences of header versioning versus path versioning?"
With the version in the path, every cache and gateway sees distinct URLs, so caching and routing work with no extra configuration, and access logs show the version for free.
With a header or media-type parameter, a shared cache must be told the response varies by that header, so the service adds
Vary: API-Versionto responses, and a gateway that routes by version needs a header rule instead of a path rule.Rate limits and metrics tagged by URL do not distinguish versions unless the tag is added explicitly, which Boot's
http.server.requestsdoes not do by default; a customServerRequestObservationConventionadds the resolved version as a low-cardinality tag.Those are the costs of a stable URL space, and they are manageable when written down once.
- "When would you not version at all?"
For internal APIs between services owned by one organisation, where both sides deploy often, I prefer additive evolution with a compatibility rule instead of versions: never remove or rename a field, never change a type, add fields with defaults, and have consumers ignore unknown fields.
A contract test in each consumer against the producer's current schema catches breakage before deploy. Versioning is for boundaries where the consumer's release schedule is not yours, which is external partners and mobile applications that cannot be forced to update.
Even there, a version should be a rare event with a sunset plan, as in Q72, because each live version is a product you support.
Q72 · Design. "Design the migration of a breaking change to a widely used endpoint: customer.name splits into firstName and lastName, with 40 external clients on different upgrade schedules."
Reveal answer
Strong answer Requirements: no client breaks on the day we deploy, clients migrate at their own pace inside a deadline, we can see who is still on the old shape, and the code does not fork forever. Design: the change is additive first.
For six months the response carries all three fields, name computed from the two new ones, so every client keeps working and new clients can adopt the new fields immediately; requests accept either name or the pair, with a validation rule that exactly one form is present.
Then the removal is a versioned change: with Boot 4's versioning, the existing handler is version = "1", a new handler is version = "2" returning only the new fields, and the default version stays 1 until the deadline.
Measurement: a Micrometer counter on http.server.requests tagged with the resolved version and the client id from the token shows exactly which clients still call version 1, which drives the outreach list.
Communication: a deprecation header, Deprecation and Sunset with the date, on every version 1 response, and an OpenAPI document per version generated by springdoc.
At the deadline, version 1 returns 410 Gone with a problem body pointing at the migration guide for another month, then the handler is deleted.
Trade-offs: the dual-write window costs a computed field and a validation branch, which is cheap; a long deadline is the real cost, so it is a business decision with a date.
What I would not do: change the field in place and email everyone, or keep both versions indefinitely, since the second handler becomes a second product.
Picture it the response shape and the usage numbers at three moments of the migration, and what to do for each client group.
The setup: GET /customers/9, with 40 clients and the split of name into firstName and lastName.
// phase 1, additive (months 0-6): old and new fields side by side
{ "id": 9, "name": "Mary Ann Smith", "firstName": "Mary Ann", "lastName": "Smith" }
// phase 2, version 2 (default stays 1 until the deadline)
version 1: { "id": 9, "name": "Mary Ann Smith", "firstName": "Mary Ann", "lastName": "Smith" } + Deprecation, Sunset headers
version 2: { "id": 9, "firstName": "Mary Ann", "lastName": "Smith" }
// phase 3, after the deadline: version 1 -> 410 Gone + problem body, later the handler is deleted
Make the invisible visible: the usage metric that drives the outreach list:
# illustrative output
http.server.requests{version="1", client="acme"} 41,200 / day
http.server.requests{version="1", client="globex"} 9,800 / day
http.server.requests{version="2", client="initech"} 12,500 / day
month 0: 40 clients on v1 month 3: 22 month 5: 6 deadline: remove v1 only when this reads 0
| Phase | Risk or symptom | Action |
|---|---|---|
| Additive | Client rejects unknown fields | Test with the strictest client; fix before deploy |
| Version 2 live | Client still on v1 near the deadline | Contact it by client id from the metric |
| Deadline | Calls still arriving on v1 | 410 with a migration-guide link for a month, then delete |
Land it Make the change additive, measure who still uses the old shape, set a sunset date on the wire, and only then remove.
- "Requirement change: a regulator requires the split within 30 days, so the six-month window is gone. What changes?"
The additive window shrinks but does not disappear, because the day-one deploy still must not break anyone.
I would ship the additive response on day one, and instead of waiting for clients to move on their own, drive the migration: an automated email per client id from the usage metric, a weekly report of who is still on the old shape, and direct calls to the ten largest clients.
The default version flips to 2 on day 25, so any client that has not set a version explicitly gets the new shape then, with the old version still available by explicit header for the last five days as a safety valve.
On day 30 the old handler returns 410. The regulator's requirement is met by the response shape, and the window is used for outreach rather than waiting.
- "What would you cut under time pressure?"
The per-version OpenAPI documents and the 410 grace period, in that order.
I would keep the additive response, the request validation accepting both forms, the usage metric by client id, and the
DeprecationandSunsetheaders, because those four are what make the migration observable and safe.The metric is the one I would fight for, because without it "who is still on the old shape" is a guess, and a removal based on a guess is how a large client gets broken on a Friday.
The OpenAPI document for the new version can be generated later from the same annotations; the headers take an interceptor and ten lines.
- "How do you make sure the computed
namefield stays consistent with the new fields during the window?" The record for the response has
firstNameandlastNameas stored fields andnameas a derived accessor that concatenates them, annotated for Jackson so it is serialised, with no setter; on the request side, the DTO accepts either and a validator ensures exactly one form is present, and the mapper into the domain splitsnameon the first space with a documented rule for single-token names. The split rule is the risky part: "Mary Ann Smith" can go either way, so I record which form the client sent in the audit log and never overwrite a stored first-and-last pair with a split derived fromnameunless the client sentnameexplicitly. A contract test covers both request forms and asserts the same domain result.- "How do
DeprecationandSunsetheaders work, and do clients actually read them?" Sunsetis an RFC 8594 header carrying an HTTP date after which the resource will be gone;Deprecationis the companion from the IETF deprecation-header specification, carrying the date the deprecation took effect, and aLinkheader withrel="deprecation"points at the migration guide.Most clients do not read them automatically, but API gateways and client libraries increasingly log them, and they give client developers something to find in their logs when they investigate.
The value is less in automatic behaviour and more in having a machine-readable statement on every response, so the removal date is not only in an email nobody forwarded.
I add them in a
HandlerInterceptorthat checks the resolved version and sets the headers when it is the deprecated one.
Q73. "You need to log every request body for an audit requirement. Why does a naive filter break the controller, and what is the correct pattern?"
Reveal answer
Strong answer The request body is a stream read once from the socket.
A filter that calls request.getInputStream() and reads it to log it consumes the stream, and when the controller's @RequestBody converter reads it, the stream is empty and Jackson throws HttpMessageNotReadableException, so the client sees a 400 for a perfectly valid request.
The pattern is to wrap the request in a ContentCachingRequestWrapper, which copies bytes into a buffer as the real consumer reads them, and pass the wrapper down the chain; after chain.doFilter returns, the filter calls getContentAsByteArray() and logs it.
The same wrapper exists for the response, ContentCachingResponseWrapper, and you must call copyBodyToResponse() at the end or the client receives nothing. Boot's own CommonsRequestLoggingFilter does this with a size cap.
Two operational rules: cap what you log, because a 2 megabyte body per request at 500 requests per second is a gigabyte per second of log traffic, so log the first few kilobytes and the length; and never log bodies containing credentials or card data, which means the audit filter needs a per-endpoint allow list or a redaction step, and probably should write to a separate audit sink rather than the application log. For multipart uploads, do not cache at all.
// WHY THE NAIVE VERSION BREAKS: the request body is a one-shot InputStream.
// Reading it in a filter consumes it, so the controller receives an empty body
// and Jackson fails with "Required request body is missing".
// CORRECT — wrap the request so the bytes are cached and can be read twice.
@Component
public class AuditLoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws Exception {
var wrapped = new ContentCachingRequestWrapper(req);
try {
chain.doFilter(wrapped, res); // controller reads normally
} finally {
// Read AFTER the chain: the cache is only populated once the
// body has actually been consumed downstream.
byte[] body = wrapped.getContentAsByteArray();
log.info("{} {} body={}", req.getMethod(), req.getRequestURI(),
redact(new String(body, UTF_8)));
}
}
// Only log routes that need auditing, and cap the size — see Q74.
@Override protected boolean shouldNotFilter(HttpServletRequest r) {
return !r.getRequestURI().startsWith("/api/payments");
}
}
Read the finally block and the size cap together. The wrapper holds the whole body in heap for the request's lifetime, so logging every route without a limit is what doubles heap usage under load — which is exactly the incident in the next question.
Picture it a request body as a one-shot stream, the filter that drains it, and the same filter with a caching wrapper.
The setup: a filter that logs the body, in front of a controller with @RequestBody Payment p. The correct filter is the code below.
// ❌ TRAP: reads the one-shot stream
String body = new String(request.getInputStream().readAllBytes(), UTF_8);
log.info("body={}", body);
chain.doFilter(request, response); // controller now reads an empty stream
The trace: who reads the stream, in order:
naive: AuditFilter ──► readAllBytes() stream position at end, 214 bytes consumed
└─► chain.doFilter(request)
└─► Jackson converter reads body ✗ nothing left
wrapped: AuditFilter ──► new ContentCachingRequestWrapper(request)
└─► chain.doFilter(wrapped)
└─► Jackson reads body, wrapper copies bytes into its cache ✓
└─► finally: getContentAsByteArray() -> 214 bytes, logged ✓
What you see: the failure and the working result:
# illustrative output
naive: POST /api/payments -> 400
HttpMessageNotReadableException: Required request body is missing
wrapped: POST /api/payments -> 201
INFO AuditLoggingFilter : POST /api/payments body={"amount":10,"cardNumber":"****"}
Why: the container hands out the socket's bytes once; only a wrapper that copies them as the real reader consumes them can offer a second look.
The fix and what you see now: the wrapped version in the code below, which logs after chain.doFilter and caps what it keeps.
Land it The body is a one-shot stream, so wrap it to cache rather than read it, and log with a size cap and a redaction list.
- "Why is the body available only after
chain.doFilterreturns, and how do you log it when the controller fails?" ContentCachingRequestWrappercopies bytes into its buffer as they pass through its input stream, so before the controller reads, the buffer is empty; only after the converter has consumed the stream doesgetContentAsByteArray()hold anything. If I need the body before the handler, I must read it myself into memory and expose it through a wrapper with a replayable stream, which is what a manualbyte[]wrapper does at the cost of always buffering. When the controller throws,chain.doFilterstill returns after the exception resolvers have written the error response, so the filter's post-processing runs and the body is available; wrapping the call in a try-finally guarantees the log line even when the exception propagates past the resolvers to the container.- "How do you redact card numbers and passwords from the logged body without parsing every JSON body twice?"
Two layers. An allow list by endpoint: the filter has a set of path patterns where body logging is enabled, and payment and authentication endpoints are simply not in it, so their bodies are never buffered.
For endpoints that are logged, a redaction step runs on the byte array before it is written: a streaming pass with Jackson's
JsonParserthat copies tokens to aJsonGeneratorand replaces the value of any field whose name matches a deny list such aspassword,cardNumber,cvv,ssn, which is one pass and no object model.Regex on the raw text is the fallback for non-JSON bodies but misses nested structures. The redaction list lives in the platform starter so every service applies the same one.
- "Where should the audit records go, and what does 'separate sink' mean concretely?"
Audit records have different retention, access control, and integrity requirements from application logs: they may need to be kept for years, read only by compliance, and tamper-evident.
So they go to their own destination, an append-only table, an object storage bucket with versioning and a retention lock, or a dedicated Kafka topic consumed by an audit service.
In Boot the filter writes to a dedicated Logback logger named
AUDITwith its own appender and no propagation to the root, so the records do not mix with debug output, or better, calls anAuditEventRepositoryor publishes anAuditApplicationEventthat a separate component ships asynchronously.The application log is a debugging tool with short retention and broad access, which is the wrong place for an audit trail.
- "What is the cost of the wrapper on a request that is never logged, and how do you avoid it?"
The wrapper allocates a
FastByteArrayOutputStreamand copies every byte the controller reads, so the cost is a heap copy the size of the body plus the wrapper objects, for every wrapped request, whether or not anything is logged afterwards.For a 1 kilobyte JSON body that is nothing; for a 10 megabyte batch upload at 100 requests per second it is a gigabyte per second of copying and the memory in Q74.
Avoidance is deciding before wrapping: check the path allow list, the content type, and
getContentLengthLong()against a cap, and only then wrap; pass acontentCacheLimitso the buffer stops growing at the cap; and never wrap multipart or streaming endpoints.
Q74 · Scenario. "After deploying a request-logging filter, heap usage doubles and the service is OOM-killed under load. The filter only logs bodies at DEBUG level, which is off in production. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: memory grew with the filter deployed even though its logging is disabled, so the cost is in what the filter does before deciding whether to log.
- Evidence: a heap histogram showing
byte[]andContentCachingRequestWrapperorFastByteArrayOutputStreaminstances dominating; allocation profiling with async-profiler pointing at the wrapper. - Cause: the filter wraps every request in a caching wrapper unconditionally, so every body is copied into heap regardless of the log level; with large upload or batch bodies and 200 concurrent requests, that is hundreds of megabytes of copies held for the request's lifetime. A second common cause is building the log string with the full body eagerly,
log.debug("body=" + body), which concatenates before the level check. - Fix: only wrap when
log.isDebugEnabled()and the content type is JSON andgetContentLengthLong()is below a cap such as 64 kilobytes; use the wrapper'scontentCacheLimitconstructor argument so the buffer stops growing at the cap; skip multipart and streaming endpoints; and use parameterised logging so nothing is built unless the level is on. - Prevention: a load test that includes the largest realistic body, and heap dashboards in the canary stage so a doubling is caught before full rollout.
Picture it how many bytes sit in the heap when the wrapper is applied unconditionally, and what the heap histogram looks like before and after the fix.
The setup: a filter that wraps every request, and a batch endpoint receiving large bodies.
Make the invisible visible: the arithmetic and the histogram:
# illustrative output
200 concurrent requests x 5 MB body, each copied into a FastByteArrayOutputStream
= about 1 GB of byte[] live at once, plus the same again as garbage from the copies
class instances bytes
[B (byte[]) 812 1.1 GB
o.s.util.FastByteArrayOutputStream 200 ...
ContentCachingRequestWrapper 200 ...
The trace: the cost is paid before the level check:
AuditFilter ──► new ContentCachingRequestWrapper(request) ✗ always, whatever the log level
└─► chain.doFilter(wrapped) every byte read is also copied
└─► if (log.isDebugEnabled()) log(...) DEBUG off, copy already made, thrown away
The fix: decide before wrapping and cap the cache:
boolean wrap = log.isDebugEnabled()
&& request.getContentType() != null && request.getContentType().contains("json")
&& request.getContentLengthLong() >= 0 && request.getContentLengthLong() <= 65_536; // ✅ FIX
HttpServletRequest toUse = wrap ? new ContentCachingRequestWrapper(request, 65_536) : request;
chain.doFilter(toUse, response);
What you see now: the same load:
# illustrative output
[B (byte[]) no ContentCachingRequestWrapper instances in the histogram; heap back to its old level
http.server.requests unchanged; jvm.gc.memory.allocated drops to the pre-deploy rate
Land it Caching a body costs a copy whether or not you log it, so the wrap itself must be conditional and capped.
- "You made the wrapping conditional on DEBUG and the content length cap, and memory still climbs slowly over a day. What next?"
A slow climb over a day is a leak, not a per-request cost. I would take two heap dumps hours apart and compare dominators.
Candidates from a logging filter: a
ThreadLocalholding the last body per thread, which with virtual threads means one per request and never cleared; an MDC entry containing the body that is put but never removed, so it stays on pooled threads and accumulates in async appender queues; an async Logback appender with a large queue and a slow sink, whereAsyncAppender'squeueSizeof 256 is default but a custom one set to a million holds events in memory when the sink lags; or a request-scoped bean storing bodies with a lost destruction callback.The dump names the retaining class, and the fix is a finally block that clears whatever it is.
- "How exactly does
getContentLengthLong()help, and what about chunked requests?" It returns the
Content-Lengthheader as a long, or -1 when absent, before any of the body is read. A quick check against a cap such as 64 kilobytes lets the filter skip wrapping a large body entirely.Chunked transfer encoding has no content length, so the value is -1; for those I either skip logging, which is safe, or wrap with a
contentCacheLimitso the cache stops at the cap while the controller still reads the full stream.The limit constructor,
new ContentCachingRequestWrapper(request, 65536), makes the wrapper discard bytes beyond the limit rather than growing, and Spring 6.1 addedgetContentAsString(Charset)and made the limit reliable for the input stream path as well as the parameter path.- "Why does
log.debug("body=" + body)cost memory even at INFO, and what is the fix?" Java evaluates the argument before the call, so the concatenation runs and allocates the full string regardless of the level; Logback only then checks the level and discards it.
For a 1 megabyte body that is a megabyte of garbage per request, which is not a leak but a high allocation rate that raises GC pressure and heap usage under load.
The fix is parameterised logging,
log.debug("body={}", body), where the placeholder is filled only if the level is enabled, and for expensive arguments aSupplieror an explicitif (log.isDebugEnabled()).If the body is a byte array that must be decoded to a string, the decode itself must be inside the guard, since the parameterised form would still pass a decoded string.
- "What would the canary stage need to show to catch this before full rollout?"
A canary at 5 percent of traffic with the same request mix as production, including the large-body endpoints, watched for at least an hour with automatic comparison against the baseline:
jvm.memory.usedfor the heap,jvm.gc.pausecount and total, allocation rate fromjvm.gc.memory.allocated, and p99 latency. A doubling of heap or a 50 percent increase in allocation rate fails the canary automatically. The catch in this scenario is that a canary receiving only small requests would pass, so the canary must receive a representative slice, which usually means routing by hash of client rather than by endpoint, and the load test in CI must include the largest realistic body so the per-request cost is known before the canary.
Q75. "What is Boot's /error handling, when does a request end up there instead of in your advice, and how do you make it return JSON consistently?"
Reveal answer
Strong answer Boot registers an ErrorPageFilter and an error page mapping so that any error the servlet container sees, meaning an exception that escaped every filter and resolver, a sendError call from a filter such as Security, or a 404 for an unmapped path, is forwarded internally to /error.
There, BasicErrorController renders either an HTML "Whitelabel Error Page" for browsers or a JSON map with timestamp, status, error, and path for API clients, using the ErrorAttributes bean; server.error.include-message, include-stacktrace, and include-binding-errors control detail, and they default to never in production precisely so stack traces do not leak.
Requests land there rather than in your advice when the failure occurred outside the DispatcherServlet: a filter threw, Security called sendError(401), Tomcat rejected a malformed request, the async timeout fired, or the path matched no handler and spring.mvc.throw-exception-if-no-handler-found is false (Boot 3.2 and later default it to true, so 404s now reach the advice as NoResourceFoundException).
To make everything JSON in one shape: extend ResponseEntityExceptionHandler in the advice for MVC errors, configure Security's entry point and denied handler for the security errors, and replace ErrorAttributes with a custom bean, or register your own ErrorController, that emits the same ProblemDetail fields for whatever still falls through.
Turn off the whitelabel page with server.error.whitelabel.enabled=false so an API service never emits HTML.
Picture it the three routes a failing request can take, and the different bodies the client gets from the advice and from /error.
The setup: a JSON API with a @ControllerAdvice, Spring Security, and no custom ErrorController.
The trace: which path each failure takes:
controller throws OrderNotFound ──► DispatcherServlet ──► @ControllerAdvice ──► ProblemDetail JSON ✓ advice
filter throws / Security sendError(401) ──► container sees error status
└─► ERROR dispatch to /error ──► BasicErrorController ✗ not your advice
Tomcat rejects a malformed request ──► container ──► /error ──► BasicErrorController
What you see: two different bodies from the same API:
# illustrative output
from the advice: 404 {"type":"about:blank","title":"Not Found","status":404,"detail":"order 42"}
from /error (JSON): 401 {"timestamp":"2026-09-12T10:03:00.000+00:00","status":401,"error":"Unauthorized","path":"/api/orders"}
from /error (HTML): 401 <html>... Whitelabel Error Page ... (Accept: text/html or */*)
Why: failures born outside the DispatcherServlet never see your advice, so the container's error page, /error, answers them.
The fix: one shape, and no HTML:
server.error.whitelabel.enabled=false
server.error.include-stacktrace=never
server.error.include-message=never
# plus an ErrorController or ErrorAttributes bean that emits ProblemDetail fields
What you see now: every route returns the same fields:
# illustrative output
401 Content-Type: application/problem+json {"type":"about:blank","title":"Unauthorized","status":401,"detail":"authentication required","instance":"/api/orders"}
Land it The error controller is the last resort for failures born outside MVC, so give it the same problem shape as the advice and keep stack traces off.
- "How does
BasicErrorControllerdecide between HTML and JSON, and how do you force JSON?" It has two handler methods on
/error: one withproduces = "text/html"that renders the whitelabel page or anerror/view, and a fallback that returns aResponseEntity<Map>serialised as JSON. Content negotiation on theAcceptheader picks between them, so a browser gets HTML and a client sendingAccept: application/jsongets JSON, but a client sendingAccept: */*or nothing can get HTML. To force JSON:server.error.whitelabel.enabled=falseremoves the HTML view, but the HTML handler still exists and can produce a container error page; the reliable approach is a customErrorControllerbean with a single@RequestMapping("/error")producing JSON, or anErrorViewResolverthat returns null, so the JSON path is the only path. Boot'sErrorAttributescustomisation controls the fields either way.- "What are the
ErrorAttributesfields exactly, and how do you get aProblemDetailshape out of that path?" DefaultErrorAttributesproducestimestamp,status,error(the reason phrase),path, and optionallymessage,exception,trace, anderrorsfor binding failures, controlled byserver.error.include-*properties, each withnever,always, oron-param.To get a problem shape, I declare a bean extending
DefaultErrorAttributesand overridegetErrorAttributes(WebRequest, ErrorAttributeOptions)to return a map withtype,title,status,detail, andinstancebuilt from the same request attributes, reading the exception withgetError(webRequest).Then the custom error controller sets the content type to
application/problem+json. That makes a filter exception, a 404, and an advice-handled exception look the same to a client.- "What is the
ErrorPageFilterfor, and does it apply with an embedded server?" ErrorPageFilterexists for the WAR deployment case: on an external servlet container, Boot cannot register error pages through the embedded server factory, so the filter interceptssendErrorand exceptions and forwards to/erroritself.With the embedded Tomcat, Boot registers a real container error page for
/errorviaErrorPageRegistrar, and Tomcat's own error valve performs the forward; the filter is not registered.The distinction matters when debugging: with embedded Tomcat, the forward to
/erroris an ERROR dispatch, and filters run again for it unless their registration excludes the ERROR dispatcher type, which is why a logging filter can log a request twice and whyOncePerRequestFilterskips error dispatches by default.- "Security calls
sendError(401). Does that go to/error, and how do you stop the whitelabel page leaking there?" Yes: the default
HttpStatusEntryPointorBasicAuthenticationEntryPointcallresponse.sendError(401), Tomcat sees the error status with an empty body and dispatches to the/errorpage, andBasicErrorControllerrenders the result, which for a browser-likeAcceptheader is the whitelabel HTML with the status and timestamp.That is how a JSON API ends up returning HTML for 401.
The stop is either to make the error controller JSON-only as above, or to give Security an entry point that writes the body itself and never calls
sendError, as in Q50, so the container never dispatches.entry point sendErrorruns offline# illustrative output BasicAuthenticationEntryPoint -> response.sendError(401) -> container ERROR dispatch to /error -> BasicErrorController -> 401 Content-Type: text/html (Whitelabel page for a browser-like Accept)The second is better because the entry point can also set
WWW-Authenticatecorrectly. Also ensure/erroris permitted in the security chain, otherwise the error dispatch itself is rejected and the client gets a bare container 401.
Q76 · Scenario. "A support ticket includes a screenshot of your API returning a full stack trace with internal class names and an SQL fragment. Which settings are wrong, and what else do you check?"
Reveal answer
Strong answer In diagnosis order:
- Symptom: internal detail in an error response. Two different paths can leak: Boot's error attributes, or an exception handler that puts
ex.getMessage()or the cause into the response body. - Evidence: the response shape tells you which. A
tracefield with atimestampandpathmeansserver.error.include-stacktrace=alwaysis set, probably from a development profile that became active in production; adetailfield containing the SQL means your advice copied aDataAccessExceptionmessage intoProblemDetail.detail. - Fix the settings:
include-stacktrace=never,include-message=neveroron-paramat most,include-exception=false. Fix the advice: a catch-all handler forExceptionandDataAccessExceptionthat logs the full exception with a generated error id and returns a genericProblemDetailwhosedetailis "unexpected error, reference 5f3a…", so support can find the log without the client seeing internals. Keep specific handlers with safe messages for domain exceptions. - Then check what else the same profile mistake exposed:
spring.jpa.show-sql, Actuator exposure,debug=true, and H2 console if present. Check whether the leak is reachable by unauthenticated users and whether any of the stack revealed a library version with a known vulnerability. - Prevention: production profile values pinned in the platform starter, a contract test that asserts every error response matches the ProblemDetail schema and contains no
tracefield, and a rule that exception messages are never sent to clients unless the exception type is on an allow list.
Picture it the leaked response next to the response after the fix, and how the field names show which leak path produced it.
The setup: a request that triggers a DataAccessException.
What you see: the two leak shapes, and the fixed response:
# illustrative output
leak 1, Boot error attributes (include-stacktrace=always):
{"timestamp":"...","status":500,"error":"Internal Server Error","trace":"org.springframework.dao.DataIntegrityViolationException: ... \n\tat com.shop.orders.OrderRepo...","path":"/orders"}
leak 2, your own advice copied ex.getMessage():
{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"could not execute statement [... SQL ...]","instance":"/orders"}
after the fix:
{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"Unexpected error, reference 5f3a91c2","errorRef":"5f3a91c2"}
Why: the first comes from a property, the second from code; the shape of the JSON tells you which.
The fix: a catch-all that keeps the detail in the log:
@ExceptionHandler(Exception.class)
ProblemDetail unexpected(Exception ex) {
String ref = UUID.randomUUID().toString().substring(0, 8);
log.error("unhandled error ref={}", ref, ex); // full detail stays in the log
var pd = ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
"Unexpected error, reference " + ref);
pd.setProperty("errorRef", ref);
return pd; // ✅ FIX: client gets only the reference
}
| Symptom in the screenshot | Root cause | Action |
|---|---|---|
trace key present | include-stacktrace=always | Set to never, find the profile that set it |
SQL in detail | Advice copied ex.getMessage() | Generic handler plus error reference |
| Whitelabel HTML with trace | /error HTML view, property on | Disable whitelabel, same property fix |
Land it A leaked stack trace is a profile mistake or a copied message, and the durable fix is an error id in the response and the detail only in the log.
- "How do you prove which of the two leak paths it was, from the screenshot alone?"
I read the field names. Boot's
DefaultErrorAttributesproduces a fixed shape:timestamp,status,error,path, and, only when enabled,message,exception, andtrace. If the screenshot shows atracekey with a multi-line stack, that isserver.error.include-stacktrace=alwaysand the request never reached my advice.If instead the shape is RFC 9457 ProblemDetail, meaning
type,title,status,detail,instance, then my own@ControllerAdvicebuilt it and the SQL sits indetailbecause someone passedex.getMessage()in.A third giveaway is the content type: Boot's fallback often returns
text/htmlfor a browserAcceptheader, and that Whitelabel HTML page also shows the trace when the property is on.I would then reproduce it in staging with
curl -H "Accept: application/json"against the same route.- "Why would a development profile be active in production at all?"
The usual routes are all configuration precedence accidents. Someone sets
SPRING_PROFILES_ACTIVE=devin the base Dockerfile as a convenience and the production manifest never overrides it.Or the jar contains
application-dev.ymland aspring.profiles.include=devline in the sharedapplication.yml, which cannot be switched off by a later active-profile setting becauseincludeis additive. Or abootstrap.ymlleft over from Spring Cloud sets it.I verify with
/actuator/envon the management port, which listsactiveProfilesat the top, and with the startup log line "The following 1 profile is active".As of Aug 2026 the fix I standardise on is that the jar contains no profile-specific file for anything except
local, and the platform starter'sEnvironmentPostProcessorfails startup ifdevorlocalis active whileKUBERNETES_SERVICE_HOSTis set.- "Is a leaked stack trace actually dangerous, or is this just tidiness?"
It is reconnaissance for free. A stack trace reveals the framework and its version from package names such as
org.hibernate.orm 6.6ororg.apache.catalina, which an attacker maps straight onto a CVE list.It reveals internal class and method names, which tell them how the code is structured and which endpoints share a service. An SQL fragment reveals table and column names, which turns a blind injection attempt into a targeted one.
A
messagefrom aDataIntegrityViolationExceptioncan even reveal another user's data in a constraint value.So the risk is real, and the write-up to the security team should say the exposure window, which routes were affected, whether unauthenticated users could trigger it, and whether the disclosed versions have known vulnerabilities.
If they do, the patch becomes the priority above the setting change.
- "What does the generic handler look like so support can still find the real error?"
The handler generates a short identifier, logs the full exception under it, and returns only the identifier to the client.
Concretely, a
@ExceptionHandler(Exception.class)method doesString ref = UUID.randomUUID().toString().substring(0, 8), thenlog.error("unhandled error ref={}", ref, ex), then returnsProblemDetail.forStatusAndDetail(INTERNAL_SERVER_ERROR, "Unexpected error, reference " + ref)with a propertyerrorRefset to the same value.Because the MDC already carries
traceId, the log line links to the trace too. Support pastes the reference into the log search and finds the stack and the trace in seconds, while the client learned nothing.I also keep a small allow list of exception types whose messages are safe to forward, such as validation and not-found, and everything else goes through the generic path.
Q77. "A client disconnects mid-request. What does your Boot service do with the work in progress, and how do you set a server-side deadline for a slow handler?"
Reveal answer
Strong answer For a normal blocking handler, nothing happens on disconnect: the Tomcat thread keeps running the controller to completion, the database query keeps running, and only when the handler writes the response does the write fail with a ClientAbortException, which Boot's error handling logs quietly.
So a client that times out at 5 seconds and retries has doubled your load while the original request still runs. Mitigation: pass a deadline into the work.
For database work, @Transactional(timeout = 5) sets a statement timeout on the connection through the JDBC driver, so a query cannot outlive the deadline; for outbound HTTP, the client's read timeout does the same.
For a true cancellable deadline, run the handler asynchronously: return a Callable, a DeferredResult, or a CompletableFuture, which frees the Tomcat thread and puts the request into servlet async mode; then spring.mvc.async.request-timeout=5000 fires an AsyncRequestTimeoutException after 5 seconds, which your advice maps to 503 or 504, and the DeferredResult.onTimeout and onCompletion callbacks let you cancel the underlying future or upstream call.
On WebFlux, cancellation is native: a client disconnect cancels the subscription and the chain propagates it to WebClient, which closes the upstream connection. Either way, an interviewer wants to hear that "the client gave up" does not free anything unless your code is written to notice.
Picture it a timeline of one abandoned request, what each side believes at each moment, and the same request with a deadline.
The setup: a client with a 5 second timeout that retries once, calling a handler that takes 12 seconds.
The trace: what happens on the server:
# illustrative output
t=0s client sends request A Tomcat thread exec-7 starts the handler, query runs
t=5s client times out, closes socket server is not told; exec-7 and the query keep going ✗
t=5s client retries as request B exec-8 starts the same work ✗ load doubled
t=12s exec-7 writes the response ClientAbortException: Broken pipe (first time the server learns)
http.server.requests records A as 200, 12 s
The fix: pass a deadline so the work stops: a transaction timeout for the database, and an async timeout for a cancellable request.
@GetMapping("/report")
DeferredResult<Report> report() {
var result = new DeferredResult<Report>(5_000L); // ✅ FIX: 5 s deadline, thread released
var future = service.generateAsync(result); // Tomcat thread is free now
result.onTimeout(() -> future.cancel(true)); // stop the work, then advice maps to 503
return result;
}
What you see now: the same scenario:
# illustrative output
t=0s request A accepted, Tomcat thread released immediately
t=5s AsyncRequestTimeoutException -> 503, future cancelled, query cancelled ✓
client retry B starts clean; nothing from A is still running
| Mechanism | Outcome |
|---|---|
| Client disconnects, blocking handler | Silently not applied until the write fails |
@Transactional(timeout = 5) | Works for statements; does not stop an outbound HTTP call inside |
spring.mvc.async.request-timeout with DeferredResult | Throws AsyncRequestTimeoutException after 5 seconds |
Going deeper The transaction timeout is not a database statement timeout.
Spring records a deadline on the transaction; JdbcTemplate and Hibernate apply the remaining seconds as Statement.setQueryTimeout on each statement they create, so a query that starts late in the transaction gets a shorter budget, and a statement already waiting on a row lock is cancelled by the driver when its timeout fires.
What it cannot interrupt is Java code between statements, an outbound HTTP call inside the transaction, or a wait on the connection pool.
For a hard database-side limit you also set statement_timeout on the PostgreSQL role or as a connection-init statement, and for lock waits lock_timeout, so the deadline holds even for code paths that bypass Spring's bookkeeping.
Land it Blocking handlers run to the end regardless of the client, so put the deadline on the transaction and the outbound call, and go async when you need real cancellation.
- "How would you verify in production that abandoned requests are actually still running?"
Two signals side by side. The ingress or load balancer logs show the client-side outcome, typically a 499 in nginx meaning the client closed the connection, or a 504 from the balancer's own timeout.
The application's
http.server.requeststimer still records those same requests as completed with a 200 and a duration longer than the client's timeout, because Tomcat only learns the client is gone at write time.So I chart the count of nginx 499s against the count of application requests over 5 seconds, and if they track each other, the abandoned work is running to completion.
A thread dump during a spike confirms it: worker threads deep in a repository call for a request whose client hung up 20 seconds ago. Tomcat also logs
ClientAbortException: Broken pipeat DEBUG on the write, which I can enable briefly on one pod.- "With virtual threads enabled, does any of this change?"
The cost model changes but the semantics do not.
Under
spring.threads.virtual.enabled=true, each request gets a cheap virtual thread instead of one of 200 platform threads, so an abandoned request no longer consumes a scarce worker; it consumes a few kilobytes of heap and, more importantly, a pooled database connection or a downstream call slot while it finishes.So the thread pool stops being the thing that fills up, and the connection pool and the bulkheads become the ceiling instead. The blocking handler still runs to completion, and Tomcat still discovers the disconnect only when it writes.
Deadlines therefore matter more, not less, because virtual threads let you accept far more abandoned work before anything visibly refuses. The async
DeferredResultpath with a timeout, or a per-request deadline passed to the transaction and the client, remains the way to actually stop work.- "Where do you put the deadline so that every layer respects it?"
I carry a single absolute deadline through the request rather than separate timeouts per layer.
A filter computes
Instant deadline = now.plusMillis(budget)from a configured budget, or from an inboundX-Request-Deadlineheader on internal calls, and stores it in a request-scoped holder or aScopedValueon Java 21 and later.Each outbound
RestClientcall computes the remaining time and sets it as the read timeout through a per-requestClientHttpRequestFactorysetting, or refuses immediately if nothing remains. The transaction layer does the same by callingTransactionTemplate.setTimeoutwith the remaining seconds instead of a fixed annotation value.The reason to use one absolute deadline is arithmetic: three sequential calls with 2-second timeouts each can take 6 seconds against a 3-second client, whereas a shared deadline guarantees the total.
- "What HTTP status should the async timeout produce, and why not 500?"
I map
AsyncRequestTimeoutExceptionto 503 Service Unavailable with a shortRetry-After, because it tells the truth: the service could not complete the work in time, the request was not malformed, and a later retry may succeed.Spring's
ResponseEntityExceptionHandleralready does this mapping when you extend it, producing a ProblemDetail with status 503.A 500 says "we have a bug", which misleads dashboards and triggers the wrong alerts, and a 504 implies a gateway timed out on an upstream, which is only accurate if this service is acting as a proxy.
The status also shapes client behaviour: well-written clients and ingress controllers retry idempotent requests on 503 with backoff and do not retry on 500.
I also count timeouts separately with a tagged metric so a rise in 503s from deadlines is distinguishable from a rise in 503s from load shedding.
Q78 · Design. "Design an API for a report that takes up to 10 minutes to generate, callable by clients that time out at 30 seconds, with retries that must not start duplicate generations."
Reveal answer
Strong answer Requirements: the request must return quickly, the client must be able to poll or be notified, a retry must attach to the existing job, and the work must survive a pod restart. Design: the asynchronous request-reply pattern.
POST /reports with an Idempotency-Key validates the parameters, inserts a report_job row in state QUEUED with the parameters and the key (unique constraint on the key, so a retry gets the existing row back), and returns 202 Accepted with a Location: /reports/{id} header and a body containing the job id and a suggested poll interval.
Generation runs outside the request: a Kafka message or a database-backed queue triggers a worker, in the same service or a separate deployment, which claims the row with UPDATE ... WHERE state = 'QUEUED' using SKIP LOCKED so two workers cannot both take it, sets RUNNING with a heartbeat timestamp, writes the output to object storage, and marks DONE with the URL, or FAILED with a reason.
GET /reports/{id} returns the state, progress if known, and on completion a 303 See Other to the download URL or the pre-signed link inline. A stale RUNNING row with an old heartbeat is requeued by a scheduled sweeper, which is how a pod restart is survived.
Optionally a webhook or SSE stream notifies the client. Jobs and outputs expire after 7 days. Trade-offs: the client does two calls instead of one, which is the honest shape of a 10-minute operation.
What I would not do: hold the HTTP connection open with a long async timeout, because load balancers and clients will cut it and the retry storm begins; or run the generation in an @Async method with no persistence, because a restart loses the job silently.
Picture it the call sequence, the job row at each moment, and the retry that attaches to the existing job.
The setup: a client that times out at 30 seconds retries POST /reports with the same Idempotency-Key.
The trace: the calls and what the client sees:
Client ──► POST /reports Idempotency-Key: k-1
└─► insert report_job(key=k-1, state=QUEUED) ✓ 202 Accepted, Location: /reports/17
Client ──► POST /reports Idempotency-Key: k-1 (retry after a timeout)
└─► insert violates unique(key) ──► return existing row ✓ 202, Location: /reports/17 (no second job)
Worker ──► UPDATE ... FOR UPDATE SKIP LOCKED claims job 17, state=RUNNING
Client ──► GET /reports/17 200 {"state":"RUNNING"} ... later 303 See Other to download ✓
What you see: the job table through the lifetime of one report:
# illustrative output
id | key | state | attempts | claim_version | heartbeat
17 | k-1 | QUEUED | 0 | 0 | -
17 | k-1 | RUNNING | 1 | 1 | 10:03:10
17 | k-1 | RUNNING | 1 | 1 | 10:04:10 (worker died after this)
17 | k-1 | QUEUED | 1 | 1 | 10:04:10 sweeper requeues at 10:05:10 (stale 60 s)
17 | k-1 | DONE | 2 | 2 | url=s3://reports/17.pdf
| Symptom | Root cause | Action |
|---|---|---|
| Two reports for one click | No unique idempotency key | Unique constraint on the key, return the existing row |
Job stuck in RUNNING forever | Pod crashed, nothing requeues | Heartbeat plus sweeper, bounded attempts |
| Two workers on one job | Read then write claim | Single-statement claim with SKIP LOCKED, fencing token |
Land it Anything longer than a client's patience becomes a resource with an id, a state, and a poll URL, and the idempotency key is what makes retries attach instead of duplicate.
- "The requirement changes: clients now need the report inline and cannot poll. What do you do?"
Then I separate "start" from "wait" but keep one round trip for the common case.
The
POSTstill creates the job and returns immediately, but the client can passPrefer: wait=25, the RFC 7240 header, and the server holds the request for up to 25 seconds using aDeferredResult, completing it with the finished report if the job completes in time, or with 202 and theLocationif not.That keeps the connection inside the client's 30-second budget with margin for the balancer. For reports that typically take under 20 seconds this satisfies most calls inline, and the long ones fall back to the resource-with-an-id shape.
If the client truly cannot handle 202 at all, the remaining options are a webhook they register, or a pre-computed report refreshed on a schedule so the request is a read. What I would refuse is raising the balancer timeout to 10 minutes.
- "Two workers claim the same job anyway. How could that happen and how do you make the claim safe?"
It happens when the claim is a read followed by a write in separate statements, or when the sweeper requeues a job whose worker is alive but slow to heartbeat.
The safe claim is one statement:
UPDATE report_job SET state = 'RUNNING', worker = ?, heartbeat = now() WHERE id = (SELECT id FROM report_job WHERE state = 'QUEUED' ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) RETURNING *.The row lock plus
SKIP LOCKEDmeans two workers never select the same row, and the update is the claim.For the sweeper, I use a fencing token: each claim increments a
claim_versioncolumn, the worker carries its token, and every later write by that worker includesWHERE claim_version = ?, so a worker that was declared dead but wakes up finds its writes affect zero rows and stops.Heartbeat interval at 10 seconds and stale threshold at 60 gives six missed beats before requeue.
- "What would you cut if you had two days instead of two weeks?"
I would keep the parts that protect correctness and cut the parts that improve experience. Keep: the
report_jobtable with the unique idempotency key, the 202 withLocation, the pollingGET, and the single-statement claim, because those are what stop duplicate generation and lost jobs.Cut: the webhook and SSE notification, the progress percentage, and the separate worker deployment; the worker can be a
@Scheduledpoller in the same service under a ShedLock guard, and a Kubernetes-managed restart of the pod still resumes from the table.Also cut object storage on day one by storing the report as a
byteaor a file on a mounted volume if reports are under a few megabytes, with a note to move it.The sweeper for stale
RUNNINGrows stays, because a crashed pod otherwise leaves jobs stuck forever, and that is the first bug users would report.- "How does the client know the difference between 'still running' and 'the job was lost'?"
Through explicit states and timestamps on the resource, never through absence. The
GETreturnsstate,createdAt,startedAt,lastHeartbeat, andattempts. A job inRUNNINGwith a heartbeat in the last minute is healthy.A job in
QUEUEDfor longer than the expected queue delay means workers are behind, and I expose the queue depth as a metric to see it fleet-wide.A job the sweeper has requeued shows
attempts: 2, and after a bounded number of attempts, say three, it moves toFAILEDwith a reason such as "worker died repeatedly", so the client sees a terminal state rather than waiting forever.A
GETfor an unknown id returns 404 only after the 7-day retention, and before that returns the terminal record. The rule is that every id the client was ever given resolves to a state until retention ends.
Q79. "Which server-side HTTP settings do you actually tune on embedded Tomcat in production, and what does each protect against?"
Reveal answer
Strong answer A short list, each with a reason:
- Pool size:
server.tomcat.threads.maxandthreads.min-sparesize the worker pool as in Q45. - Sockets:
server.tomcat.max-connections, default 8,192, caps open sockets, which bounds memory per connection. With virtual threads it becomes the effective concurrency limit and may need raising for streaming workloads. - Backlog:
server.tomcat.accept-countsizes the kernel backlog, which decides whether a burst queues briefly or is refused. - Slow headers:
server.tomcat.connection-timeout, default 60 seconds in Boot, is how long Tomcat waits for a client to send the request line and headers after connecting. Lowering it to 5 to 10 seconds is the defence against slow-header attacks that hold connections open by sending one byte a minute. - Keep-alive:
server.tomcat.keep-alive-timeoutandmax-keep-alive-requestscontrol idle connection reuse behind a load balancer. Keep-alive should be slightly longer than the balancer's idle timeout to avoid races where the balancer reuses a connection the server just closed. - Sizes:
server.max-http-request-header-size, default 8 kilobytes, needs raising only for large tokens or cookies, and lowering is a cheap protection.server.tomcat.max-swallow-sizelimits how much of an aborted upload Tomcat will read to keep the connection. - Compression and HTTP/2:
server.compression.enabledwith a min size of a kilobyte trades CPU for bandwidth, andserver.http2.enabledis worthwhile only when the service terminates TLS itself, since most deployments terminate at the ingress. - Proxy headers:
server.forward-headers-strategy=nativeorframeworkmakes the service trustX-Forwarded-*headers from the proxy so generated URLs and the scheme are right.
Picture it each setting with the abuse or failure it bounds, and one live check that proves a value took effect.
The setup: an embedded Tomcat behind a load balancer with a 60 second idle timeout.
server:
tomcat:
threads.max: 200
max-connections: 8192
accept-count: 100
connection-timeout: 5s # slow-header attack
keep-alive-timeout: 75s # longer than the balancer's 60 s idle
max-http-request-header-size: 8KB
forward-headers-strategy: native
| Setting | Protects against |
|---|---|
connection-timeout | Clients that connect and send a byte a minute |
max-connections | Unbounded sockets and their memory |
accept-count | A burst turning into a long invisible queue |
keep-alive-timeout | 502 races when the balancer reuses a connection Tomcat closed |
max-http-request-header-size | Oversized headers and cookies |
What you see: a slow-header probe, before and after lowering connection-timeout:
# illustrative output
$ time nc api.shop.example 8080 (type nothing)
before: Connection closed by foreign host real 60.0 s
after: Connection closed by foreign host real 5.0 s
Land it Threads and connections set capacity, connection-timeout and header size limit abuse, and keep-alive must be tuned against the load balancer rather than in isolation.
- "Why does keep-alive need to be longer on the server than on the load balancer, and what happens if it is the other way round?"
Because whichever side closes an idle connection first creates a race for the other side.
If Tomcat's
keep-alive-timeoutis 20 seconds and the balancer's idle timeout is 60, the balancer believes a connection is reusable at second 21, sends a request on it, and Tomcat has already closed the socket, so the balancer sees a reset or an empty reply and reports a 502 to the user.keep-alive raceruns offline# illustrative output t=20s Tomcat closes the idle connection (keep-alive-timeout 20 s) t=21s balancer sends request on that connection (its idle timeout is 60 s) ✗ reset, empty reply -> balancer returns 502 for one request out of a few hundredThat is exactly the 0.3 percent of intermittent errors people chase for weeks. If the server's timeout is longer, the balancer closes first, and since the balancer never sends on a connection it has closed, there is no race.
So the rule is server keep-alive greater than balancer idle timeout plus a margin: AWS ALB defaults to 60 seconds, so I set Tomcat to 75. The same rule applies one hop further out between the ingress and the ALB.
- "How would you verify these settings took effect on a running pod?"
I look at the running Tomcat, not the properties file. The
/actuator/configpropsendpoint shows the boundserver.tomcat.*values, which tells me what Boot intended to apply.To see what Tomcat actually has, I use JMX:
jcmd <pid> ManagementAgent.startor the Actuator JMX exposure, then theTomcat:type=ThreadPool,name="http-nio-8080"MBean showsmaxThreads,maxConnections,connectionTimeout,keepAliveTimeout, andacceptCountlive.Behaviourally, I test connection-timeout with
nc host 8080, type nothing, and time how long until the server closes the socket. For keep-alive,curl -vwith two requests on one connection and a sleep between them shows whether the second reused the connection. The Tomcat metricstomcat.threads.busyandtomcat.connections.currentconfirm behaviour under load.- "What breaks at ten times the traffic if you tuned only these?"
The settings bound abuse and set capacity, but they do not create capacity, so at ten times the load the first thing that breaks is whatever sits below Tomcat.
With 200 threads and a 10-connection database pool, requests queue for connections long before threads run out, so the failure looks like slow responses and
SQLTransientConnectionException, not connection refusals.If I raised
threads.maxto 2,000 to compensate, I would just move the queue into the JVM and pay 2 gigabytes of stack.The honest ten-times plan is horizontal: more pods behind the balancer, each with these same small numbers, plus load shedding at the front so that overload is a fast 503 rather than a slow timeout.
accept-countmatters here, because a large backlog silently queues seconds of requests the client has already given up on; I keep it around 100 so excess is refused visibly.- "When would you put a reverse proxy in front instead of tuning Tomcat?"
Whenever the service is reachable from clients I do not control.
Nginx or Envoy buffers the entire request before opening a connection to Tomcat, so a slow-header or slow-body attacker ties up a cheap event-loop slot in the proxy instead of a Tomcat worker thread, and Tomcat only ever sees complete requests.
The proxy also does TLS termination, HTTP/2 and HTTP/3 to the client with plain HTTP/1.1 to the service, request size limits, and connection limits per client address, none of which Tomcat does as well.
In Kubernetes this is the ingress controller, so the answer is usually already true, and my Tomcat tuning then targets the proxy as the client: keep-alive above the proxy's idle timeout,
forward-headers-strategy=nativeto trustX-Forwarded-ForandX-Forwarded-Proto, and a connection-timeout that only needs to defend against the proxy's own idle behaviour.
Q80 · Scenario. "Tomcat shows 8,000 open connections and 190 busy threads, but the application's request timer says requests complete in 20 ms. The service is nearly unresponsive. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the application says it is fast while the server says it is saturated. The time is being spent before the request is handed to the application: in reading headers or bodies, or in connections that never send a complete request.
- Evidence: a thread dump shows worker threads in Tomcat's
Http11Processor.servicereading the input buffer rather than in application code;ss -tnshows thousands of established connections from a small set of client addresses with small send queues; the request timer only measures from dispatch to completion, so it cannot see this. - Likely causes, ranked: a slow-request attack or a misbehaving client that opens connections and sends bytes very slowly, holding a thread per connection through the 60-second
connection-timeout; a client library with a bug that opens a connection per request and never completes; a load balancer health check misconfigured to open connections without closing them; or, if the connections are from your own gateway, a keep-alive mismatch where the gateway holds idle connections and Tomcat'smax-connectionsfills with idle sockets while the busy threads are genuine. - Fix: lower
server.tomcat.connection-timeoutto 5 seconds so a connection that has not sent a full request is dropped; setserver.tomcat.max-keep-alive-requestsand a keep-alive timeout matched to the balancer; block or rate-limit the offending source at the ingress; and, since a single Tomcat cannot distinguish slow attackers from slow mobile clients well, put a reverse proxy that buffers requests in front so Tomcat only ever sees complete requests. - Prevention: alert on
tomcat.connections.currentand on the ratio of busy threads to request rate, which is the shape that exposes "busy but not serving".
Picture it the numbers from the dashboards, the thread dump and the socket list for a server that is busy but not serving, and a table from symptom to action.
The setup: the service is nearly unresponsive while the application timer reads 20 ms.
What you see: the three views that disagree:
# illustrative output
http.server.requests mean 20 ms (starts at DispatcherServlet)
tomcat.connections.current 8,000
tomcat.threads.busy 190 of 200
completed requests per second 12
thread dump:
"http-nio-8080-exec-41" RUNNABLE org.apache.coyote.http11.Http11InputBuffer.fill
"http-nio-8080-exec-42" RUNNABLE org.apache.coyote.http11.Http11InputBuffer.fill
ss -tn ESTAB 6,900 connections from 3 client addresses, Send-Q 0
The trace: where the time goes:
Client ──► opens socket, sends "GET /ord" then waits
└─► Tomcat worker thread blocked reading the request line ✗ thread held up to connection-timeout (60 s)
DispatcherServlet ──► never called, so the application timer never starts
| Symptom | Root cause | Action |
|---|---|---|
| Busy threads high, request rate low | Threads parked on incomplete requests | Lower connection-timeout, buffering proxy in front |
| Connections high, threads idle | Idle keep-alive sockets | Tune keep-alive-timeout and max-keep-alive-requests |
Threads in CoyoteInputStream.read | Trickled request bodies | Proxy that buffers bodies with a body timeout |
Sockets in CLOSE_WAIT | Application not closing a stream | Look for a filter that consumes the stream |
Land it When the server is busy and the application is fast, the time is in connection handling, and connection-timeout plus a buffering proxy are the controls.
- "You lowered connection-timeout to 5 seconds and the connection count barely moved. What next?"
Then the connections are not idle-before-request; they are established and doing something, or they are idle keep-alives that the timeout does not cover.
The
connection-timeoutonly applies while Tomcat waits for the request line and headers of a new request, so idle keep-alive connections are governed bykeep-alive-timeoutinstead, and connections with a slow body upload are governed by neither once the headers are read.So I re-check the thread dump for where the 190 busy threads are: if they sit in
CoyoteInputStream.read, clients are trickling request bodies, and the defence is a proxy that buffers bodies with a body timeout.If the count is high but threads are idle, they are keep-alive connections, and
keep-alive-timeoutplusmax-keep-alive-requestsis the lever.And if
ss -tnshows the sockets are inCLOSE_WAIT, the application is not closing something, which is a leak in a filter that consumes the stream.- "How do you distinguish an attack from a legitimately slow client population?"
By distribution and by identity. Legitimate slow clients, mobile users on poor networks, spread across thousands of source addresses, spread across all routes, and each holds one or two connections; their request completion times form a long tail but they do complete.
An attack concentrates: a handful of source addresses or one autonomous system, hundreds of connections each, a single cheap route, and requests that never complete.
I get that view from the ingress access logs grouped by client address and from
ss -tn | awkon the pod grouped by peer.The Tomcat metric
tomcat.connections.currentversushttp.server.requestscount tells me the ratio of connections to completed requests, which for real traffic is close to one and for slow-connection abuse is far above.Once identified, the block belongs at the ingress or WAF by address and rate, not in Tomcat.
- "Why did the request timer miss this, and what metric would have caught it?"
http.server.requestsstarts its timer when theDispatcherServletreceives the request, which is after Tomcat has parsed the request line and headers, so any time spent waiting for those bytes is invisible to it. It also never records connections that fail to become requests at all.The metrics that see the earlier phase are Tomcat's own:
tomcat.connections.currentandtomcat.connections.keepalive.current,tomcat.threads.busyagainsttomcat.threads.config.max, and the ratio of busy threads to request throughput.The shape that should page is "busy threads near max while completed requests per second is low", which is the definition of threads occupied by non-requests.
I add that ratio as a recording rule in Prometheus and alert when it stays above a threshold for two minutes, alongside the ingress's upstream connect time and upstream response time histograms, which show the same problem from outside.
- "Would virtual threads have prevented this?"
They would have hidden it for longer, which is not the same as preventing it. With
spring.threads.virtual.enabled=true, Tomcat spawns a virtual thread per connection, so 8,000 slow connections cost 8,000 cheap threads instead of exhausting 200 workers, and the service would keep serving real requests.But
server.tomcat.max-connections, default 8,192, still caps sockets, so a determined attacker simply opens 8,192 and the service refuses everyone regardless of thread type. The actual defences remain the same: a shortconnection-timeout, a buffering proxy, and per-address connection limits at the edge.Virtual threads buy time and remove the thread pool as the first thing to fail, which is worth having, but the connection limit and the kernel's socket buffers are finite, and any resource that is finite and free for the attacker to consume needs an explicit limit.
09 · DrillData, Transactions, Testing & Configuration — Q81–Q115
This section is where a Boot interview turns into a correctness interview. The transaction questions probe the proxy, propagation, rollback rules, and the connection pool that sits underneath every one of them; the Spring Data questions stay at the Boot level and hand the Hibernate internals to Chapter E5. The testing questions ask what a test actually starts and why suites get slow; the configuration questions ask where a value came from and how to change it safely. Scenarios go in diagnosis order.
These questions test whether you can say precisely what happens between the annotation and the database, and therefore why it sometimes does not happen.
Q81. "Walk me through exactly what happens when a call enters a @Transactional method, down to the connection."
Reveal answer
Strong answer The call crosses seven steps between the proxy and the pool, and each one is a place something can go wrong.
- Proxy: the call arrives at the CGLIB proxy, which invokes the
TransactionInterceptor. - Attributes: the interceptor reads the transaction attributes for the method from the
AnnotationTransactionAttributeSource, cached per method. - Manager: it asks the
PlatformTransactionManagerfor a transaction withgetTransaction(definition). - Begin, for JPA:
JpaTransactionManagerchecksTransactionSynchronizationManager, a set of thread-locals, for an existing transaction bound to the current thread. WithREQUIREDand none present, it:- creates an
EntityManager; - obtains a JDBC connection from the pool through the entity manager and calls
setAutoCommit(false); - applies the isolation level and read-only flag if set, and a statement timeout if one was declared;
- binds both the entity manager and the connection holder to the thread.
- creates an
- Synchronisations: it registers synchronisations so that repositories and
JdbcTemplateon the same thread find the same connection. Then the interceptor invokes the target method. - Commit: on normal return, Hibernate flushes pending changes as SQL, the connection commits, the synchronisations'
afterCommitcallbacks run, the thread-locals are cleared, and the connection returns to the pool. - Rollback: on an exception, the interceptor consults the rollback rules.
RuntimeExceptionandErrorroll back by default; checked exceptions commit unless listed inrollbackFor. A rollback discards the persistence context and returns the connection.
If the transaction was joined rather than created, an exception only marks it rollback-only and the outermost boundary decides.
@Service
public class OrderService {
@Transactional
public void confirm(String id) { ... }
}
// The call `orderService.confirm("4021")` goes through this sequence:
//
// 1. The injected reference is a CGLIB proxy, not OrderService. The call lands
// in the generated subclass's overridden confirm().
// 2. TransactionInterceptor reads the merged @Transactional attributes
// (propagation, isolation, timeout, readOnly, rollbackFor).
// 3. It asks PlatformTransactionManager for a transaction.
// DataSourceTransactionManager checks TransactionSynchronizationManager —
// a ThreadLocal map — for a connection already bound to THIS thread.
// 4. None bound (REQUIRED, no active tx): it borrows a Connection from Hikari,
// calls conn.setAutoCommit(false), and BINDS it to the thread's ThreadLocal.
// 5. Your method body runs. Every JdbcTemplate/EntityManager call on this
// thread now finds that same bound connection instead of borrowing its own.
// 6. Return normally -> conn.commit()
// Throw a RuntimeException/Error -> conn.rollback()
// Throw a CHECKED exception -> COMMIT (the default rollback rule)
// 7. The connection is unbound from the thread and returned to the pool.
Step 4 is the one that explains the most bugs. The transaction is bound to the thread, which is why a new thread — @Async, a parallel stream, a reactive scheduler — starts with no transaction, and why a connection is held for the whole method including any slow HTTP call inside it.
Picture it What one thread holds before, during and after the call, and what a second thread holds instead.
The setup: the OrderService.confirm from the code above, called from a controller, with one extra line that hands work to an @Async method on another bean.
@Service
public class OrderService {
private final OrderRepository repo;
private final AuditAsync audit; // @Async method on another bean
@Transactional
public void confirm(String id) {
repo.save(order); // uses the connection bound to THIS thread
audit.record(id); // ❌ TRAP: runs on a pool thread, outside this transaction
}
}
Make the invisible visible: the thread-locals are just a map per thread. Here is what TransactionSynchronizationManager holds for each thread while confirm runs.
# illustrative output
thread http-nio-8080-exec-3 (the request thread)
resources:
EntityManagerFactory -> EntityManagerHolder(em #7)
HikariDataSource -> ConnectionHolder(conn #4, autoCommit=false)
actualTransactionActive = true
thread task-1 (the @Async pool thread)
resources: (empty)
actualTransactionActive = false
The trace: one hop per line.
Controller ──► proxy.confirm("4021")
└─► TransactionInterceptor
├─► JpaTransactionManager.getTransaction ✓ conn #4 borrowed, autocommit off, bound to exec-3
├─► target.confirm("4021")
│ ├─► repo.save(order) ✓ finds conn #4 in the thread-local
│ └─► audit.record(id) ──► thread task-1
│ └─► repo.save(auditRow) ✗ no bound resources: new conn #9, autocommit
└─► commit conn #4 ✓ conn #4 returned to the pool
What you see: log lines from logging.level.org.springframework.orm.jpa=DEBUG and the pool gauge.
# illustrative output
DEBUG [http-nio-8080-exec-3] JpaTransactionManager : Creating new transaction with name [com.shop.OrderService.confirm]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG [http-nio-8080-exec-3] JpaTransactionManager : Opened new EntityManager [...] for JPA transaction
hikaricp.connections.active = 1 (conn #4, held until commit)
DEBUG [task-1] (no transaction line at all: the audit insert committed by itself on conn #9)
DEBUG [http-nio-8080-exec-3] JpaTransactionManager : Initiating transaction commit
hikaricp.connections.active = 0
Why: the transaction is not a property of the method, it is a pair of thread-locals on the thread that entered the proxy, so a second thread starts with an empty map.
The fix: keep everything that must be atomic on the outer thread, and let the async method start its own transaction after the outer one commits.
@Transactional
public void confirm(String id) {
repo.save(order);
events.publishEvent(new OrderConfirmed(id)); // ✅ FIX: no thread hop inside the transaction
}
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onConfirmed(OrderConfirmed e) { ... } // runs after commit, with its own transaction if it needs one
What you see now: the audit insert can only exist if the order committed.
# illustrative output
DEBUG [exec-3] JpaTransactionManager : Initiating transaction commit (order committed first)
DEBUG [task-1] ... runs after the commit and never before it, so a rolled-back order never leaves an audit row
Land it The annotation is a thread-local connection with autocommit off, bound for the duration of the outermost proxied call, and every rule about it follows from that sentence.
- "When exactly is the connection taken from the pool, and can you delay it?"
By default, at
getTransaction, before your method body runs.JpaTransactionManager.doBegincreates theEntityManagerand, throughHibernateJpaDialect.beginTransaction, Hibernate obtains the JDBC connection to callsetAutoCommit(false)and apply isolation, so the connection is checked out for the whole method even if the first query comes after 300 milliseconds of validation or an outbound call.You can delay it by wrapping the
DataSourceinLazyConnectionDataSourceProxy, which hands Hibernate a placeholder and only fetches the real connection on the first statement; Boot 3.x and later also let Hibernate defer withhibernate.connection.provider_disables_autocommit=truewhen the pool already has autocommit off, which skips a round trip.As of Aug 2026 that combination is what I use by default, and I verify with
hikaricp.connections.usagethat checkout duration dropped to the SQL time only.- "What is the difference between the transaction being rolled back and being marked rollback-only?"
Ownership. The proxy that created the transaction, the outermost
REQUIREDboundary, owns it and is the only one that issues the JDBCrollbackorcommit.An inner proxy that merely joined the existing transaction has no authority to end it, so when an exception passes through it, it calls
setRollbackOnlyon theTransactionStatus, which sets a flag on the sharedDefaultTransactionStatus, and rethrows.If the exception reaches the outer boundary, the outer proxy rolls back and the flag was redundant. If the outer method catches the exception and returns normally, the outer proxy tries to commit, the manager sees the flag, rolls back instead, and throws
UnexpectedRollbackException.So "marked" means "somebody inside decided this cannot succeed", and only the owner turns that decision into a database command.
- "Where does isolation level get applied, and does it survive the connection returning to the pool?"
The transaction manager applies isolation by calling
Connection.setTransactionIsolationduring begin, and for Hibernate the dialect does the same on the underlying JDBC connection. Before the connection is returned, Spring'sDataSourceUtils.resetConnectionAfterTransactionrestores the previous isolation and read-only values, so the next borrower does not inherit them.HikariCP also resets state on return: it tracks a dirty bit for autocommit, isolation, read-only, catalog, and network timeout, and only issues the reset calls that are needed, which is why Hikari's
transaction-isolationproperty is the pool-wide default and Spring's annotation is a per-transaction override.The trap is
Isolation.DEFAULT, which means "whatever the database session already has":READ COMMITTEDon PostgreSQL andREPEATABLE READon MySQL, so the same code behaves differently across databases unless you declare it.- "What happens to this picture when the method runs on a virtual thread or hands work to another thread?"
Virtual threads change nothing, because
TransactionSynchronizationManagerstill usesThreadLocal, and virtual threads support thread-locals fully; the transaction is bound to whichever thread runs the method.Handing work to another thread is where it breaks: a
CompletableFuture.supplyAsyncor an@Asynccall inside a transactional method runs on a thread with no bound resources, so a repository call there gets a fresh connection in autocommit mode, invisible to the caller's transaction and committed immediately even if the caller rolls back.what an @Async call inside a transaction leaves behindruns offline# illustrative output thread exec-3: INSERT INTO orders ... (conn #4, not yet committed) thread task-1: INSERT INTO audit (order_id) ... (conn #9, autocommit: committed immediately) thread exec-3: ROLLBACK (caller fails) orders: (empty) audit: 1 row for an order that does not existThe same is true for parallel streams. The rule is that a transaction is a single-thread scope, and anything that must be atomic with the outer work stays on the outer thread.
If the goal is parallel reads, each task gets its own short read-only transaction and the results are merged afterwards.
Q82 · Scenario. "A @Transactional service method throws, the caller sees the exception, but the rows it inserted before the throw are still in the database. Walk me through the causes in order of likelihood."
Reveal answer
Strong answer In diagnosis order:
- Symptom: an exception escaped but no rollback occurred. Either there was no transaction, or there was one and the rule said commit.
- Evidence: set
logging.level.org.springframework.transaction=TRACEandorg.springframework.orm.jpa=DEBUG; look for "Creating new transaction" before the method and "Initiating transaction commit" or "rollback" after. Also check the exception's type. - Causes, in order of likelihood:
- One, most likely: the exception is checked, for example a custom
ImportException extends Exception. Spring commits on checked exceptions unless@Transactional(rollbackFor = Exception.class)is declared. - Two: self-invocation, so the method never went through the proxy and each repository call committed on its own.
- Three: the exception was caught inside the method, logged, and rethrown as something else after the repository calls; or the method caught it and returned normally while the caller saw a different exception from a later step.
- Four: the method is on a class that is not a bean, or is
finalorprivate. - Five: two transaction managers exist and the annotation used the wrong one, or the datasource is a non-transactional proxy.
- Six, rare:
spring.datasource.hikari.auto-commit=truewith a JDBC path that bypasses the transaction manager entirely, such as a rawDataSource.getConnection().
- One, most likely: the exception is checked, for example a custom
- Fix: declare
rollbackFor = Exception.classas a project convention, or make domain exceptions unchecked; move the call across a bean boundary; never obtain connections directly. - Prevention: an integration test with Testcontainers that throws mid-method and asserts the count is zero, because this bug is invisible to unit tests.
// ❌ TRAP: BROKEN — a checked exception does NOT roll back by default.
@Transactional
public void importBatch(Path file) throws IOException {
repo.save(header); // this INSERT is committed
parse(file); // throws IOException
} // -> Spring COMMITS, then rethrows
// Result: the header row stays in the table although the caller sees the IOException
// Spring's default: roll back on RuntimeException and Error, commit on
// checked exceptions. It is a deliberate convention, not a bug — but almost
// nobody expects it, which is why it is worth stating explicitly.
// ✅ FIX 1 — declare it.
@Transactional(rollbackFor = Exception.class)
public void importBatch(Path file) throws IOException { ... }
// ✅ FIX 2 — the one I prefer: do not use checked exceptions for failures the
// caller cannot meaningfully handle.
@Transactional
public void importBatch(Path file) {
try { parse(file); }
catch (IOException e) { throw new ImportFailed(file, e); } // unchecked
}
Read the second fix. Declaring rollbackFor on every method is a per-method promise somebody will forget; converting to an unchecked exception at the boundary fixes it once and matches how the rest of Spring behaves.
Picture it The same method run twice, once with a checked exception and once with the fix, with the SQL in the order it ran and the table before and after.
The setup: the importBatch method in the code below, where parse(file) throws IOException after repo.save(header).
Make the invisible visible: the proxy decides commit or rollback by asking the rule about the exception it just caught.
// TransactionInterceptor, written out as pseudo-Java
try {
target.importBatch(file);
} catch (Throwable ex) {
// rollbackOn(ex) is true only for RuntimeException and Error, plus anything in rollbackFor
// IOException -> checked, not listed -> rollbackOn = false -> COMMIT, then rethrow
// ImportFailed (unchecked) -> rollbackOn = true -> ROLLBACK, then rethrow
}
The trace: one hop per line.
Controller ──► proxy.importBatch(file) ✓ transaction begins (conn #4, autocommit off)
└─► target.importBatch(file)
├─► repo.save(header) INSERT issued, not yet committed
└─► parse(file) ✗ throws IOException (checked)
◄── proxy: rollbackOn(IOException) = false ✗ COMMIT, then rethrow
Controller ◄── IOException
What you see: SQL in the order it ran, and the table before and after.
# illustrative output
conn #4 setAutoCommit(false)
conn #4 INSERT INTO import_header (id, file_name) VALUES (1, 'q3.csv')
conn #4 COMMIT ✗ expected ROLLBACK
import_header before call after call
id | file_name (0 rows) 1 | q3.csv <- still there, caller saw IOException
TRACE TransactionInterceptor : Completing transaction for [ImportService.importBatch] after exception: java.io.IOException
DEBUG JpaTransactionManager : Initiating transaction commit
Why: the default rule treats a checked exception as a business outcome, so the interceptor commits what was done so far.
The fix: either rollbackFor = Exception.class or an unchecked exception at the boundary, both shown in the code below (FIX 1 and FIX 2).
What you see now: the same call after FIX 2.
# illustrative output
conn #4 setAutoCommit(false)
conn #4 INSERT INTO import_header (id, file_name) VALUES (1, 'q3.csv')
conn #4 ROLLBACK ✓
import_header before call after call
(0 rows) (0 rows) <- nothing survived
Which cause is it?: read the log first, then act.
| What the TRACE log shows | Root cause | Action |
|---|---|---|
| no "Creating new transaction" line for the method | no transaction: self-invocation, not a bean, final or private | call across a bean boundary |
| "Creating new transaction", then "Initiating transaction commit" after the exception | rule said commit: checked exception | rollbackFor or make the exception unchecked |
| two "Creating new transaction" lines, the inner one commits | REQUIRES_NEW, or a second transaction manager | check propagation and the transactionManager qualifier |
| commit logged, exception thrown later | failure after the method returned, such as a listener or serialisation | the commit was correct; fix the later step |
Land it Check the exception type first, because "checked exceptions commit" surprises more people than the proxy does, and then check the proxy.
- "Why does Spring commit on checked exceptions? It seems like an obviously wrong default."
The reasoning comes from EJB, which Spring's transaction model copied for familiarity: a checked exception is part of the method's declared contract, so the caller was expected to handle it as a business outcome, for example "insufficient funds", and business outcomes are not system failures, so the work done so far should stand.
An unchecked exception was assumed to mean a bug or an infrastructure failure, where nothing can be trusted.
That distinction rarely matches how modern code uses exceptions, which is why nearly every team I have worked on declares
rollbackFor = Exception.classas a convention, or writes a meta-annotation such as@BusinessTransactionalthat carries it.As of Aug 2026, Spring Framework 7 still keeps the historical default for compatibility; changing it would silently alter behaviour in every existing application, which is worse than a documented surprise.
- "The exception is unchecked, there is no self-invocation, and the log still says 'commit'. What is left?"
Then I look at what happened between the insert and the throw.
The most likely remaining cause is that the insert and the throw are in different transactions after all: the repository call is inside a nested method annotated
REQUIRES_NEW, or the insert happens through aJdbcTemplatebuilt on a differentDataSourcethan the transaction manager's, or a second transaction manager bean exists and the annotation resolved to the one that does not manage this datasource, which the TRACE log shows as two managers logging.two transactions in the log, not oneruns offline# illustrative output TRACE TransactionInterceptor : Getting transaction for [OrderService.importAll] DEBUG JpaTransactionManager : Creating new transaction with name [OrderService.importAll] DEBUG JpaTransactionManager : Suspending current transaction, creating new transaction with name [AuditService.write] DEBUG JpaTransactionManager : Initiating transaction commit (inner commits: the insert is durable) DEBUG JpaTransactionManager : Initiating transaction rollback (outer rolls back: the inner insert stays)Another is
@Transactionalfrom the wrong package,jakarta.transaction.Transactional, which Spring does honour but whoserollbackOnattribute differs and whose default is also to commit on checked exceptions.Last, the exception is thrown after the method returned, in a
@TransactionalEventListeneror in serialisation, so the commit was correct and the failure is later than it looks.- "How do you write the test so it proves rollback rather than proving your mocks?"
It has to hit a real database and must not be
@Transactionalitself, because a test-managed transaction would wrap the service call and the rollback-versus-commit decision would never reach the database.So: a
@SpringBootTestwith a Testcontainers PostgreSQL through@ServiceConnection, a@MockitoBeanor a test double for the collaborator that throws after the insert, thenassertThatThrownBy(() -> service.importBatch(...)), and finally aJdbcClientcount query asserting zero rows.a test that proves rollback, not mocksruns offline@SpringBootTest // ❌ TRAP if you add @Transactional here: the test wraps the call class ImportRollbackTest { @MockitoBean Parser parser; // throws after the header insert @Autowired ImportService service; @Autowired JdbcClient jdbc; @Test void failedImportLeavesNothing() { when(parser.parse(any())).thenThrow(new ImportFailed("bad row")); assertThatThrownBy(() -> service.importBatch(Path.of("q3.csv"))) .isInstanceOf(ImportFailed.class); long n = jdbc.sql("select count(*) from import_header").query(Long.class).single(); assertThat(n).isZero(); // ✅ committed state, read outside any test transaction } }The count must run outside any transaction the test holds, so it sees committed state only. I also add the inverse test, the happy path committing, so the suite fails if someone later makes everything
REQUIRES_NEW.The whole test takes under a second once the context is cached and it is the only test in the codebase that can catch a propagation regression.
- "How would you find every method in the codebase that has this bug today?"
Statically and then dynamically.
Statically, an ArchUnit rule: every method annotated
@Transactionalthat declares a checked exception in itsthrowsclause, or calls a method that does, must specifyrollbackFor; and a second rule that no@Transactionalmethod isprivate,final, or called from the same class, which ArchUnit can approximate by scanning call graphs.Dynamically, a custom
TransactionSynchronizationregistered in a test profile that records, for each transaction, whether it committed while an exception was in flight, which I detect by wrapping theTransactionInterceptorwith an aspect that notes the exception.Running the integration suite with that on produces a list of offenders in one run. Then the fix is one pull request introducing the meta-annotation and a rewrite recipe, in OpenRewrite, that replaces
@Transactionalwith it everywhere.
Q83. "REQUIRES_NEW versus NESTED: how does each work at the connection level, and what does REQUIRES_NEW cost you under load?"
Reveal answer
Strong answer The two propagations differ in whether the inner work gets its own connection.
- REQUIRES_NEW, mechanism: the transaction manager suspends the current transaction, meaning it unbinds its connection and entity manager from the thread and parks them. It then opens a completely separate transaction on a second connection from the pool.
- REQUIRES_NEW, outcome: the inner transaction commits or rolls back on its own; then the outer resources are re-bound and the outer transaction continues.
- REQUIRES_NEW, isolation: the two cannot see each other's uncommitted changes, and if the inner one updates a row the outer one has locked, they deadlock against each other in the same thread.
- REQUIRES_NEW, cost under load: every level of nesting holds one more connection per request for the duration of the inner call. With a pool of 10 and 10 concurrent requests each entering a
REQUIRES_NEWmethod, all 10 outer connections are held and the 10 inner requests wait for a connection that will never be freed. That is a pool deadlock that looks like a hang. - NESTED, mechanism: it creates a JDBC savepoint on the same connection; rolling back the inner part means
ROLLBACK TO SAVEPOINT, the outer transaction continues, and nothing is committed until the outer commit. - NESTED, cost and support: it costs no extra connection but is supported only by
DataSourceTransactionManagerwith JDBC drivers that support savepoints;JpaTransactionManagerthrowsNestedTransactionNotSupportedException.
So: REQUIRES_NEW for "must be durable even if the outer fails", such as audit and outbox rows, with the pool sized for it; NESTED for "try this part, keep going if it fails" in JDBC code.
Picture it One shared example run under both options, with the SQL and connection ids in order, then a table of outcomes and a pool that runs dry.
The setup: one outer method writes an order, calls an inner audit method, and then fails. A second scenario has the inner method failing and the outer one catching it.
@Transactional
public void placeOrder(Order o) {
orders.save(o); // INSERT orders
auditor.write(o); // inner method: REQUIRES_NEW in run 1, NESTED in run 2
throw new IllegalStateException("payment declined"); // scenario A: outer fails AFTER the inner succeeded
}
Make the invisible visible: the connection and the commit points for each option.
# illustrative output
conn A setAutoCommit(false)
conn A INSERT INTO orders ... -- outer suspended, A unbound from the thread
conn B setAutoCommit(false) -- second connection borrowed
conn B INSERT INTO audit ...
conn B COMMIT ✓ audit row is durable now
-- A re-bound to the thread
conn A ROLLBACK <- IllegalStateException
orders: 0 rows audit: 1 row (audit survived)
# illustrative output
conn A setAutoCommit(false)
conn A INSERT INTO orders ...
conn A SAVEPOINT sp1
conn A INSERT INTO audit ...
conn A RELEASE SAVEPOINT sp1 -- inner "done", nothing committed
conn A ROLLBACK <- IllegalStateException
orders: 0 rows audit: 0 rows (audit rolled back with the order)
| Scenario | REQUIRES_NEW | NESTED (JDBC) |
|---|---|---|
| A: inner succeeds, outer throws afterwards | audit row survives, order rolled back, 2 connections | audit row rolled back with the order, 1 connection |
| B: inner throws, outer catches and continues | inner rolled back alone; order commits | ROLLBACK TO SAVEPOINT sp1; order commits |
| inner touches a row the outer already wrote | blocks on the outer lock: same-thread hang | no problem: same connection, same locks |
| pool of 10, 10 requests enter at once | all 10 hold A, all 10 wait for B | no extra connection needed |
What you see: the pool when the hang happens.
# illustrative output
hikaricp.connections.max 10
hikaricp.connections.active 10 <- every connection is an outer transaction
hikaricp.connections.pending 10 <- every thread is waiting for its inner connection
HikariPool-1 - Connection is not available, request timed out after 30000ms
Why: REQUIRES_NEW makes one thread hold two connections, and the outer one is not released until the inner call returns.
The fix: budget the pool for two connections per thread on that path, or restructure so the durable write happens before or after the outer transaction (see the last follow-up).
What you see now: the same load with the pool sized for it, or the audit write moved out.
# illustrative output
hikaricp.connections.max 20
hikaricp.connections.active 14
hikaricp.connections.pending 0
Going deeper One correction to the usual summary: JpaTransactionManager can do NESTED.
Its nestedTransactionAllowed flag defaults to false, so the default is indeed NestedTransactionNotSupportedException, but when set to true and the JpaDialect exposes the JDBC connection, which HibernateJpaDialect does, it creates a JDBC savepoint on the same connection exactly like DataSourceTransactionManager.
The reason it is off by default is the persistence context: a ROLLBACK TO SAVEPOINT undoes the SQL but not the managed entities Hibernate already flushed and still holds in memory, so after a nested rollback the first-level cache can disagree with the database until you clear() it.
That mismatch is the real reason to avoid NESTED with JPA, not a hard limitation.
// REQUIRES_NEW — suspends the outer transaction and borrows a SECOND connection
// from the pool. Two independent transactions, two commits.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void writeAuditRow(Audit a) { auditRepo.save(a); }
//
// Cost under load: a request in the outer transaction holds connection A while
// waiting for connection B. With a pool of 20 and 20 concurrent requests all
// doing this, every request holds one and waits for another -> DEADLOCK on the
// pool, reported as "Connection is not available, request timed out".
// Rule of thumb: pool size must exceed the maximum number of connections a
// single thread can hold at once.
// NESTED — ONE connection, using a JDBC savepoint.
@Transactional(propagation = Propagation.NESTED)
public void tryOptionalStep() { ... }
//
// SAVEPOINT sp1;
// ... work ...
// ROLLBACK TO sp1; -- undoes only the inner work, outer tx still alive
//
// No second connection, so no pool deadlock. But: only supported by
// DataSourceTransactionManager (not JTA), and JPA/Hibernate support is limited,
// which is why it is rarely seen in Boot services.
The pool arithmetic is the part that turns this into an incident. REQUIRES_NEW means one thread holds two connections, so the effective concurrency of the service halves — and the failure appears as a pool timeout rather than as anything pointing at the annotation.
Land it REQUIRES_NEW is a second connection, so budget for it in the pool or it becomes a deadlock under load; NESTED is a savepoint, and JPA does not have it.
- "How would you detect the REQUIRES_NEW pool deadlock in production rather than by reasoning?"
The signature is a full pool with zero database activity and a thread dump where every busy thread is waiting in
HikariPool.getConnection, and each of those threads already holds one connection further up its stack.thread dump of the REQUIRES_NEW pool deadlockruns offline# illustrative output "http-nio-8080-exec-7" WAITING at com.zaxxer.hikari.pool.HikariPool.getConnection at ...TransactionInterceptor.invoke <- inner REQUIRES_NEW asking for connection B at com.shop.AuditService.writeAuditRow at com.shop.OrderService.placeOrder <- outer transaction already holds connection A pg_stat_activity: 10 sessions, state = idle in transactionHikari's
leak-detection-thresholdreports the outer connection as a leak after the threshold because it has been held without returning; the stack trace it prints shows the outer@Transactionalmethod frame above aREQUIRES_NEWinner call.In metrics,
hikaricp.connections.activeequals the maximum,hikaricp.connections.pendingequals the number of stuck requests, and the database'spg_stat_activityshows every sessionidle in transaction. The confirming test is that the hang clears the momentconnection-timeoutfires and the inner calls fail, then recurs.The fix is a pool at least twice the concurrent request count for that path, or a redesign.
- "Give a case where REQUIRES_NEW is the right tool and one where people use it wrongly."
Right: an audit or outbox record of a failed attempt, where the surrounding transaction is about to roll back and the record must survive; a "job started" heartbeat row written before a long batch so a monitor can see progress before the batch commits; or claiming an idempotency key so that a concurrent duplicate request sees it immediately.
In all three the inner write is meant to be durable independently of the outer outcome.
Wrong: using it to "commit in chunks" from inside a big transaction, which does not release the outer connection and still holds the outer locks; using it to escape a rollback-only mark after catching an exception, which hides a design problem; and calling it in a loop, which multiplies the connection cost by the iteration count.
The test I apply is whether I would be happy for the inner write to exist when the outer work never did.
- "What isolation does the inner transaction see, and can the two deadlock?"
The inner transaction runs on a second connection, so from the database's point of view it is an unrelated session.
It cannot see the outer transaction's uncommitted rows, and if it reads a row the outer one has updated but not committed, it either blocks on the row lock, if it tries to update the same row, or sees the old value under
READ COMMITTED.That gives the same-thread deadlock: the outer transaction holds a row lock, the inner one on the second connection waits for that lock, and the outer one is waiting for the inner method to return.
PostgreSQL cannot detect it as a deadlock because only one side is waiting in the database, so it hangs until
lock_timeoutor the transaction timeout fires. The rule that prevents it is that the inner transaction must never touch rows the outer one has already written.- "How would you keep the guarantee of REQUIRES_NEW without the second connection?"
Reorder the work so the durable record is written first, in its own short transaction, and the business work runs afterwards in a separate one.
The orchestrator is a non-transactional method: step one calls
auditService.recordAttempt(...), which is a normalREQUIREDtransaction that commits and returns its connection; step two calls the business method, alsoREQUIRED, which gets a connection only for its own duration.The two never overlap, so the pool sees one connection per request. On failure of step two, a third short transaction updates the audit row to "failed", and if the process dies between them, a sweeper marks attempts with no outcome.
This is the same idea as the outbox: do the durable thing and the risky thing in sequence with state in between, instead of nesting them. It costs a little more code and gives back half the pool.
Q84 · Scenario. "A method catches an exception from a called service, logs it, and continues. At the end, the caller gets UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only. Explain and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the outer commit was refused because something inside marked the transaction rollback-only, even though no exception reached the outer boundary.
- Evidence: the called service method is itself
@Transactionalwith defaultREQUIRED; the exception thrown inside it was aRuntimeException; the outer method caught it. - Cause: with
REQUIRED, the inner method joins the outer transaction. When the inner proxy sees the exception, it cannot roll back a transaction it does not own, so it sets the global rollback-only flag and rethrows. The outer method catches the exception and thinks it recovered, but the transaction is already doomed. At commit time the manager sees the flag, rolls back, and throwsUnexpectedRollbackExceptionso the caller is not lied to. This is correct behaviour; the design that expected to recover inside a joined transaction is what is wrong. - Fix, by intent:
- Inner failure must not affect the outer work: give the inner method
REQUIRES_NEW, so its failure is its own; or mark the inner methodnoRollbackForthat exception, if the inner writes are fine to keep. - Outer work should fail when the inner fails: stop catching and let the exception propagate, which is the most common correct answer.
- Never: set
globalRollbackOnParticipationFailure=falseon the manager globally; it hides the flag everywhere.
- Inner failure must not affect the outer work: give the inner method
- Prevention: a rule that catching exceptions from a transactional call inside a transaction requires an explicit propagation decision, and a test for the recovery path.
// The inner method joins the SAME transaction (REQUIRED, tx already active).
// When it throws, the interceptor marks the shared transaction rollback-only.
// Catching the exception afterwards does not un-mark it.
@Transactional // OUTER — owns the transaction
public void processOrder(String id) {
repo.save(order);
try {
inventoryService.reserve(id); // @Transactional, joins this tx
} catch (OutOfStock e) {
log.warn("no stock, continuing"); // the exception is handled...
} // ❌ TRAP: ...but the tx is already marked rollback-only
repo.save(audit);
} // Result: the commit attempt turns into a rollback
// and throws UnexpectedRollbackException:
// Transaction silently rolled back ...
// ✅ FIX 1 — give the inner call its OWN transaction, so its failure is isolated.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void reserve(String id) { ... } // separate connection, commits/rolls back alone
// ✅ FIX 2 — do not throw for an expected outcome. Return a result instead.
public ReserveResult reserve(String id) {
return stock.isAvailable(id) ? ReserveResult.ok() : ReserveResult.outOfStock();
}
The mental model to keep: rollback-only is a flag on the shared transaction, set by the interceptor before your catch block ever runs. Fix 2 is usually the better design, because an out-of-stock item is an expected business outcome rather than an exceptional condition.
Picture it The one shared transaction at four moments, with the log line, the SQL and the table that show why the catch block did not save it.
The setup: processOrder and reserve from the code below: the outer method owns the transaction, the inner one joins it and throws OutOfStock, the outer one catches.
Make the invisible visible: there is one transaction, so one flag, and both methods see the same one.
# illustrative output
1. processOrder enters the proxy tx #1 created by processOrder (owner) rollbackOnly = false
2. reserve() enters the proxy joins tx #1 (REQUIRED) rollbackOnly = false
3. reserve() throws OutOfStock its proxy cannot roll back what it does not own
-> marks tx #1 rollbackOnly = true
4. processOrder catches, saves audit continues as if nothing happened rollbackOnly = true
The trace: one hop per line.
Controller ──► proxy.processOrder("4021") ✓ owns tx #1
└─► target.processOrder
├─► repo.save(order) INSERT, uncommitted
├─► proxy.reserve("4021") joins tx #1
│ └─► target.reserve throws OutOfStock
│ ◄── proxy marks tx #1 rollback-only, rethrows ✗ doomed
├─► catch (OutOfStock) "recovered" only in Java
└─► repo.save(audit) INSERT, uncommitted
◄── proxy tries to commit: flag is set -> ROLLBACK, throws UnexpectedRollbackException
What you see: the log line at the moment of marking, the SQL, the exception and the table.
# illustrative output
TRACE TransactionInterceptor : Completing transaction for [InventoryService.reserve] after exception: OutOfStock
DEBUG JpaTransactionManager : Participating transaction failed - marking existing transaction as rollback-only
conn #4 INSERT INTO orders ...
conn #4 INSERT INTO audit ...
conn #4 ROLLBACK ✗ the caller expected a commit
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
orders / audit before after
(0 rows) (0 rows) <- nothing was saved
Why: the inner proxy cannot end a transaction it does not own, so it sets a flag that only the owner turns into a database command.
The fix: FIX 1 (REQUIRES_NEW on reserve) or FIX 2 (return a result instead of throwing), both in the code below.
What you see now: with FIX 1, the order and audit commit and the reservation rolls back alone.
# illustrative output
DEBUG JpaTransactionManager : Suspending current transaction, creating new transaction with name [InventoryService.reserve]
conn #9 ROLLBACK (reserve alone, on its own connection)
conn #4 INSERT INTO orders ...
conn #4 INSERT INTO audit ...
conn #4 COMMIT ✓
orders / audit before after
(0 rows) 1 order, 1 audit row
Land it A joined transaction cannot be partially recovered by catching, so the fix is to decide whether the inner work is separate, and say so with propagation.
- "You switched the inner method to REQUIRES_NEW and now the outer transaction hangs under load. Why?"
Because the fix moved the problem from correctness to capacity. The inner method now needs a second pooled connection while the outer one is held, so each request in that path consumes two connections at once.
With a pool of 10 and more than 10 concurrent requests, the outer transactions hold all 10 connections and every inner call waits for one that will only be freed when an outer transaction finishes, which cannot happen until its inner call returns.
That is the pool deadlock from Q83, and it presents as a hang that clears when
connection-timeoutfires.The immediate mitigation is a pool at least twice the concurrency on that path, and the durable fix is to restructure so the inner work runs before or after the outer transaction rather than inside it, or to reconsider whether the inner failure really should leave the outer work intact.
- "What does noRollbackFor actually do, and where should it go?"
noRollbackForis a rollback rule evaluated by the proxy that sees the exception. If I put@Transactional(noRollbackFor = InventoryUnavailableException.class)on the inner method, its proxy sees that exception, checks the rules, finds it excluded, and does not mark the transaction rollback-only; it just rethrows.The outer method catches it and continues, and the commit succeeds, including whatever the inner method wrote before it threw.
Putting the rule on the outer method instead does nothing for this case, because the inner proxy already marked the transaction before the outer rule was consulted. The rule therefore belongs on the boundary closest to the throw.
where noRollbackFor goesruns offline// ✅ FIX: the rule goes on the INNER method, the boundary closest to the throw @Transactional(noRollbackFor = InventoryUnavailableException.class) public void reserve(String id) { ... } // inner proxy sees the exception, finds it excluded, does not mark // ❌ TRAP: the same attribute on processOrder() does nothing for this case // Result: with the rule on reserve(), the outer catch works and the commit succeedsIt is the right tool only when the inner method's partial writes are correct to keep, which is rarer than people think; usually a domain method that throws has not written anything worth keeping.
- "Is there a way for the outer method to find out the transaction is doomed before it wastes more work?"
Yes.
TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()returns true once any participant has marked it, so the outer method can check after the catch block and bail out with a clear exception of its own rather than doing 200 milliseconds more work and then receivingUnexpectedRollbackException.checking the flag before wasting more workruns offlinetry { inventoryService.reserve(id); } catch (OutOfStock e) { if (TransactionAspectSupport.currentTransactionStatus().isRollbackOnly()) { throw new OrderAbandoned(id, e); // fail now with a clear exception, not at commit } }The same object lets you deliberately mark rollback with
setRollbackOnly()when you want to swallow an exception but still abandon the work, which is the honest version of "catch and continue".I use it sparingly, because code that inspects transaction status is coupled to the proxy, but in an orchestration method that catches for the purpose of reporting partial failures it is exactly right.
In a
TransactionTemplate.executecallback the same is available on theTransactionStatusparameter, which is cleaner.- "How would you explain this exception to a junior who just hit it, in one sentence, and what would you tell them to check first?"
One sentence: something you called inside this transaction already gave up on it, so your catch block recovered the code path but not the transaction.
First check: find the method whose exception you caught and see whether it is
@Transactionalwith default propagation, because if so it joined your transaction and marked it. The decision I ask them to make explicitly is whether the outer work should survive the inner failure.If no, delete the catch and let it propagate, and the confusing exception disappears because the rollback is now the obvious outcome. If yes, the inner work is a separate unit and should say so with
REQUIRES_NEW, and they need to know that costs a connection.I also point them at the TRACE logging for
org.springframework.transaction, which prints "Participating transaction failed - marking existing transaction as rollback-only" at the exact moment.
Q85 · Design. "Design audit logging so that every attempt to change an order, successful or not, is recorded durably, without slowing the order path or leaking into it."
Reveal answer
Strong answer Requirements first:
- failed attempts must be recorded even when the business transaction rolls back;
- successful ones must not be recorded if the business transaction rolls back afterwards, because a record of a change that did not happen is misleading;
- the audit write must not add latency or a second failure mode to the order;
- audit must not be forgettable by developers.
Design: an AOP aspect, @Around on methods annotated with a custom @Audited, captures actor, action, target id, and outcome, and hands an AuditEvent to an AuditRecorder. The recorder has two paths keyed by outcome.
- Failure path: it writes with
REQUIRES_NEW, since the surrounding transaction is about to roll back and the record must survive. The pool is sized for that extra connection, and the write is a single insert. - Success path: it does not write directly. It publishes the event, and a
@TransactionalEventListener(phase = AFTER_COMMIT)hands it to an asynchronous writer, so the record exists only if the order committed and the order path never waits on it. - Durability of the asynchronous path: an outbox. The event is inserted in the same transaction as the order as a row in
audit_outbox, and a relay moves rows to the audit store, which makes success records as durable as the order. - The store: append-only, with a database role that has no delete privilege.
Trade-offs: REQUIRES_NEW costs a connection during failures, which are rare; the outbox adds a table and a relay, which is the price of not losing records on a crash.
What I would not do: write audit rows inside the business transaction, because a rollback erases the evidence; or fire-and-forget from an @Async method with no persistence, because a crash loses the record silently.
Picture it Two attempts, one that commits and one that fails, with what each table holds at three moments, then a table from symptom to cause to action.
The setup: the aspect hands the event to the recorder; the recorder owns the two paths.
@Aspect @Component
class AuditAspect {
@Around("@annotation(audited)")
Object around(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
try {
Object result = pjp.proceed();
recorder.recordSuccess(AuditEvent.of(audited, pjp)); // success path
return result;
} catch (Throwable t) {
recorder.recordFailure(AuditEvent.failed(audited, pjp, t)); // failure path
throw t;
}
}
}
@Component
class AuditRecorder {
@Transactional(propagation = Propagation.REQUIRES_NEW) // ✅ survives the outer rollback
void recordFailure(AuditEvent e) { auditLog.save(e); }
void recordSuccess(AuditEvent e) { events.publishEvent(e); } // aspect runs inside the order transaction
@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
void toOutbox(AuditEvent e) { outbox.save(e); } // row in audit_outbox, same commit as the order
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void nudgeWriter(AuditEvent e) { asyncWriter.wake(); } // only fires if the order committed
}
Make the invisible visible: the state of each table at three moments, for a success (order 4021) and a failure (order 4022).
| Moment | orders | audit_outbox | audit_log |
|---|---|---|---|
| A1: 4021 inside its transaction | 4021 CONFIRMED (uncommitted) | row 91, published_at NULL (uncommitted) | empty |
| A2: 4021 committed | 4021 CONFIRMED | row 91, published_at NULL | empty |
| A3: relay has run | 4021 CONFIRMED | row 91, published_at 10:02:07 | 4021 CONFIRM SUCCESS |
| B1: 4022 running, declined | 4022 PENDING (uncommitted) | empty | empty |
| B2: recordFailure on its own connection | 4022 PENDING (still uncommitted) | empty | 4022 CONFIRM FAILED (committed) |
| B3: 4022 rolled back | no row for 4022 | empty | 4022 CONFIRM FAILED |
The trace: the failure path.
Controller ──► proxy.confirm(4022) ✓ transaction on conn A
└─► AuditAspect.around
├─► target.confirm(4022) throws PaymentDeclined
└─► recorder.recordFailure(...) ✓ REQUIRES_NEW: conn B, INSERT audit_log, COMMIT
◄── rollback conn A; caller sees PaymentDeclined
| Symptom | Root cause | Action |
|---|---|---|
| failed attempt has no audit row | audit row written inside the business transaction | write failures with REQUIRES_NEW |
| audit row exists for an order that was rolled back | audit written before commit, outside the order transaction | success path through the outbox row, same commit as the order |
| order latency rises when the audit store is slow | synchronous write on the order path | relay moves rows asynchronously |
| audit rows missing after a crash | fire-and-forget @Async with no persistence | outbox, so the row is durable with the order |
| pool timeouts during a burst of failures | each failure holds a second connection | size the pool for it; failures are rare so this is a budget, not a redesign |
Land it Failures are recorded in their own transaction, successes are recorded through an after-commit outbox, and neither path can slow or break the order.
- "The requirement changes: auditors need the record to include the before and after state of the order. What changes?"
The capture point moves from the method boundary into the data layer, because an aspect around a service method sees arguments and a return value, not the row that was changed.
For JPA entities, Hibernate Envers does this natively:
@Auditedon the entity writes a revision row intoorder_AUDin the same transaction with the full new state and a revision table that carries actor and timestamp through a customRevisionListener.what Envers adds to the databaseruns offline# illustrative output order order_AUD (same transaction as the change) id | status id | REV | REVTYPE | status 4021| CONFIRMED 4021| 41 | 0 | PENDING 4021| 42 | 1 | CONFIRMED REVINFO: REV=42, REVTSTMP=..., actor=alice (filled by the custom RevisionListener)That gives the after-state for successful changes for free. The before-state is the previous revision, which Envers can query. For failed attempts, which never flush, the aspect still records the intended change from the request payload.
The trade-off is that Envers writes are inside the business transaction, which the original design avoided, so the audit table must be on the same database and its write cost is on the order path; for a few rows per change that is acceptable.
- "How do you make sure a developer cannot add an order-changing method and forget the audit?"
By making the annotation a consequence of location rather than memory.
An ArchUnit test asserts that every public method in classes under
..order.application..whose name starts with a mutating verb, or that is@TransactionalwithoutreadOnly, carries@Audited; it runs in the unit test phase and fails the build with the method name.A second guard is a Spring Modulith or package convention where the only entry point to order mutation is one
OrderCommandsfacade, whose methods are all audited, and repository access is package-private so a new controller cannot bypass it.Third, a reconciliation query in staging compares the count of order version changes, from the
@Versioncolumn or an Envers revision table, against the count of audit records, and pages if they diverge. The first stops the mistake, the last catches whatever the first missed.- "What would you cut if you had to ship this by Friday?"
I would ship the aspect and the failure path exactly as designed, and simplify the success path to a synchronous insert inside the business transaction, deferring the outbox.
The failure path with
REQUIRES_NEWis small and cannot be replaced, because without it failed attempts leave no trace.Writing success records inside the business transaction means a rollback erases them, but that is correct for success records, since a rolled-back order was not changed; what it costs is one insert of latency, roughly a millisecond, on the order path, and a coupling where an audit table failure fails the order.
I would accept that for a week and note it. What I would not cut is the append-only database role, because retrofitting a permission is harder than granting it correctly once, and the durability claim to the auditors depends on it.
- "How does the after-commit outbox path behave if the relay is down for an hour?"
Nothing is lost and the order path is unaffected, which is the point. The
audit_outboxrows were written in the same transaction as the order, so they sit in the database withpublished_atnull.When the relay returns, it selects the oldest unpublished rows in batches of 500 with
FOR UPDATE SKIP LOCKED, writes them to the audit store, and marks them, catching up at whatever rate the audit store accepts.Two things need care: a metric for the age of the oldest unpublished row, with an alert at 5 minutes, so an hour-long outage is noticed in the first five; and the audit store's consumer must be idempotent on the outbox id, because the relay might have written a batch and crashed before marking it.
What the auditors see is a delay in the audit trail, never a gap, and the row's
created_atpreserves the true event time.
Q86. "What does @Transactional(readOnly = true) actually do, and how would you route read-only transactions to a replica?"
Reveal answer
Strong answer The flag does three concrete things and one thing people assume it does.
- Driver: it sets
Connection.setReadOnly(true), which PostgreSQL's driver turns intoSET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY, so a write inside actually fails on Postgres. MySQL's driver also sends a read-only start and the InnoDB engine can skip some transaction bookkeeping. - Hibernate: it sets the session's flush mode to
MANUAL, so no dirty checking happens at commit. That saves CPU and memory on large result sets because the persistence context does not keep snapshot copies. - Transaction manager: it tells the transaction manager not to expect a flush.
- What it does not do: guarantee no writes on every database. It is a hint plus a driver-dependent guard, not a security boundary.
Replica routing is built on it, in three parts.
- The routing datasource: extend
AbstractRoutingDataSourcewithdetermineCurrentLookupKeyreturningreplicawhenTransactionSynchronizationManager.isCurrentTransactionReadOnly()is true, wrapped in aLazyConnectionDataSourceProxy. - Why the proxy matters: without it the transaction manager fetches the connection at transaction start, before the read-only flag is bound, so routing sees the wrong value. The lazy proxy defers the real checkout to the first statement, when the flag is set.
- Read-your-writes: this becomes an application concern. A request that just wrote must not go to a lagging replica, so a short window after a write pins that user to the primary, which is a topic from Chapter E8.
Picture it The order of events inside getTransaction with and without the lazy proxy, and what each routing key and each kind of write does.
The setup: the recent() method and the routing datasource in the code below, plus one writer method to compare against.
@Transactional(readOnly = true)
public List<Order> recent() { return repo.findTop20ByOrderByCreatedDesc(); } // should go to the replica
@Transactional
public void rename(Long id, String name) { ... } // must go to the primary
Make the invisible visible: the same getTransaction for recent(), side by side.
WITHOUT LazyConnectionDataSourceProxy WITH it
1 doBegin: dataSource.getConnection() 1 doBegin: proxy hands back a stand-in, no real connection
routing asked now: read-only flag NOT set (nothing asked yet)
key = "primary" ✗ 2 prepareSynchronization: read-only flag = true
2 prepareSynchronization: flag = true 3 first SELECT: stand-in asks routing
(too late, connection already chosen) flag is true -> key = "replica" ✓
The trace: the second column as a call path.
Controller ──► proxy.recent()
└─► TransactionInterceptor
├─► getTransaction -> doBegin ✓ stand-in connection, autocommit handled lazily
├─► prepareSynchronization ✓ readOnly = true bound to the thread
└─► target.recent() -> first SELECT
└─► ReplicaRoutingDataSource.determineCurrentLookupKey() ✓ "replica"
What you see: a debug log line in determineCurrentLookupKey and the connection counts per server.
# illustrative output
routing key = primary (tx readOnly flag not bound yet) <- logged for recent()
pg primary: 120 active sessions pg replica: 0 active sessions <- the replica sits idle
Why: the transaction manager gets the connection in doBegin and only afterwards writes the read-only flag, so the routing datasource asks too early.
The fix: wrap the routing datasource in LazyConnectionDataSourceProxy, as in the code below.
What you see now: the same log line and the same counts.
# illustrative output
routing key = replica (recent)
routing key = primary (rename)
pg primary: 35 active sessions pg replica: 85 active sessions
Code inside a readOnly = true method | Outcome |
|---|---|
native UPDATE through JdbcClient, PostgreSQL with the default readOnlyMode | Throws: "cannot execute UPDATE in a read-only transaction" |
the same UPDATE on H2 or with readOnlyMode=ignore | Silently applied: the flag is a no-op |
| change a managed entity with a setter, then return | Silently not applied: FlushMode.MANUAL, no dirty checking |
| the method joins an existing read-write transaction | Silently ignored: the flag belongs to the outer transaction |
Going deeper The PostgreSQL JDBC driver's behaviour depends on its readOnlyMode connection property.
The default, transaction, does not change the session; it begins each transaction with BEGIN READ ONLY while setReadOnly(true) is set, so a write inside the transaction fails with "cannot execute INSERT in a read-only transaction".
always uses the session-level SET SESSION CHARACTERISTICS form, and ignore makes the flag a no-op. This matters for routing with a pooler: behind PgBouncer in transaction mode, session-level settings leak across clients, so transaction mode is the safe choice.
Verification is direct: with logging.level.org.hibernate.SQL=DEBUG and the driver's loggerLevel=TRACE you see the BEGIN READ ONLY, and a deliberate write in a test annotated readOnly = true must fail on PostgreSQL.
// What readOnly actually does — three separate effects, none of them enforcement:
@Transactional(readOnly = true)
public List<Order> recent() { ... }
// 1. Hibernate sets FlushMode.MANUAL: no dirty checking, no automatic flush.
// This is the real performance win — no snapshot comparison per entity.
// 2. Spring calls Connection.setReadOnly(true). Whether the driver does
// anything with it is driver-specific; PostgreSQL forwards it, others ignore it.
// 3. ❌ TRAP: It is a HINT, not a guarantee. A native UPDATE inside a readOnly method
// will still execute.
// Routing to a replica: a DataSource that picks by the current transaction.
public class ReplicaRoutingDataSource extends AbstractRoutingDataSource {
@Override protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? "replica" : "primary";
}
}
@Bean
DataSource dataSource(@Qualifier("primary") DataSource p,
@Qualifier("replica") DataSource r) {
var routing = new ReplicaRoutingDataSource();
routing.setTargetDataSources(Map.of("primary", p, "replica", r));
routing.setDefaultTargetDataSource(p);
// Lazy so the key is read when the connection is first USED, i.e. after
// the transaction has been marked read-only — not at getConnection() time.
return new LazyConnectionDataSourceProxy(routing); // ✅ FIX: without this wrapper every request routes to "primary"
// Result: readOnly = true -> key "replica" -> the SELECTs leave the primary
}
LazyConnectionDataSourceProxy is the part that makes it work. Without it the connection is acquired before the transaction's read-only flag is set, so every request routes to the primary and the replica sits idle — a bug that looks like the routing simply not working.
Land it readOnly is a flush-mode and driver hint that becomes a routing key only if the connection is obtained lazily.
- "A user updates their profile and the next page shows the old value. Your replica routing is working as designed. What now?"
That is replication lag meeting read-only routing, and the fix is to stop sending that user's reads to the replica for a short window after a write.
I keep a per-user "wrote at" timestamp, in a signed cookie or in Redis keyed by user id, set by a
TransactionSynchronization.afterCommiton any read-write transaction.The routing datasource's lookup key then returns
replicaonly if the transaction is read-only and the user's last write is older than the observed lag ceiling, say 2 seconds.For strict cases, a request can pass an explicit "consistent read" hint that always pins to the primary.
The lag ceiling itself comes from a metric:
pg_stat_replicationexposesreplay_lag, and I alert if it exceeds the window, because at that point the pinning is no longer sufficient and the correct action is to route everything to the primary until it recovers.- "Why does the transaction manager fetch the connection before the read-only flag is bound, and how do you check the proxy fixed it?"
The order inside
AbstractPlatformTransactionManager.getTransactionis: calldoBegin, which forJpaTransactionManagerobtains the connection and sets autocommit, and thenprepareSynchronization, which is what writes the read-only flag intoTransactionSynchronizationManager.So at the moment the routing datasource is asked for a connection,
isCurrentTransactionReadOnly()is still false and it routes to the primary.LazyConnectionDataSourceProxyreturns a stand-in connection duringdoBeginand only asks the routing datasource for a real one when the first statement is prepared, by which time the flag is set.To check, I add a debug log in
determineCurrentLookupKeyand run areadOnly = truemethod: the key must printreplica. In a test, two Testcontainers instances, or one database with two schemas, make the routing observable by inserting a marker row only in one.- "What are the costs of readOnly on the JPA side, and is there any risk?"
The benefit is that Hibernate sets
FlushMode.MANUALand marks loaded entities read-only, so it skips taking the snapshot copy it normally keeps for dirty checking, which halves the memory of a large result set and removes the flush-time comparison.The risk is that a write in a read-only method silently does nothing on databases whose driver ignores the flag: on H2 or on a driver with
readOnlyMode=ignore, the entity change is never flushed, the transaction commits, and the code appears to work while persisting nothing.On PostgreSQL it fails loudly, which is better. The other subtlety is that
readOnlyon a method that joins an existing read-write transaction is ignored, because the flag belongs to the outer transaction; Spring logs nothing about it.So I treat
readOnlyas an optimisation plus a routing key, and I keep a test on PostgreSQL that asserts a write under it fails.- "Would you route at the datasource at all, or somewhere else?"
For a service with a handful of read-heavy endpoints, I would route explicitly rather than by flag: a second
JdbcClientor repository bound to a replica datasource, injected only into the query-side services, so the decision is visible in code and reviewable.The
AbstractRoutingDataSourceapproach is elegant but invisible, and its failure mode, a stale read in a path nobody knew was routed, is hard to debug.In a larger fleet the routing often moves out of the application into a proxy such as PgBouncer with separate ports or the cloud provider's reader endpoint, which also handles replica failover; the application then just has two named datasources.
The flag-based routing earns its place when the codebase already marks every read path
readOnly = trueconsistently and the team wants replica offload without touching each service, which is a real situation in a monolith with hundreds of repositories.
Q87 · Scenario. "Alerts fire: 'HikariPool-1 – Connection is not available, request timed out after 30000ms', pool at its max of 30, on 6 of 8 instances. Database CPU is 20 percent. Walk through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the pool is exhausted while the database is idle, which means connections are held without doing database work. That is a leak or a hold, not load.
- Evidence:
hikaricp.connections.activepinned at 30,pendinggrowing, andhikaricp.connections.usageshowing very long checkouts. On the database,pg_stat_activityshows the service's sessions mostlyidle in transaction. A thread dump of one instance shows which code holds them. Enableleak-detection-threshold=10000on one instance to get stack traces for checkouts over 10 seconds. - Likely causes, ranked:
- a
@Transactionalmethod that makes a slow outbound HTTP call or waits on a lock inside the transaction, so each request holds a connection for the call's duration; open-in-view=truewith a slow response rendering or a controller calling a slow service after the repository work;- a
REQUIRES_NEWpool deadlock as in Q83, which explains why some instances are fine, since it depends on request interleaving; - a real leak from manual
getConnection()in a utility with a missing close; - long-running batch queries on the same pool as request traffic.
- a
- Fix:
- move the external call outside the transaction, or split the method so the transaction covers only the database work;
- set
open-in-view=false; - set
connection-timeout=3000so waits fail fast instead of piling up; - set
spring.transaction.default-timeoutso no transaction can hold a connection for 30 seconds; - give batch jobs their own small pool.
- Prevention: alert on
pending > 0for 30 seconds and on p99 checkout duration; keep leak detection on at a threshold above normal transaction time in production.
Picture it One instance at four moments, the thread that holds the connection, and a table from symptom to cause to action.
The setup: a transactional method that calls a slow partner inside the transaction.
@Transactional
public void confirm(String id) {
Order o = repo.findById(id).orElseThrow(); // connection checked out here (conn #4)
shipping.book(o); // ❌ TRAP: HTTP call, 8 s today, connection still held
o.setStatus(CONFIRMED);
} // commit, connection back to the pool
Make the invisible visible: the pool is a counter; each slow request pins one of its 30 slots.
| Moment | active | pending | checkout p99 | database CPU |
|---|---|---|---|---|
| healthy | 6 of 30 | 0 | 12 ms | 20 percent |
| partner slows to 8 s | 18 of 30 | 0 | 8 s | 20 percent |
| pool exhausted | 30 of 30 | 45 | 30 s (timeouts) | 20 percent |
| after the fix | 7 of 30 | 0 | 15 ms | 22 percent |
The trace: what one pinned request is doing.
http-nio-8080-exec-12 holds conn #4 for 8 s
OrderService.confirm
└─► ShippingClient.book
└─► RestClient.exchange ✗ waiting on the network, database idle
What you see: the leak-detection log, the dump and the database side.
# illustrative output
WARN com.zaxxer.hikari.pool.ProxyLeakTask : Connection leak detection triggered for org.postgresql.jdbc.PgConnection@3f2a on thread http-nio-8080-exec-12, stack trace follows
java.lang.Exception: Apparent connection leak detected
at com.shop.ShippingClient.book(...)
at com.shop.OrderService.confirm(...)
pg_stat_activity: 30 sessions from the service, state = idle in transaction, query = (last SELECT)
Why: the connection is checked out for the whole transaction, so the pool is held for as long as the HTTP call takes, while the database has nothing to do.
The fix: keep the HTTP call outside the transaction and fail fast on waits (see Q90 for the restructure), plus connection-timeout=3000 and a transaction default timeout.
What you see now: the same four numbers after the change (last row of the table above), and no leak-detection traces.
| Symptom | Root cause | Action |
|---|---|---|
active = max, database CPU low, sessions idle in transaction | HTTP call or lock wait inside @Transactional | move the call out, add a read timeout |
leak trace shows OpenEntityManagerInViewInterceptor at the bottom | OSIV holds the connection across rendering | open-in-view=false, return DTOs |
threads stuck in HikariPool.getConnection, each already holding one | REQUIRES_NEW pool deadlock | restructure or double the pool |
leak trace points at DataSource.getConnection() in a utility | missing close | try-with-resources |
| no leak traces, checkouts short but too many | plain load | scale or shorten holds |
Land it An exhausted pool with an idle database means connections are being held hostage by something that is not SQL, and the leak-detection stack trace names the kidnapper.
- "Why are only 6 of 8 instances affected?"
Because the cause depends on request mix and timing rather than on a fixed configuration.
The two healthy instances may simply not have received the traffic that triggers the hold, for example a tenant whose orders always call the slow shipping partner, if the balancer uses consistent hashing or sticky sessions.
If it is the
REQUIRES_NEWpool deadlock, it needs a moment when concurrent requests on that path exceed half the pool, which is a probabilistic event, so some instances have hit it and others have not yet.If it is a leak, the leak rate times uptime decides who is exhausted first, and the healthy pair may be the ones restarted most recently, which I check by comparing pod age with the alert time.
Comparing
hikaricp.connections.usagepercentiles across the eight and diffing the request routes served by the healthy pair against the others usually names the trigger.- "You moved the HTTP call out of the transaction and the alert still fires. What next?"
Then the hold was not that call, or not only that call, and I stop guessing and get evidence from the pool itself.
I set
spring.datasource.hikari.leak-detection-threshold=5000on one affected instance, wait for the next alert, and read the stack traces Hikari logs for every checkout older than 5 seconds; each trace names the exact method holding the connection.If the traces point into Hibernate flush or a query, the database side is slow for that query even though average CPU is 20 percent, so I check
pg_stat_activityfor lock waits andpg_locksfor the blocking session, since a single long-runningALTER TABLEor a stuck idle-in-transaction session can block everyone.If the traces show
OpenEntityManagerInViewInterceptorat the bottom, OSIV is holding connections across slow rendering. If there are no traces at all, the checkouts are short but too many, which is load, not a hold.- "What is the right connection-timeout, and what does lowering it to 3 seconds change for users?"
The right value is a little above the longest wait you are willing to make a user endure for a connection, which for an interactive API is 1 to 3 seconds, not the 30-second default.
Lowering it changes the failure from a 30-second hang into a fast 503, which sounds worse but is better on every axis: the user gets an answer, the thread is released to serve someone else, upstream retries have a chance within their own timeout, and the alert fires within seconds instead of after the queue has built up.
What it does not do is fix the shortage. So it is paired with a
@ControllerAdvicemappingCannotGetJdbcConnectionExceptionto 503 withRetry-After: 2, a metric on that mapping, and the actual fix for the hold.mapping pool exhaustion to a fast 503runs offline@RestControllerAdvice class PoolExhaustedAdvice { @ExceptionHandler(CannotGetJdbcConnectionException.class) ResponseEntity<Void> onPoolTimeout() { poolTimeouts.increment(); // metric on the mapping return ResponseEntity.status(503).header("Retry-After", "2").build(); } // with JpaTransactionManager the failure can surface as CannotCreateTransactionException: map it too }Under a real overload, the fast failure also lets the autoscaler react to error rate rather than to a latency that only rises after everything is already stuck.
- "How do you set spring.transaction.default-timeout safely across a service that has both web requests and batch jobs?"
I set the default for the common case and override for the exceptions.
spring.transaction.default-timeout=10scaps every transaction that does not declare its own, which is right for request-path work; a transaction that legitimately needs longer, such as a batch chunk or a migration step, declares@Transactional(timeout = 300)explicitly, and that declaration is a review flag.The timeout is enforced through statement query timeouts as in Q77, so it cannot cut a Java loop, which is fine because the point is to prevent a transaction from holding a connection through a slow query.
For batch jobs I go further and give them their own
DataSourceand transaction manager bean, qualifiedbatchTransactionManager, with a separate small Hikari pool, so their long transactions cannot compete with requests at all and the default timeout can be lower on the request pool than on the batch one.
Q88. "Explain how you would size a HikariCP pool from first principles, and which two lifetime settings must be aligned with the database and the network."
Reveal answer
Strong answer Start from the database, not the application. A database server executes queries on its cores; beyond a small multiple of the core count, extra concurrent connections just contend for CPU, locks, and buffer pool and make everything slower.
- Budget: HikariCP's guidance is connections ≈ cores × 2 + effective spindles, so an 8-core Postgres is happiest around 20 active connections total.
- Divide: split that budget across instances. 8 instances get 2 or 3 each, which feels tiny but is right. A connection pooler such as PgBouncer in transaction mode lets many application connections share few database connections when the instance count is high.
- Sanity check with Little's law: at 500 requests per second per instance and 20 milliseconds of connection hold time, you need 10 connections on average. If that exceeds the database budget, the real fix is shorter hold times, not a bigger pool.
- Fixed size: use
minimum-idleequal tomaximum-pool-size, so bursts never pay connection setup.
The two lifetime settings:
max-lifetime, default 30 minutes, must be shorter than the database's idle session limit (idle_session_timeoutin Postgres,wait_timeoutin MySQL) and shorter than any firewall or load balancer idle timeout between the application and the database. Otherwise Hikari hands out a connection the network already dropped and the first query fails.keepalive-timepings idle connections every few minutes to keep NAT and firewall state alive, and is the cheaper way to prevent the same drop.
Set connection-timeout low, 2 to 3 seconds, and validation-timeout below it.
# Pool size is NOT "more is better". Each connection is a backend process on
# PostgreSQL and a thread on MySQL; oversizing moves the contention into the
# database where it is more expensive.
#
# Start from: connections = ((core_count * 2) + effective_spindle_count)
# For a 4-core pod on SSD-backed storage that is roughly 8-10, not 100.
#
# Then check the arithmetic against the throughput you need:
# throughput = pool_size / average_query_time
# 10 connections / 5 ms = 2,000 queries/sec -- ample for most services
#
# And the fleet constraint: instances * pool_size must stay under the
# database's max_connections, with headroom for migrations and admin sessions.
# ❌ TRAP: 60 instances * 10 = 600 -> exceeds a 200-connection limit. Use a pooler.
spring.datasource.hikari.maximum-pool-size = 10
spring.datasource.hikari.minimum-idle = 10 # = max: avoid churn in a container
# ✅ FIX: THE TWO LIFETIMES THAT MUST BE ALIGNED WITH INFRASTRUCTURE.
# Both must be SHORTER than the shortest timeout anywhere in the path
# (database wait_timeout, load balancer idle timeout, NAT gateway, firewall).
# Otherwise the pool hands out a connection the network already killed, and
# you get intermittent "connection reset" on the first query.
spring.datasource.hikari.max-lifetime = 1740000 # 29 min, under a 30 min LB timeout
spring.datasource.hikari.idle-timeout = 600000 # 10 min
spring.datasource.hikari.connection-timeout = 3000 # fail fast, do not queue for 30s
spring.datasource.hikari.leak-detection-threshold = 20000
The max-lifetime rule is the one that causes intermittent production errors. Any middlebox that silently drops idle TCP connections will do so without telling the pool, so a connection must be retired by the pool before anything else in the path can kill it.
Picture it The arithmetic as numbers, and the life of one connection that a middlebox kills while it sits idle, before and after aligning the lifetimes.
The setup: the properties in the code above: a fixed pool of 10, max-lifetime 29 minutes, behind a load balancer that drops idle flows after 30 minutes. For the failing run, picture max-lifetime left at a value above the shortest timeout in the path.
Make the invisible visible: the sizing arithmetic.
| Question | Arithmetic | Answer |
|---|---|---|
| database budget, 8-core Postgres | 8 × 2 + 1 spindle | about 17, call it 20 |
| per instance, 8 instances | 20 / 8 | 2 or 3 connections |
| connections needed at 500 rps, 20 ms hold | 500 × 0.020 | 10 on average, over budget: shorten holds |
| capacity of 3 connections at 5 ms hold | 3 / 0.005 | 600 queries per second |
The trace: one connection against the network path.
t=0 pool opens conn #3 to the database ✓
t=6 min conn #3 is idle; the NAT/firewall forgets the flow, nobody tells the pool
t=12 min a request borrows conn #3 and sends its first query
└─► packet hits a dead flow ✗ error on the FIRST statement
(with keepalive-time=2 min: a ping at t=2, 4, 6 ... keeps the flow alive ✓)
What you see: the log on the first statement after an idle period.
# illustrative output
WARN HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@7a1c (This connection has been closed.). Possibly consider using a shorter maxLifetime value.
org.postgresql.util.PSQLException: An I/O error occurred while sending to the backend.
Why: the pool can only retire a connection before the first middlebox kills it; it cannot know when the network dropped one.
The fix: max-lifetime below the shortest idle timeout in the path, and keepalive-time below it too, both in the code above.
What you see now: no validation failures after idle periods.
# illustrative output
(no "Failed to validate connection" lines; hikaricp.connections.pending stays 0)
Land it The pool size is the database's budget divided by instances, and the lifetime must be shorter than every idle timeout between here and the database.
- "Two or three connections per instance sounds too small. What happens if a request needs a connection and all three are busy?"
It waits on Hikari's fair queue for up to
connection-timeout, and the question is how long that wait is.If the average hold time is 5 milliseconds, then even at 100 requests per second per instance the pool is busy half a millisecond per request on average and the queue is almost always empty; Little's law says three connections at 5 milliseconds each can serve 600 requests per second at full utilisation.
reading the queue from the metricsruns offline# illustrative output hikaricp.connections.max 3 hikaricp.connections.active 0.5 (average over the minute) hikaricp.connections.pending 0 hikaricp.connections.acquire p99 = 0.4 msA wait appears only if hold times are long, which means slow queries or connections held across non-database work, and the fix for that is shorter holds, not a bigger pool, because a bigger pool per instance multiplies across the fleet into database contention that makes every query slower.
I verify the assumption with
hikaricp.connections.pendingand thehikaricp.connections.acquiretimer: pending should be zero and acquire p99 under a millisecond in steady state.- "How would you find the right keepalive-time and max-lifetime for a specific environment?"
By reading every idle timeout between the pod and the database and picking the smallest. On the database, PostgreSQL's
idle_session_timeoutandidle_in_transaction_session_timeout, MySQL'swait_timeout, or a managed service's connection limit policy.In the network, cloud NAT gateways commonly drop idle TCP flows at 350 seconds on AWS and 10 minutes on GCP, load balancers at 60 seconds, and stateful firewalls anywhere from 5 to 60 minutes.
Then
keepalive-time, which pings idle connections with the driver'sisValid, goes below the smallest of those, for example 2 minutes when an ALB or NAT sits in the path, andmax-lifetime, default 30 minutes, goes below the database's own connection lifetime or the pooler'sserver_lifetime.The symptom that tells me I got it wrong is "connection reset" or "end of file from server" on the first statement after an idle period, logged by Hikari as a failed validation.
- "Why a fixed-size pool? Does not a variable pool save resources when idle?"
A variable pool saves a few idle database sessions and costs latency exactly when it hurts.
When traffic rises, the pool has to create connections, which means a TCP handshake, TLS negotiation, and authentication, typically 20 to 100 milliseconds each, on the critical path of the first requests of the burst; those requests are the ones that become the p99.
It also produces connection storms: ten instances all growing at the same moment hit the database with a burst of new sessions.
HikariCP's own guidance is
minimum-idleequal tomaximum-pool-sizefor this reason, and the idle cost is small, since a PostgreSQL backend at idle uses a few megabytes.The exception is a very large fleet against a pooler where sessions really are scarce, and there the answer is a small fixed pool rather than a variable one.
- "Where does a transaction-mode pooler like PgBouncer change this arithmetic?"
It moves the database budget out of the application.
With PgBouncer, each instance can keep a fixed pool of, say, 10 connections to the pooler, which are cheap, and the pooler multiplexes all of them onto a small set of real backends sized by the cores × 2 rule.
A database connection is assigned only while a transaction is open, so idle application connections cost nothing on the primary. The arithmetic becomes: application pools sized for local concurrency without worrying about the fleet, and one pooler pool sized for the database.
The price is that anything relying on session state across transactions breaks, so no
SEToutside a transaction, no session-level advisory locks, noLISTEN, and named prepared statements need PgBouncer 1.21 or later withmax_prepared_statementsset, or the driver'sprepareThreshold=0. Hikari'smax-lifetimethen aligns with the pooler'sserver_idle_timeout, not the database's.
Q89 · Design. "We are scaling from 5 to 60 instances of an order service against one PostgreSQL primary with a 200-connection limit. Design the connection strategy."
Reveal answer
Strong answer Requirements:
- 60 instances against a hard limit of 200 connections, which the database cannot use efficiently anyway on, say, 16 cores;
- no connection storms on deploy;
- separate lanes for request traffic and batch work.
Design: introduce PgBouncer in transaction pooling mode between the services and the primary.
- Sizes: the services each keep a small fixed Hikari pool of 5, so 300 application connections to PgBouncer, which multiplexes them onto about 40 real database connections, close to the cores × 2 guidance.
- Transaction mode: a database connection is assigned only for the duration of a transaction, so idle application connections cost nothing on the primary. The constraint is that session-level state cannot be used: no
SEToutside a transaction, no prepared statement caching by name unless PgBouncer is configured for it, and no advisory locks across transactions. - Timeouts: Hikari is configured with
connection-timeout=2000and amax-lifetimebelow PgBouncer'sserver_idle_timeout. - Lanes: batch and reporting work gets a second Hikari pool bound to a separate PgBouncer pool with its own limit, so a report cannot consume the request lane.
- Later and deploys: read replicas, when added, get their own routing as in Q86. Deploys are rolled in batches of 10 to avoid a reconnect storm.
Trade-offs: PgBouncer is a new component to run highly available, and transaction mode forbids some driver features; the alternative of 60 × 3 direct connections is simpler but leaves no headroom for scaling further.
What I would not do: raise the database's max_connections to 600, because that trades a visible limit for invisible contention.
Picture it The connection counts for five options at three moments (steady state, rolling deploy, scale-up), then what you see on each side of PgBouncer.
The setup: the settings that make the design real: Hikari in each pod and PgBouncer in front of the primary.
# application.properties, each of the 60 pods
spring.datasource.hikari.maximum-pool-size = 5
spring.datasource.hikari.minimum-idle = 5
spring.datasource.hikari.connection-timeout = 2000
spring.datasource.hikari.max-lifetime = 540000 # below server_idle_timeout
# pgbouncer settings
pool_mode = transaction
default_pool_size = 40 # real backends on the primary
max_client_conn = 1000
server_idle_timeout = 600
Make the invisible visible: who holds how many database connections.
| Option | Steady state | During a rolling deploy of all 60 | Verdict |
|---|---|---|---|
| 60 pods × 3 direct | 180 | up to 360 while old and new pods overlap | Fails the limit: startup errors |
| 60 pods × 5 direct | 300 | 600 | Exceeds the limit at once |
raise max_connections to 600, 60 × 10 direct | 600 | 1200 | Allowed but slower: contention on 16 cores |
| 60 pods × 5 through PgBouncer | 300 client, 40 real | 600 client, 40 real | Works: the primary still sees 40 |
| same, deploy in batches of 10 | 300 client, 40 real | 350 client, 40 real | Works, and no reconnect storm |
The trace: one request through the layers.
pod (Hikari, 5 conns) ──► PgBouncer (transaction mode) ──► primary (40 backends)
BEGIN ................ borrows a backend ✓
statements ........... same backend for the whole transaction
COMMIT ............... backend returned; idle pod conns cost nothing
What you see: the error without the pooler and the pooler's own view with it.
# illustrative output
before: FATAL: sorry, too many clients already (during the rolling deploy, pods fail to start)
after: SHOW POOLS;
database | cl_active | cl_waiting | sv_active | sv_idle
orders | 38 | 0 | 31 | 9
Why: the database limit counts server connections, and a transaction-mode pooler turns 300 client connections into about 40 server connections.
| Symptom | Root cause | Action |
|---|---|---|
| pods crash-loop with "too many clients" during a deploy | old and new pods overlap and exceed the limit | PgBouncer, and roll in batches |
| "prepared statement S_1 does not exist" | named server-side prepares meet transaction mode | max_prepared_statements or prepareThreshold=0 |
| reports slow down request traffic | one shared lane | second Hikari pool and a separate PgBouncer pool |
cl_waiting above zero for long | pooler pool too small for load, or holds too long | shorten holds first, then size the pool |
Land it Above a couple of dozen instances, the pool moves out of the application and into a transaction-mode pooler, and each instance keeps a pool small enough to be honest.
- "A week after PgBouncer goes in, a query that uses a prepared statement fails with 'prepared statement S_1 does not exist'. What happened?"
The PostgreSQL JDBC driver names server-side prepared statements after a statement has run
prepareThresholdtimes, default 5, and then sends only the name.In transaction mode, the next transaction may land on a different backend where that name was never prepared, so the backend replies that it does not exist. Three fixes, in order of preference.
Upgrade PgBouncer to 1.21 or later and set
max_prepared_statements=200, which tracks named statements per client and re-prepares on the backend transparently. Or setprepareThreshold=0in the JDBC URL to disable server-side prepares, at a small parse cost per query.the error and the three fixesruns offline# illustrative output org.postgresql.util.PSQLException: ERROR: prepared statement "S_1" does not exist # fix 1: PgBouncer 1.21 or later max_prepared_statements = 200 # fix 2: driver URL, no server-side prepares jdbc:postgresql://pgbouncer:6432/app?prepareThreshold=0 # fix 3: pool_mode = session (loses the multiplexing)Or switch the pooler to session mode, which loses the multiplexing that was the whole point. I would also check for
SET search_pathorSET application_nameat connection init, which are session state and need to be in PgBouncer'sserver_reset_queryor moved into each transaction.- "The requirement changes: now there are also two read replicas. Where does that fit?"
The replicas get their own PgBouncer pools, or their own pooler instances, and the application gets a second datasource for reads. Routing is by
readOnlytransactions through the lazy routing datasource from Q86, or explicitly through a query-side repository, with the read-your-writes window handled per user.The connection budget becomes three budgets: 40 primary backends for writes and consistent reads, and per replica perhaps 60 backends, since replicas serve heavier analytical reads.
I put the replicas behind one balanced endpoint so a replica failure is a routing change rather than an application change, and I make the reader datasource optional: if the reader endpoint is down, the routing falls back to the primary with a metric, so a replica outage degrades to higher primary load rather than to errors.
Replication lag is monitored, and above 5 seconds the router pins everything to the primary automatically.
- "What would you cut under time pressure, and what is the risk of the cut?"
The cut that costs the least is skipping the separate batch lane at first: run batch work through the same pooler pool with a lower Hikari maximum, say 2, and a statement timeout, and accept that a heavy report can delay requests briefly.
The cut I would resist is going without PgBouncer and just dividing 200 by 60 instances: 3 connections each is workable, but it leaves no margin for one more scale-up, and a rolling deploy of all 60 doubles the count briefly as new pods start while old ones drain, which trips the limit and causes startup failures.
If PgBouncer cannot be deployed in time, I would set
spring.datasource.hikari.initialization-fail-timeout=-1so pods start even if the limit is hit, set the pool to 2 withminimum-idleat 1, and roll in batches of 5; then treat the pooler as the first follow-up.- "How do you run PgBouncer itself so it is not the new single point of failure?"
As a set of identical stateless instances, since PgBouncer holds no durable state.
On Kubernetes that is a Deployment of three replicas behind a ClusterIP Service, each pointed at the same primary, with the total of their
default_pool_sizevalues equal to the database budget, so 3 × 14 backends. Clients connect through the Service, which spreads connections.A pooler instance dying costs the transactions in flight on it, which the application sees as connection errors and retries idempotently. The pooler's own limits,
max_client_connaround 1,000 per instance, must exceed the application fleet's total pool size with headroom.Managed alternatives such as RDS Proxy do the same job with the operational burden removed, and as of Aug 2026 that is what I would choose on AWS unless the transaction-mode feature gaps matter.
Whatever runs it, a game day that kills a pooler instance under load is part of the rollout.
Q90 · Scenario. "Leak detection logs a stack trace: a connection was held 45 seconds, and the stack shows OrderService.confirm → ShippingClient.book → RestClient.exchange. What is wrong, and how do you restructure?"
Reveal answer
Strong answer In diagnosis order:
- Symptom: a database connection held for the duration of an HTTP call. The stack proves the outbound call is inside the transaction opened by
confirm. - Evidence:
confirmis@Transactional; the shipping client has a long or missing read timeout; the shipping provider is slow today. - Why it is wrong on three counts: it ties pool capacity to a third party's latency; if the HTTP call succeeds and the commit then fails, a shipment is booked for an unconfirmed order, so the transaction gave a false sense of atomicity; and if the commit succeeds after the HTTP call timed out, the order is confirmed without a shipment.
- Restructure: split into three steps in a non-transactional orchestrator.
- Step one: a short transaction that validates and moves the order to
CONFIRMINGand writes an outbox row "book shipment". - Step two: the call to the shipping provider, made by a relay or the same request outside any transaction, with a 3-second timeout and an idempotency key derived from the order id so a retry cannot double-book.
- Step three: a short transaction that records the booking reference and moves the order to
CONFIRMED.
CONFIRMINGwith a retry, and a sweeper resolves stuck ones. If a synchronous response is required, the request performs all three steps but holds a connection only during one and three. - Step one: a short transaction that validates and moves the order to
- Prevention: an architecture rule that
@Transactionalmethods do no I/O other than the database, checked in review and by an ArchUnit test that forbidsRestClientusage from transactional classes.
Picture it The same request before and after the restructure, with the leak log, the order states over time, and where each connection is held.
The setup: confirm is transactional and calls the shipping client inside it.
// ❌ TRAP: HTTP inside the transaction
@Transactional
public void confirm(String id) {
Order o = repo.findById(id).orElseThrow();
String ref = shipping.book(o); // 45 s today, connection held the whole time
o.markConfirmed(ref);
}
// ✅ FIX: three steps, no @Transactional on the orchestrator
public void confirm(String id) {
Order o = orders.beginConfirm(id); // tx 1: CONFIRMING + outbox row, commit
String ref = shipping.book(o, "order-" + id); // no connection held; timeout 3 s; idempotency key
orders.completeConfirm(id, ref); // tx 2: CONFIRMED + reference, commit
}
// Result: the pool is held for milliseconds in tx 1 and tx 2, not for the HTTP call
The trace: one hop per line, before and after.
BEFORE
Controller ──► proxy.confirm
└─► target.confirm conn #4 checked out
└─► ShippingClient.book
└─► RestClient.exchange ✗ 45 s, conn #4 still held
AFTER
Controller ──► confirm (no transaction)
├─► orders.beginConfirm ✓ conn borrowed, commit, returned (a few ms)
├─► shipping.book ✓ no connection held
└─► orders.completeConfirm ✓ conn borrowed, commit, returned (a few ms)
What you see: the leak warning, and the order state at each moment.
# illustrative output
WARN ProxyLeakTask : Connection leak detection triggered for org.postgresql.jdbc.PgConnection@5b2e on thread http-nio-8080-exec-4, stack trace follows
at com.shop.OrderService.confirm -> ShippingClient.book -> RestClient.exchange
hikaricp.connections.usage p99 = 45 s
| Moment | Order status | Shipment at provider | Reading |
|---|---|---|---|
| after step one | CONFIRMING | none | outbox row written |
| during step two | CONFIRMING | booked, key order-4711 | no connection held |
| crash before step three | CONFIRMING | booked | sweeper asks the provider with the same key |
| after step three | CONFIRMED | booked, reference stored | done |
Why: a transaction cannot make an HTTP call atomic, and holding it open ties the pool to the provider's latency.
What you see now: no leak warning.
# illustrative output
hikaricp.connections.usage p99 = 12 ms (confirm path)
Land it A transaction cannot make an HTTP call atomic, so keep it out and use state plus idempotency to make the two-step sequence safe.
- "The product owner says the confirm endpoint must stay synchronous and return the shipment reference. Does your restructure still work?"
Yes, and the request path does all three steps in sequence on the same thread, just not inside one transaction.
The controller calls an orchestrator method with no
@Transactional: step one,orderService.beginConfirm(id), a short transaction that flips the state toCONFIRMINGand commits, releasing the connection in a couple of milliseconds; step two,shippingClient.book(order)with a 3-second timeout and an idempotency key, holding no connection; step three,orderService.completeConfirm(id, ref), another short transaction.The response carries the reference.
The latency the user sees is the same as before, since the HTTP call dominated it anyway; what changed is that the pool is held for milliseconds instead of seconds, and a crash between steps leaves a
CONFIRMINGorder that a sweeper resolves by querying the shipping provider with the same idempotency key. The synchronous requirement never needed the transaction to span the call.- "What does the sweeper for stuck CONFIRMING orders actually do, and how does it avoid double booking?"
It runs every minute under a ShedLock guard, selects orders in
CONFIRMINGolder than 2 minutes withFOR UPDATE SKIP LOCKED, and for each one asks the shipping provider "do you have a booking for idempotency key order-4711".Providers that support idempotency keys answer with the existing booking, and the sweeper completes the order with that reference.
If the provider has no booking, the sweeper either re-issues the booking with the same key, which is safe precisely because the key makes the call idempotent, or after N attempts moves the order to
CONFIRM_FAILEDfor a human.Double booking is impossible as long as every call uses the same key derived from the order id, not a random value per attempt.
If the provider does not support idempotency keys, the sweeper must query by order reference before retrying, and the design accepts a rare manual reconciliation.
- "The ArchUnit rule seems heavy-handed. Are there legitimate reasons to do I/O inside a transaction?"
A few, and they should be explicit exceptions. Reading a small, fast, cached configuration value from Redis is harmless. Writing to a second transactional resource under a real distributed transaction coordinator, which is rare in modern services.
Publishing to Kafka inside a transaction when the outbox is not in place is common but is exactly the case the rule exists to catch, so it is not an exception.
The rule I actually write is narrower than "no I/O": classes annotated
@Transactionalor containing such methods may not depend onRestClient,WebClient,KafkaTemplate, or the shipping client interfaces, and it is applied to the application service package only.When a legitimate exception exists, the class is listed by name in the test with a comment explaining why. Heavy-handed in code review is cheaper than a leak-detection stack trace at three in the morning.
- "How do you verify the restructure worked, beyond the leak warning going away?"
With three measurements. First,
hikaricp.connections.usage, the histogram of how long each checkout lasted, whose p99 for the confirm path should drop from seconds to under 20 milliseconds; I tag it by route using aMeterFilteror read it per pod during a targeted load test.Second, a fault-injection test in CI using WireMock with a fixed 10-second delay on the shipping endpoint: with 50 concurrent confirms and a pool of 10, the old code exhausted the pool and the new code must show zero
hikaricp.connections.pendingwhile the calls wait.Third, a crash test: kill the process between step two and three in a test harness, restart, run the sweeper, and assert exactly one booking and a
CONFIRMEDorder. Only the third proves the correctness claim; the first two prove the capacity claim.
This group stays at the Boot level of data access: what the repository proxy does, how to move rows in bulk, and how to pick a locking strategy.
Q91. "What is Open Session In View, why is it on by default in Boot, and why do you turn it off?"
Reveal answer
Strong answer Open Session In View, or OSIV, is an interceptor, OpenEntityManagerInViewInterceptor, that opens a JPA EntityManager at the start of every web request and keeps it open until the response is written.
Its purpose is convenience: a controller can return an entity with lazy associations, and Jackson can trigger those lazy loads while serialising, because the session is still open.
Boot enables it by default with spring.jpa.open-in-view=true and logs a warning at startup telling you it did. Turn it off for three reasons.
- Connection hold time: the entity manager acquires a connection on first use and holds it until the request ends. A request that does 5 milliseconds of database work and 200 milliseconds of rendering or downstream calls holds a connection for 205 milliseconds, which is the number-one cause of pool exhaustion in view-rendering services.
- Hidden N+1 queries: lazy loads during serialisation fire queries nobody sees in the service layer, so a list endpoint quietly issues hundreds of selects, each outside any explicit transaction and each in autocommit.
- A blurred boundary: once it is off, a
LazyInitializationExceptiontells you exactly which query needs a fetch join or a projection, which is a design improvement forced by an error.
With it off, controllers return DTOs or projections built inside the service's transaction, which is what you want anyway.
# Boot enables this by default and logs a warning about it at startup.
spring.jpa.open-in-view = true # ❌ TRAP: the default
#
# What it does: a filter opens a Hibernate Session at the START of the request
# and keeps it open until the response is written. Lazy loading therefore works
# anywhere, including inside Jackson serialisation.
#
# What it costs:
# 1. A DATABASE CONNECTION IS HELD FOR THE WHOLE REQUEST, including time spent
# calling other services and writing bytes to a slow client. Pool exhaustion
# under load with no slow query anywhere.
# 2. Lazy loads happen during serialisation, so N+1 queries are invisible in
# the service layer and appear as unexplained latency.
# 3. Queries run outside any transaction, each in its own auto-commit.
#
spring.jpa.open-in-view = false # ✅ FIX: what production services should set
// Result: after open-in-view=false, anything relying on lazy loading during
// serialisation throws LazyInitializationException. That is the point: the
// exception is showing you where a hidden query was happening.
// ✅ FIX: fetch deliberately, in the query:
@EntityGraph(attributePaths = {"lines", "customer"})
Optional<Order> findWithLinesById(Long id);
// ...and to return a DTO, so an entity never reaches the serialiser at all:
@Transactional(readOnly = true)
public OrderDto get(Long id) {
return OrderDto.from(repo.findWithLinesById(id).orElseThrow());
}
The exceptions after turning it off are a feature, not a regression. Each one marks a place where a query was being issued during response serialisation, outside any transaction, while holding a pooled connection.
Picture it One request on a timeline with OSIV on, where the connection and the hidden selects are, and the same request with OSIV off.
The setup: a controller that returns entities, with Order.lines lazy.
@GetMapping("/orders")
List<Order> list() { // ❌ TRAP: entities reach Jackson
return repo.findAll(); // Order.lines is LAZY
}
Make the invisible visible: the life of the EntityManager and the connection during one request.
# illustrative output
t=0 ms OpenEntityManagerInViewInterceptor opens an EntityManager (no connection yet)
t=2 ms repo.findAll() runs its first SELECT -> conn #4 checked out
t=7 ms findAll returns; the session stays open, conn #4 stays with it ✗
t=8-205 ms Jackson serialises: order.getLines() for every order -> one SELECT each (N+1)
t=207 ms response written, session closed, conn #4 back in the pool
The trace: one hop per line.
Request ──► OpenEntityManagerInViewInterceptor EntityManager opened
└─► Controller.list
└─► repo.findAll() SELECT orders ✓
└─► Jackson writes JSON
└─► order.getLines() x 100 SELECT lines, 100 times ✗ outside any transaction, autocommit
Response written ──► EntityManager closed conn #4 released after 205 ms
What you see: the startup warning, the SQL and the pool numbers.
# illustrative output
WARN JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. ...
select o.id, o.status from orders o -- 1 statement
select l.* from order_lines l where l.order_id=? -- repeated 100 times
hikaricp.connections.usage p99 = 205 ms (5 ms of it is database work)
Why: the session, and with it the connection, is released when the response is written, not when the repository call returns.
The fix: open-in-view=false, fetch in the query and return a DTO, as in the code above.
What you see now: the same request with the fix.
# illustrative output
select o.id, o.status, l.* from orders o left join order_lines l on l.order_id = o.id -- 1 statement
hikaricp.connections.usage p99 = 7 ms
(a forgotten fetch now throws LazyInitializationException instead of issuing a silent query)
Land it OSIV trades connection time and hidden queries for convenience, and a service that cares about its pool sets it to false and returns DTOs.
- "If it is that harmful, why is it still on by default, as of today?"
Compatibility and the size of the change.
Boot's team has said publicly that they consider the default wrong but that flipping it would break a large fraction of existing applications on upgrade with
LazyInitializationExceptionin places their tests do not cover, which is worse than a warning.So since Boot 2.0 the compromise is the startup warning, "spring.jpa.open-in-view is enabled by default", which appears unless you set the property explicitly either way.
As of Aug 2026, Boot 4.x still defaults it to true for the same reason; the property is the one line every new service template should set to false on day one, and the platform starter I described in Q5 does that.
The convention I follow is that the property is always set explicitly in
application.yml, so a reader knows the team decided rather than inherited.- "Does OSIV hold a connection for the whole request, or only after the first query?"
Only after the first query, but until the end of the request. The interceptor opens an
EntityManager, which is cheap and has no connection yet; Hibernate acquires the JDBC connection lazily when the first statement runs, or at transaction start if a@Transactionalmethod begins.The problem is release: with OSIV, the connection release mode is effectively "on close of the session", and the session closes when the response has been written, so from the first query onward the connection is held across service work, outbound calls, and serialisation.
Without OSIV, Hibernate's default release mode in Boot returns the connection at the end of each transaction.
So a request that never touches the database costs nothing under OSIV, and a request that touches it early and then spends 500 milliseconds elsewhere costs 500 milliseconds of pool.
That is why the damage scales with the slowest part of the request, not with the database work.
- "What is the WebFlux or virtual-thread equivalent of this problem?"
WebFlux has no OSIV because there is no thread to bind a session to; the equivalent property
spring.data.jpa.repositories.bootstrap-modeis unrelated, and JPA on WebFlux is discouraged anyway.With virtual threads on MVC, OSIV behaves exactly as before, since the
EntityManageris bound to the virtual thread byThreadLocaland released at the end of the request; what changes is that thread starvation is gone, so the visible failure moves entirely to pool exhaustion, and it arrives faster because the server accepts more concurrent requests.So virtual threads make OSIV more dangerous, not less.
The general form of the problem in any model is a resource acquired early and released late, and the general cure is scoping the resource to the work that needs it, which for JPA means the transaction boundary in the service layer.
- "How would you turn it off safely in a large existing service?"
Find the breakages before users do. First, set
open-in-view=falsein the integration test profile only and run the suite; everyLazyInitializationExceptionnames an endpoint and an association to fix.Second, for coverage the suite lacks, enable it in staging behind traffic replay, since the exception is deterministic per endpoint rather than timing dependent. Third, fix endpoints one at a time with DTO projections or fetch joins, as in Q92, and merge each fix independently.
Fourth, flip the property in production during low traffic with a rollback ready, which is just flipping it back, since no data changes. A useful interim guard is
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=falseleft at its default, because turning that on would hide the same problem in a worse way.The whole exercise usually takes a week for a service with a few dozen endpoints.
Q92 · Scenario. "After setting open-in-view=false, several endpoints throw LazyInitializationException: could not initialize proxy - no Session. The team wants to turn it back on. What do you do instead?"
Reveal answer
Strong answer In diagnosis order:
- Symptom: entities are leaving the transaction with uninitialised lazy associations, and something outside the transaction, usually Jackson in the controller, touches them. This was always happening; OSIV hid it with a long-lived session.
- Evidence: each stack trace names the entity and the association, for example
Order.lines; andshow-sqlin a test shows the queries that used to fire during serialisation. - Cause: controllers return JPA entities directly and rely on lazy loading at render time.
- Fix, per endpoint, in order of preference:
- DTO or projection: return a DTO or an interface projection built inside the service's
@Transactionalmethod, so the data is loaded where the session exists and the API shape is explicit. - Fetch join or entity graph: where the entity graph is genuinely needed, load it with a fetch join in
@Queryor an@EntityGraphon the repository method, so one query loads what the endpoint needs. - Wider boundary: for the rare case where the controller must do the assembly, widen the transaction boundary to a thin application service, never to the controller.
- Never:
hibernate.enable_lazy_load_no_trans, which reopens a session per lazy load and multiplies the query count.
- DTO or projection: return a DTO or an interface projection built inside the service's
- Prevention: an ArchUnit test that controllers do not return
@Entitytypes, and a query-count assertion in tests for list endpoints. Turning OSIV back on would restore the pool problem and keep the hidden N+1s.
// ❌ TRAP: The exception means: the entity left the persistence context with an
// uninitialised proxy, and something touched it after the transaction closed.
// Turning open-in-view back on hides it and holds a connection for the whole
// request. These are the four real fixes, in order of preference.
// ✅ FIX 1 — fetch what you need, in the query. Most specific, no N+1.
public interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = {"lines", "customer"})
Optional<Order> findWithLinesById(Long id);
@Query("select o from Order o join fetch o.lines where o.status = :s")
List<Order> findByStatusWithLines(@Param("s") Status s);
}
// ✅ FIX 2 — a projection. Fetches only the columns the response needs and
// returns something that is not an entity, so laziness cannot bite at all.
public interface OrderSummary {
Long getId();
String getCustomerName(); // resolves customer.name via the property path
BigDecimal getTotal();
}
List<OrderSummary> findByStatus(Status s);
// ✅ FIX 3 — map to a DTO inside the transaction, so the boundary is explicit.
@Transactional(readOnly = true)
public OrderDto get(Long id) {
Order o = repo.findWithLinesById(id).orElseThrow();
return OrderDto.from(o); // all access happens while the context is open
}
// Result: no lazy proxy ever leaves the transaction
// ❌ TRAP (FIX 4) — the anti-pattern to avoid: Hibernate.initialize(o.getLines())
// in a loop. It works, and it is N+1 with extra steps.
Read fixes 2 and 3 together. The durable answer is that entities should not escape the service layer at all — once a DTO crosses the boundary, lazy loading is structurally impossible rather than merely avoided.
Picture it What the controller holds when the exception fires, the SQL and exception it produces, and what each fix does to the SQL.
The setup: a controller returning the entity, after open-in-view=false.
@GetMapping("/orders/{id}")
Order get(@PathVariable Long id) { // ❌ TRAP: the entity leaves the service
return service.findOrder(id); // service is @Transactional; lazy "lines" is not loaded yet
} // Jackson then calls order.getLines() with no session
Make the invisible visible: the entity as the controller receives it.
# illustrative output
Order@41 {
id = 41
status = NEW
lines = PersistentBag [UNINITIALIZED, session = null] <- a placeholder, not a list
}
The trace: one hop per line.
Controller ──► service.findOrder(41)
└─► transaction opens, SELECT order, transaction closes ✓ session gone
Controller ◄── Order with lines = UNINITIALIZED
Jackson ──► order.getLines().size()
└─► no session to load with ✗ LazyInitializationException
What you see: the exception and the HTTP result.
# illustrative output
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role 'com.shop.Order.lines': could not initialize proxy - no Session
(usually wrapped by Spring MVC in HttpMessageNotWritableException)
HTTP/1.1 500 Internal Server Error
Why: the lazy collection can only load while its session is open, and with OSIV off the session ends with the service transaction.
The fix: FIX 1, 2 or 3 in the code above. They differ in how many statements they issue.
| Choice | SQL issued | Outcome |
|---|---|---|
| OSIV back on | 1 for orders, plus 1 per order for lines, in autocommit | Works but N+1 and a connection held for the whole request |
@EntityGraph(attributePaths = {"lines", "customer"}) | 1 join | Works, one statement |
interface projection OrderSummary | 1 with only the needed columns | Works, laziness cannot occur |
Hibernate.initialize(o.getLines()) in a loop | 1 per order | Works, N+1 with extra steps |
enable_lazy_load_no_trans=true | 1 per lazy access, each in a new session | Silently works, multiplies queries |
What you see now: after FIX 1.
# illustrative output
select o.*, l.*, c.* from orders o left join order_lines l on l.order_id = o.id left join customer c on c.id = o.customer_id where o.id = ?
HTTP/1.1 200 OK (1 statement, no LazyInitializationException)
Land it The exception is the design telling you where the API needs a DTO or a fetch join, so fix each endpoint rather than reopening the session for all of them.
- "You added a fetch join and now the list endpoint returns duplicate parents. Why, and what is the fix?"
A fetch join on a collection produces one SQL row per child, so a parent with five lines appears five times in the JDBC result and, on Hibernate 5, five times in the entity list.
Hibernate 6 and later de-duplicates parents automatically, so as of Aug 2026 on Boot 3.x and 4.x this specific symptom means an older Hibernate or a query returning a projection rather than entities.
On Hibernate 5 the fix is
SELECT DISTINCT o FROM Order o JOIN FETCH o.lineswithhibernate.query.passDistinctThrough=falseso the distinct is applied in memory rather than sent to SQL. The related trap is pagination: a fetch join on a collection plusPageablemakes Hibernate load everything and paginate in memory, logged as "firstResult/maxResults specified with collection fetch; applying in memory".For paged list endpoints, fetch the parents with pagination first, then load the children for that page with a second query using
@BatchSizeor anINlist.- "The team says DTOs everywhere is a lot of boilerplate. What do you say?"
I agree, and I point at the tools that remove most of it.
Spring Data interface projections declare the shape as an interface with getters and are populated by Hibernate directly from a query, with no mapping code; record-based DTO projections use a constructor expression, and Spring Data can infer them from the record's components.
MapStruct generates mappers at compile time for the cases where entity and DTO differ.
The boilerplate that remains is the DTO type itself, which is the API contract, and it is exactly what should be written by hand because it is what clients depend on and what changes independently of the schema.
The alternative, serialising entities, means every column addition is an API change, every lazy association is a latent N+1, and Jackson annotations end up on persistence classes. I would rather write a record than debug that.
- "How do you make sure the N+1 does not come back six months from now?"
With an assertion on query count in the tests for list endpoints.
Hibernate statistics, enabled in the test profile with
hibernate.generate_statistics=true, exposegetPrepareStatementCount, and a small JUnit extension resets it before the test and asserts a ceiling afterwards, for example "listing 50 orders must execute at most 3 statements".Libraries such as the datasource-proxy test helpers do the same with a
QueryCountHolder. The test fails the moment someone adds a lazy field to the DTO builder that triggers per-row loads.In production, the second guard is the JDBC observation from datasource-micrometer, which gives a span per statement, so a trace for a list request with 200 child spans is visible on the dashboard as an outlier.
The third is the ArchUnit rule that controllers cannot return entity types, which prevents the original cause.
- "Is @EntityGraph better or worse than JOIN FETCH in @Query?"
They generate the same kind of SQL, so the difference is where the intent lives.
@EntityGraph(attributePaths = {"lines", "customer"})on a derived query method keeps the method name readable and lets the graph be reused across methods, and it composes withSpecificationqueries where a hand-written JPQL cannot.JOIN FETCHinside@Queryis explicit and reviewable next to the rest of the query, which matters when the query already has conditions and ordering.Both share the same limits: fetching two collections at once produces a cartesian product, which Hibernate refuses for bags with
MultipleBagFetchException, and both paginate in memory when a collection is fetched.My rule is
@EntityGraphfor simple lookups and Specifications,JOIN FETCHwhen I am writing the query anyway, and neither for more than one collection, where@BatchSizeor a second query is the right tool.
Q93. "How does Spring Data JPA turn an interface into a working repository, and where would you stop using derived query methods?"
Reveal answer
Strong answer How the interface becomes a repository, in order:
- Scan: at startup,
@EnableJpaRepositories, applied by auto-configuration, scans for interfaces extendingRepositoryand registers aJpaRepositoryFactoryBeanfor each. - Proxy: the factory creates a JDK proxy implementing your interface.
- Inherited methods: calls to methods inherited from
JpaRepository, such assaveandfindById, are delegated to aSimpleJpaRepositoryinstance. It is itself annotated@Transactional(readOnly = true)at class level with read-write on the mutating methods, which is why repository calls work without your own annotation. - Declared methods: they are handled by a
QueryExecutorMethodInterceptor. If the method has@Query, the JPQL or native SQL is parsed once; otherwise thePartTreeparser turns the name into a query at startup, so a misspelled property fails the boot rather than the first call. - Return types are adapted:
Optional,List,Page,Slice,Stream, and projections, whether interface-based or DTO constructor expressions.
Stop using derived names when:
- the name exceeds about three conditions;
- the query needs a join fetch, aggregation, or a subquery;
- you need a projection to avoid loading whole entities;
- the SQL will be reviewed by a DBA.
At that point an explicit @Query is clearer and reviewable.
For dynamic filters use Specification or Querydsl rather than a dozen derived methods. And for anything set-based, such as "mark all expired orders", use a modifying @Query with @Modifying(clearAutomatically = true) rather than loading and saving entities one at a time.
The persistence context, dirty checking, and fetch strategies behind all of this are Chapter E5.
Picture it The generated proxy written out, what each call becomes, and the startup failure for a misspelled name.
The setup: a repository interface with one inherited call, one derived query and one explicit query.
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByStatus(Status s); // derived name
List<Order> findByStatuss(Status s); // ❌ TRAP: misspelled property
@Query("select o from Order o join fetch o.lines where o.id = :id")
Optional<Order> findWithLines(@Param("id") Long id); // ✅ FIX when the name stops reading well
}
Make the invisible visible: the proxy Spring builds, written out as pseudo-Java.
// bean "orderRepository" -> JpaRepositoryFactoryBean -> JDK proxy implementing OrderRepository
class OrderRepository$Proxy implements OrderRepository {
save(o) -> SimpleJpaRepository.save(o) // @Transactional (read-write)
findById(id) -> SimpleJpaRepository.findById(id) // class-level @Transactional(readOnly = true)
findByStatus(s) -> query built at STARTUP by PartTree: select o from Order o where o.status = ?1
findWithLines(id) -> the @Query JPQL, parsed once at startup
findByStatuss(s) -> no property "statuss" on Order: the application fails to start
}
The trace: one call through the proxy.
Service ──► orderRepository.findById(7) (proxy)
└─► SimpleJpaRepository.findById ✓ opens its own read-only transaction if none is active
Service ──► orderRepository.findByStatus(NEW)
└─► QueryExecutorMethodInterceptor ✓ runs the query built at startup
What you see: the startup failure.
# illustrative output
BeanCreationException: Error creating bean with name 'orderRepository' ...
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property 'statuss' found for type 'Order'
APPLICATION FAILED TO START
Why: the method name is parsed against the entity metamodel when the repository is created, so a wrong name cannot reach the first call.
| The query needs | Use |
|---|---|
| one or two simple conditions | derived name, reads like English |
| a join fetch, aggregation or subquery | @Query |
| only a few columns | interface projection or DTO |
| filters chosen at runtime | Specification or Querydsl |
| "mark all expired orders" | @Modifying(clearAutomatically = true) @Query |
Land it Derived names are for simple lookups that read like English; the moment a query needs performance thought, write it down in @Query where it can be reviewed.
- "Why does the repository work without @Transactional on my service, and when does that bite?"
Because
SimpleJpaRepositoryis annotated@Transactional(readOnly = true)at class level and@Transactionalonsave,delete, and the other mutating methods, so each repository call that finds no surrounding transaction opens and commits its own. That is fine for a singlefindById.It bites when a service method does two repository calls that must be atomic, such as
orderRepository.save(order)followed bystockRepository.decrement(sku): each commits separately, so a failure in the second leaves the first committed.two repository calls, two commitsruns offline# illustrative output (no @Transactional on the service method) conn #4 INSERT INTO orders ... COMMIT <- orderRepository.save(order), its own transaction conn #5 UPDATE stock SET qty = qty - 1 ... fails <- stockRepository.decrement(sku) throws orders: 1 row (kept) stock: unchanged <- the first commit cannot be undoneIt also bites for lazy loading: an entity returned from a repository's own transaction is detached the moment the call returns, so touching a lazy collection in the service throws
LazyInitializationExceptioneven with OSIV off.The rule is that the service method that represents the use case owns the transaction, and repository-level transactions are a fallback, not a design.
- "Where does Spring Data's query derivation fail at startup, and where does it fail at runtime?"
Derivation fails at startup when the method name cannot be parsed against the entity's metamodel: a property that does not exist, a misspelling, or an operator that does not fit the type, such as
findByNameGreaterThanon a boolean, all throw duringJpaRepositoryFactoryBeaninitialisation with a message naming the method.A
@Queryin JPQL is also validated at startup, because Hibernate parses it when the repository is created, so a wrong entity name or attribute fails the boot.A native
@Queryis not validated until first execution, since the SQL is opaque to Hibernate; that is the one that fails at runtime, often in production on a different database than the tests used.That is why native queries need a test that executes them against the real engine, and why I prefer JPQL where the query is expressible in it.
- "What about the persistence context in a long loop over a repository?"
Every entity loaded or saved through a repository inside a transaction stays managed in the
EntityManageruntil the transaction ends, and every flush dirty-checks all of them.A loop that processes 100,000 rows through
findByIdandsavein one transaction grows the persistence context to 100,000 entities, makes each flush slower than the last, and eventually exhausts the heap.The fixes are to page the work with
Pageableor a keyset condition and commit per page, to callentityManager.flush()thenclear()every 500 entities inside a chunk, or to switch to aStreamreturn type with@QueryHints(@QueryHint(name = HINT_FETCH_SIZE, value = "500"))and detach as you go.For set-based changes, a modifying
@QuerywithUPDATE ... WHEREavoids loading anything; and the mechanics of the first-level cache belong to Chapter E5.- "Would you ever use JDBC or JdbcClient instead of a repository, and how do they coexist?"
Yes, for reporting queries, bulk operations, and anything where the SQL matters more than the object model.
JdbcClient, added in Spring Framework 6.1, gives a fluent API overJdbcTemplatewith named parameters and row mapping to records, and it participates in the same transaction as JPA because both use the connection bound byTransactionSynchronizationManagerto the current thread, as long as they share theDataSourceand the transaction manager isJpaTransactionManager, which exposes the JDBC connection.The one rule is flush ordering: JPA changes are only in the database after a flush, so a
JdbcClientread inside the same transaction may not see an unflushed entity change; callentityManager.flush()first, or keep the two on separate paths.Spring Data JDBC is a third option, an aggregate-oriented mapper without a persistence context, good for simpler domains.
Q94 · Design. "Design a nightly import of 5 million rows from a CSV into PostgreSQL through a Boot service, restartable, in under 20 minutes, without disturbing daytime traffic."
Reveal answer
Strong answer Requirements: 5 million rows in 20 minutes is about 4,200 rows per second, restartable after a crash without duplicates, bounded memory, and isolation from request traffic. Design: skip JPA for this path.
- Reading and writing: a streaming reader (
BufferedReaderover the file, or the Apache Commons CSV parser in streaming mode) feeds chunks of 1,000 rows to aJdbcClientorNamedParameterJdbcTemplate.batchUpdate, one transaction per chunk, so 5,000 commits total instead of 5 million, and memory holds one chunk. - Restart: use
INSERT ... ON CONFLICT (natural_key) DO UPDATEso a re-run after a crash is idempotent, and record progress in animport_runtable with the last committed line number so a restart resumes from the chunk after the last commit. - Postgres-specific speed: the driver's
reWriteBatchedInserts=trueturns a 1,000-row batch into a single multi-row insert, roughly 5 to 10 times faster. For even more, theCopyManagerAPI streams the file withCOPY FROM STDINinto a staging table and oneINSERT ... SELECTmerges it. - Isolation: a dedicated small Hikari pool for the importer, a
SET statement_timeouton its session, and if the service is multi-instance, a ShedLock-guarded@Scheduledor a separate Kubernetes Job so exactly one importer runs.
Spring Batch is the framework for this if the job grows steps and needs restart metadata for free, and its chunk-oriented model is exactly this design. Trade-offs: bypassing JPA means no entity callbacks or second-level cache invalidation, so invalidate explicitly if those matter.
What I would not do: repository.saveAll on entities with IDENTITY ids, which disables batching and issues 5 million single inserts plus a flush of a huge persistence context.
Picture it The chunk loop as code, the SQL and commit points of one chunk, the progress table at four moments, and a table from symptom to action.
The setup: the importer loop: chunk, upsert, advance the marker, commit together.
long done = runs.lastLine(runId); // 0 on a first run
for (List<Row> chunk : reader.chunks(file, done, 1000)) { // skips the lines already imported
tx.executeWithoutResult(status -> {
jdbc.batchUpdate(UPSERT, chunk, 1000, (ps, r) -> { // insert ... on conflict (natural_key) do update
ps.setString(1, r.key());
ps.setString(2, r.name());
});
runs.advance(runId, chunk.lastLine()); // UPDATE import_run SET last_line = ? WHERE id = ?
}); // ✅ chunk and marker commit together
}
Make the invisible visible: the numbers the design has to hit.
| Quantity | Value |
|---|---|
| rows | 5,000,000 |
| budget | 20 minutes = 1,200 s, so about 4,200 rows per second |
| chunks | 5,000 chunks of 1,000, so 5,000 commits |
| multi-row inserts, reasonable Postgres | 20,000 to 50,000 rows per second: 100 to 250 s for 5 million |
What you see: the SQL of one chunk, and the progress table around a crash.
# illustrative output
setAutoCommit(false)
INSERT INTO customer (nat_key, name) VALUES (?,?),(?,?),... ON CONFLICT (nat_key) DO UPDATE ... -- 1,000 rows
UPDATE import_run SET last_line = 3000 WHERE id = 17
COMMIT <- rows and marker become visible together
# illustrative output
moment import_run.last_line customer rows
start of run 0 0
after chunk 2 committed 2000 2000
crash in the middle of chunk 3 2000 (chunk 3 rolled back with its marker) 2000
restart resumes at line 2001 ... the final count is exact
The trace: one hop per line.
Scheduler (ShedLock) ──► importer
├─► read last_line from import_run ✓
└─► per chunk: tx { batch upsert + advance marker } ✓ one commit
└─► crash here ──► whole chunk rolled back ✓ no partial chunk
| Symptom | Root cause | Action |
|---|---|---|
| 5 million single inserts, batching ignored | saveAll with IDENTITY ids | JDBC batch through JdbcClient |
| daytime requests slow during the import | importer shares the request pool | dedicated small pool, low-traffic window |
| duplicates after a re-run | plain insert, no natural key | ON CONFLICT DO UPDATE |
| upsert three times slower than plain insert | extra secondary indexes | drop them before the load, rebuild afterwards |
| two importers run at once | multi-instance @Scheduled | ShedLock or a Kubernetes Job |
Land it Bulk loading is chunked JDBC with upserts and a progress marker, on its own pool, and JPA is the wrong tool for it.
- "The requirement changes: the file now arrives as a stream over HTTP and the rows must be validated against another service. What changes?"
Two things.
The reader no longer sees the whole file, so restart must be by a durable position I control: I write the incoming stream to object storage first, unchanged, then run the import from that copy, which also gives me a replayable artifact when someone disputes a row later.
Validation against another service adds latency per row, which at 4,200 rows per second would blow the 20-minute budget, so it must be batched: collect the 1,000 keys in a chunk, make one bulk validation call with a 2-second timeout, and mark failures in a rejects table rather than stopping.
If the validation service cannot do bulk, I pre-fetch its reference data once into a local map if it fits, or run validation as a separate pass over the staging table so the load and the validation each have their own throughput.
The
ON CONFLICTupsert and the chunk commit stay as they were.- "How exactly does the restart resume from the right place without duplicating a partially committed chunk?"
The progress marker is written in the same transaction as the chunk, so they are atomic: the batch insert and
UPDATE import_run SET last_line = ? WHERE id = ?commit together or not at all.On restart, the importer reads
last_line, skips that many lines from the file, and resumes from the next chunk. There is no partially committed chunk to worry about, because a crash mid-chunk rolled the whole chunk back along with its marker.The upsert is the second safety net: if the marker were ever behind the data, for example because someone re-ran the job manually with the wrong run id, the
ON CONFLICT DO UPDATEmakes reinserting rows harmless.What the marker cannot handle is a file that changed between runs, so the
import_runrow also stores the file's hash and the job refuses to resume onto a different file.- "What would you cut if you had a day, and what is the risk?"
I would keep chunked
batchUpdate, the upsert, and the progress marker, because those give the restart guarantee and most of the speed, and I would cutCOPY, the staging table, and Spring Batch. ThereWriteBatchedInserts=trueURL flag is one line and stays.Without
COPY, the throughput of multi-row inserts on a reasonable Postgres is 20,000 to 50,000 rows per second, which meets 5 million in 20 minutes with margin, so the cut costs nothing measurable.The risk in the day-one version is isolation: without a dedicated pool the importer can hold connections against daytime traffic, so at minimum I set the importer's transactions on a separate
DataSourcewith a pool of 2, which is a few lines of configuration, and schedule it in the low-traffic window.Spring Batch comes back when a second step or a second job appears.
- "How would you verify the 20-minute target before the first real run?"
With a generated file of the same size and the same key distribution against a database of production shape, meaning the same indexes and roughly the same existing row count, because upsert cost depends on both.
I run the import in staging and watch three numbers: rows per second from the importer's own counter,
pg_stat_activitywait events to see whether the database is bound on WAL writes, index maintenance, or lock waits, and the Hikari checkout duration to see whether the importer is waiting on its pool.A common finding is that a unique index on the natural key plus two secondary indexes make the upsert three times slower than a plain insert, and the fix is to drop the secondary indexes before the load and rebuild afterwards, which for 5 million rows is minutes.
I also test the restart by killing the pod at minute 10 and confirming the resume and the final count.
Q95 · Scenario. "A batch job using saveAll on 200,000 entities takes 40 minutes. hibernate.jdbc.batch_size=50 is set. The database shows 200,000 single-row inserts. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: batching is configured but not happening. Hibernate has specific conditions under which it will batch, and one is not met.
- Evidence: the entity's id uses
@GeneratedValue(strategy = GenerationType.IDENTITY); the statistics fromhibernate.generate_statistics=trueshow batch count zero; the persistence context grows to 200,000 managed entities and the job's heap climbs. - Causes:
- One, almost certainly:
IDENTITYgeneration requires the database to return the id on each insert, so Hibernate must execute each insert immediately to get it and cannot batch. - Two: even with batching,
saveAllon a huge list keeps every entity managed, so each flush dirty-checks everything and the job slows down over time. - Three: mixed entity types in one loop defeat batching unless
hibernate.order_inserts=true. - Four: on MySQL, batching also needs
rewriteBatchedStatements=truein the JDBC URL to send a multi-row insert.
- One, almost certainly:
- Fix:
- switch ids to
SEQUENCEwith an allocation size, for example@SequenceGenerator(allocationSize = 50), so Hibernate fetches 50 ids per round trip and can batch inserts; - process in chunks of 500 with
entityManager.flush()andclear()after each, or better, one transaction per chunk; - set
order_insertsandorder_updates; - add the driver flag.
IDENTITYfor legacy reasons, use JDBC batch throughJdbcClientfor this path as in Q94. - switch ids to
- Prevention: a test that asserts the batch count from Hibernate statistics for the import path.
# batch_size alone is not enough. All three of these are required, and the
# first two are the ones usually missing.
spring.jpa.properties.hibernate.jdbc.batch_size = 50
spring.jpa.properties.hibernate.order_inserts = true # group same-table INSERTs
spring.jpa.properties.hibernate.order_updates = true
# ❌ TRAP — THE KILLER: with GenerationType.IDENTITY, Hibernate MUST execute each INSERT
# immediately to learn the generated id, so batching is silently disabled
# entirely. No error, no warning — batch_size is simply ignored.
# ✅ FIX: use a sequence with a pooled optimiser instead:
# @Id
# @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
# @SequenceGenerator(name = "order_seq", sequenceName = "order_seq",
# allocationSize = 50) # must match batch_size
# private Long id;
# Also required for PostgreSQL, or the driver sends statements one at a time
# regardless of what Hibernate batches:
spring.datasource.url = jdbc:postgresql://db/app?reWriteBatchedInserts=true
// ❌ TRAP — second cause: the persistence context accumulates all 200,000 entities.
// Dirty checking then compares a growing snapshot on every flush, so the job
// gets slower as it runs — the signature of this bug is a job that starts fast.
@Transactional
public void importAll(List<Order> orders) {
for (int i = 0; i < orders.size(); i++) {
em.persist(orders.get(i));
if (i % 50 == 0) { // must match batch_size
em.flush(); // send the batch
em.clear(); // and let the entities be collected
}
}
}
// Result: the context never holds more than about 50 entities, and each flush sends one batch
// ✅ FIX for a pure bulk load with no entity semantics needed: JdbcTemplate is
// simply the right tool and will beat any JPA configuration:
jdbc.batchUpdate("insert into orders (id, customer_id, total) values (?,?,?)",
rows, 500, (ps, row) -> { ... });
The identity-strategy point is the one that wastes days. Everything looks correctly configured, the property is present, and batching is off — because the id generator forced Hibernate to flush after every single insert.
Picture it The SQL Hibernate sends with IDENTITY and with a sequence, the statistics for each, and the heap as the persistence context grows.
The setup: an entity with IDENTITY ids and a saveAll of 200,000, with batch_size=50 set.
@Entity
class Order {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) // ❌ TRAP: batching silently off
Long id;
...
}
orderRepository.saveAll(orders); // 200,000 entities, batch_size=50 is set but ignored
Make the invisible visible: the SQL in the order it runs.
# illustrative output
insert into orders (customer_id, total) values (?, ?) -- immediately, to learn the generated id
insert into orders (customer_id, total) values (?, ?) -- next entity, another round trip
... 200,000 times statements prepared: 200,000 batches: 0
The trace: one entity.
repo.saveAll(list)
└─► em.persist(order 1)
├─► IDENTITY: must know the id now ✗ INSERT executed immediately
└─► entity placed in the context, keyed by that id
└─► em.persist(order 2) ... the same, 200,000 times, all entities stay managed
What you see: the second cause, over time.
| Minute | Managed entities | Flush cost |
|---|---|---|
| 0 | 0 | fast |
| 10 | 60,000 | each flush dirty-checks all of them |
| 25 | 150,000 | slower than the last |
| 40 | 200,000 | heap near its limit |
Why: IDENTITY forces an immediate insert per entity, and an unbounded persistence context makes every flush slower.
The fix: SEQUENCE with allocationSize = 50, chunks with flush and clear, and the driver flag, as in the code above.
What you see now: the SQL with a sequence and batching working.
# illustrative output
select nextval('order_seq') -- once per 50 ids
insert into orders (id, customer_id, total) values (?,?,?) -- 50 parameter sets, ONE JDBC batch
... about 4,000 batches statements prepared: about 4,000 batches: 4,000
runtime: about 2 minutes instead of 40
Land it IDENTITY ids and JDBC batching are mutually exclusive in Hibernate, and a growing persistence context is the second reason batch jobs crawl.
- "Why can't Hibernate batch IDENTITY inserts? MySQL returns generated keys for a batch."
Because Hibernate needs the identifier at
persisttime to place the entity in the persistence context, which is keyed by id, and to satisfy its identity guarantees.With
IDENTITYthe only way to learn the id is to execute the insert and readgetGeneratedKeys, so Hibernate executes immediately and cannot defer to a batch.JDBC drivers can return keys for a batched insert, and MySQL does, but Hibernate's insert pipeline for identity generation was designed around the immediate-execution model and, as of Aug 2026 with Hibernate 7 in Boot 4, that is still how it works.
The workaround inside Hibernate is a different generator:
SEQUENCEwith a pooled optimizer lets Hibernate assign ids in memory from a block and batch freely. On MySQL, which has no sequences, that means aTABLEgenerator, which is slow, or doing bulk paths through JDBC.- "You switched to SEQUENCE with allocationSize 50 and existing rows now collide. Explain."
The pooled optimizer treats each value from the sequence as the start of a block of 50, so if the database sequence increments by 1 while Hibernate assumes 50, two instances that fetch consecutive sequence values generate overlapping id ranges and collide on the primary key.
what a mismatched sequence doesruns offline# illustrative output sequence orders_seq: INCREMENT BY 1 Hibernate allocationSize = 50 instance A: nextval = 1000 -> uses a block of 50 ids from there instance B: nextval = 1001 -> uses a block of 50 ids from there ✗ the ranges overlap ERROR: duplicate key value violates unique constraint "orders_pkey" fix (Flyway): ALTER SEQUENCE orders_seq INCREMENT BY 50;The sequence's
INCREMENT BYmust equal theallocationSize, and its current value must be above the maximum existing id. The Flyway migration therefore doesALTER SEQUENCE orders_seq INCREMENT BY 50andSELECT setval('orders_seq', (SELECT max(id) FROM orders) + 50).Hibernate validates this mismatch at startup when
hibernate.hbm2ddl.auto=validateis on and logs a warning otherwise, and the check that matters is a test that inserts from two contexts against the migrated schema.The pooled-lo optimizer,
hibernate.id.optimizer.pooled.preferred=pooled-lo, is safer when another application also inserts into the same table.- "How would you prove the batching is happening in production, not just in a test?"
Three views. The JDBC driver's log, with
loggerLevel=TRACEon the PostgreSQL driver briefly, shows oneexecuteBatchwith 50 parameter sets rather than 50 executes, and withreWriteBatchedInserts=trueit shows a single multi-rowINSERT ... VALUES (...), (...).Hibernate's statistics, exposed as Micrometer meters when
hibernate.generate_statistics=trueand thespring.jpa.properties.hibernate.session.events.logis off, includehibernate.statements.preparedand a batch count; for 200,000 rows I expect around 4,000 prepared statements, not 200,000.And the database itself:
pg_stat_statementsshows the insert's call count, which should drop by a factor of 50. The datasource-micrometer JDBC spans in a trace show the same shape, one span per batch.If any of these still show one statement per row, the entities are going through a path that flushes per entity, usually a cascade or an
IDENTITYchild.- "What is the memory picture for the 200,000-entity saveAll, and how do you bound it?"
Each managed entity costs the entity itself plus Hibernate's snapshot copy of its state for dirty checking plus a map entry, so roughly two to three times the entity's size; 200,000 entities of a kilobyte each is about 600 megabytes, which on a 1-gigabyte heap is the reason the job slows and then dies.
The bound is the chunk: for each 500 entities, call
saveAll, thenentityManager.flush()to send the batch, thenentityManager.clear()to detach everything, so the context never holds more than 500.Better still, one transaction per chunk through a
TransactionTemplate, which also bounds the undo work on failure and releases locks.The source list itself must be streamed rather than loaded, so the reader is an iterator over the file or a
Streamquery, not aListof 200,000. With those two changes the heap stays flat for the whole run.
Q96. "Explain optimistic locking with @Version end to end, including what happens on conflict and how you retry correctly."
Reveal answer
Strong answer A @Version column, an integer or timestamp, is read with the entity and included in every update: Hibernate issues UPDATE ... SET ..., version = 6 WHERE id = ? AND version = 5.
- Conflict: if another transaction committed a change in between, the version is now 6 and the update matches zero rows.
- Detection: Hibernate detects the zero count and throws
OptimisticLockException, which Spring translates toObjectOptimisticLockingFailureException, and the transaction rolls back. - Cost: nothing was locked in the database while the user thought, so throughput under low contention is excellent.
- Across a web round-trip: the check works if the version is carried in the form or the API payload and set on the entity before saving, which is how "someone else edited this record" is detected.
Retrying correctly has three rules.
- Re-read: the retry must re-read the entity, because the persistence context that failed is gone and the stale state must not be reused.
- Outside the transaction: the retry must happen outside the failed transaction, which means the retry loop wraps the transactional method from a separate bean, since the exception is thrown by the proxy at commit time. A retry annotation on the transactional method itself would run inside the doomed transaction.
- Bounded: three attempts with jitter, because under heavy contention optimistic locking degrades into wasted work and the honest answer is a pessimistic lock or an atomic update statement.
Spring Framework 7's @Retryable(includes = OptimisticLockingFailureException.class) on the outer bean, or Resilience4j's retry, implements the loop.
@Entity
public class Product {
@Id private Long id;
@Version private long version; // Hibernate manages this; never set it yourself
private int stock;
}
// On update, Hibernate appends the version to the WHERE clause:
// UPDATE product SET stock = ?, version = 4 WHERE id = ? AND version = 3
// If another transaction committed first, 0 rows match -> OptimisticLockException
// (surfaced by Spring as ObjectOptimisticLockingFailureException).
// Result: the second writer's transaction rolls back and its entity is stale.
// ✅ FIX: THE RETRY MUST RE-READ. Retrying with the same stale entity fails forever.
@Service
public class StockService {
// The retry has to be OUTSIDE the transaction, or the retried attempt joins
// a transaction that is already marked rollback-only.
@Retryable(retryFor = ObjectOptimisticLockingFailureException.class,
maxAttempts = 3, backoff = @Backoff(delay = 50, multiplier = 2))
public void decrement(Long id, int qty) {
inner.decrementInTx(id, qty);
}
}
@Service
public class StockServiceInner {
@Transactional
public void decrementInTx(Long id, int qty) {
Product p = repo.findById(id).orElseThrow(); // fresh read, fresh version
if (p.getStock() < qty) throw new OutOfStock(id);
p.setStock(p.getStock() - qty);
} // flush -> version check
}
Read why the retry sits in a separate bean. The retry must begin a new transaction with a fresh read; retrying inside the failed transaction re-uses the stale entity and the doomed transaction, so it fails identically three times.
Picture it Two transactions on one row with the SQL in order and the version at each step, then the retry done right and done wrong.
The setup: the Product and StockService in the code above; two requests decrement the stock of product 7 at the same time.
Make the invisible visible: the SQL in the order it ran, with commit points.
# illustrative output
T1 SELECT stock, version FROM product WHERE id = 7 -> stock=10, version=3
T2 SELECT stock, version FROM product WHERE id = 7 -> stock=10, version=3
T1 UPDATE product SET stock=9, version=4 WHERE id=7 AND version=3 -> 1 row
T1 COMMIT ✓
T2 UPDATE product SET stock=8, version=4 WHERE id=7 AND version=3 -> 0 rows ✗
T2 ROLLBACK ObjectOptimisticLockingFailureException
retry (new transaction):
T2 SELECT ... -> stock=9, version=4
T2 UPDATE product SET stock=8, version=5 WHERE id=7 AND version=4 -> 1 row
T2 COMMIT ✓
| Moment | stock | version |
|---|---|---|
| before | 10 | 3 |
| after T1 commits | 9 | 4 |
| after the retry commits | 8 | 5 |
The trace: where the retry sits.
Controller ──► StockService.decrement(7, 1) @Retryable, NOT transactional
├─► attempt 1: inner.decrementInTx
│ └─► transaction, flush -> 0 rows ✗ exception leaves the transaction
└─► attempt 2: inner.decrementInTx ✓ new transaction, fresh read, version 4
(retry inside the transaction would re-run on the stale entity and the doomed transaction: fails 3 times)
What you see: the exception, and the two ways of retrying.
| Retry placement | Outcome |
|---|---|
| on a separate outer bean, wrapping the transactional method | Works: new transaction, fresh read, succeeds on attempt 2 |
| inside the same transaction with the same entity | Throws the same exception three times |
| version copied from the current row into the client object | Silently not applied: locking is switched off |
Land it Optimistic locking is a conditional update that fails loudly at commit, and the retry has to re-read from a fresh transaction one bean further out.
- "Why does the retry annotation on the transactional method itself not work?"
Because of proxy ordering and where the exception surfaces. The
OptimisticLockExceptionis thrown by Hibernate at flush time, which for aREQUIREDmethod happens inside the transaction proxy's commit, after the method body has returned.A retry interceptor on the same method sees the exception only if it wraps the transaction interceptor, and even then, if it re-invokes the method, the second attempt runs within the same proxy chain but a new transaction, which is actually fine.
The real problem is when the retry interceptor is inside the transaction interceptor, which happens by default because
@Transactional's advisor has a lower order than most: then the retry re-runs the body inside the already-doomed transaction and the persistence context still holds the stale entity, so every attempt fails identically.Setting
@EnableTransactionManagement(order = ...)and the retry's order can fix it, but moving the retry one bean outward is the version that cannot be misconfigured.- "How does the version travel through a REST update, and what if the client does not send it?"
The read response includes the version, either as a field or as an
ETagheader, and the update request sends it back, either in the body or asIf-Match.The handler loads the current entity, compares the client's version with the loaded one, and if they differ returns 412 Precondition Failed immediately; if they match, it applies the change and Hibernate's versioned update guards the window between the load and the commit.
If a client omits the version, there are two honest options: refuse with 428 Precondition Required, which is what a public API should do, or treat the request as "last writer wins" with an explicit audit note, which is sometimes the business intent for internal tools.
Never silently copy the entity's current version into the client's object to make the save succeed, which is a common bug that turns optimistic locking off while leaving the annotation in place.
- "At what contention level does optimistic locking stop being worth it, and how do you tell?"
The signal is the retry rate.
With Micrometer, I count
ObjectOptimisticLockingFailureExceptionper operation, and when retries exceed a few percent of attempts on a given entity type, each successful update is costing several wasted transactions of database work, and latency for that operation shows a second mode at the retry delay.That usually appears on a hot aggregate: a shared account, a counter, a popular product.
At that point I move that specific path to a pessimistic lock,
@Lock(PESSIMISTIC_WRITE)on the repository method, which serialises writers at the database without wasted work, or better to an atomic conditionalUPDATEas in Q97, and leave optimistic locking on everything else.Optimistic locking is the right default because most rows are edited by one person at a time, and the exceptions announce themselves through the retry counter.
- "What happens with @Version and a bulk update query, or a JDBC write, on the same table?"
They bypass the version unless you include it.
A JPQL
UPDATE Order o SET o.status = :s WHERE o.id = :iddoes not increment the version, so a subsequent entity update built on a stale read succeeds when it should have failed; JPQL supportsUPDATE VERSIONED Order o ...in Hibernate to increment it, and a native statement must doSET version = version + 1explicitly.a bulk update that bypasses the versionruns offline# illustrative output UPDATE orders SET status = 'SHIPPED' WHERE id = 1 -- version stays 5, nobody notices UPDATE orders SET note = 'x', version = 6 WHERE id = 1 AND version = 5 -- 1 row: stale write succeeds ✗ fix: UPDATE VERSIONED ... (Hibernate JPQL) or SET version = version + 1 in native SQLConversely, an entity that was updated by a bulk statement in the same persistence context is now stale in memory, so a
@Modifying(clearAutomatically = true)is needed to evict it.The rule is that the version column is a convention shared by every writer of the table, and a writer that ignores it silently disables the protection for everyone else.
In code review I look for any write to a versioned table that does not go through Hibernate's entity update.
Q97 · Design. "Design the stock-decrement path for a flash sale: 10,000 buyers, 500 units, one product row. Choose the locking strategy and defend it."
Reveal answer
Strong answer Requirements: never oversell, fair enough, fast under a burst of thousands of writes to one row, and honest failures.
Analysis of the two obvious options:
- Optimistic locking with
@Version: wrong here. With 10,000 concurrent attempts on one row, almost every transaction fails at commit and retries. The database does thousands of times the useful work. - Pessimistic
SELECT ... FOR UPDATE: serialises correctly. But it holds a lock across the read-decide-write, and it holds the connection for that duration. Throughput is bounded by lock hold time and the pool.
Design:
- One atomic statement:
UPDATE stock SET on_hand = on_hand - 1 WHERE sku = ? AND on_hand > 0, executed throughJdbcClientor a modifying@Query. - The affected-row count decides: 1 means reserved, 0 means sold out.
- Why it is enough: the database takes the row lock for microseconds. The check and the decrement are one operation. No version or explicit lock is needed.
- A short transaction also inserts the reservation row with the buyer's idempotency key, so a retry cannot reserve twice.
- Redis in front: a
DECRon a counter pre-seeded with 500 sheds the 9,500 losers in under a millisecond each, without touching Postgres. - Postgres stays the source of truth: only winners proceed to the atomic update. If Redis and Postgres disagree, Postgres wins and the reservation fails safely.
- Around it: rate limiting per user, and a queue for the checkout that follows, keep the rest of the system calm.
Trade-offs: the single-statement approach is specific to counters. A complex invariant across several rows would need FOR UPDATE in a defined lock order.
What I would not do: load the entity, check, decrement, and save, under any locking strategy, because that is three round trips per attempt for a one-statement problem.
Picture it two buyers race for the last unit, first with load-check-save and then with the single conditional UPDATE, followed by the sale as numbers over time.
The setup: one stock row with on_hand = 1 and two buyers, A and B, arriving together.
// ❌ TRAP: three steps, and the lock (if any) is held across all of them
@Transactional
public boolean reserveBroken(String sku) {
Stock s = stockRepo.findBySku(sku); // SELECT on_hand
if (s.getOnHand() <= 0) return false; // decide in Java
s.setOnHand(s.getOnHand() - 1); // write back later
return true;
}
// ✅ FIX: check and decrement are one statement; the row count is the answer
@Transactional
public boolean reserve(String sku, String buyerId, String idemKey) {
int rows = jdbc.sql("UPDATE stock SET on_hand = on_hand - 1 WHERE sku = :sku AND on_hand > 0")
.param("sku", sku).update();
if (rows == 0) return false; // Result: 0 rows means sold out
jdbc.sql("INSERT INTO reservation(idem_key, sku, buyer_id) VALUES (:k, :sku, :b)")
.param("k", idemKey).param("sku", sku).param("b", buyerId).update();
return true; // Result: 1 row means reserved
}
Make the invisible visible: what the database does with the lock when both UPDATEs arrive at once.
# illustrative output
t0 A: UPDATE stock SET on_hand = on_hand - 1 WHERE sku='SKU-1' AND on_hand > 0
takes the row lock, on_hand 1 -> 0
t0 B: same statement waits for the row lock (microseconds)
t1 A: COMMIT lock released
t1 B: wakes up, re-checks on_hand > 0 on_hand is 0, so no row matches
B gets "0 rows updated" sold out, nothing written
The trace: the broken version, step by step.
A: SELECT on_hand ........................ 1 decide: OK
B: SELECT on_hand ........................ 1 decide: OK (A has not written yet)
A: UPDATE stock SET on_hand = 0 ; COMMIT ✓ A reserved the last unit
B: UPDATE stock SET on_hand = 0 ; COMMIT ✗ B reserved it too: oversold by 1
What you see: the SQL of the fixed path in the order it runs, with the table before and after.
# illustrative output
A BEGIN
A UPDATE stock SET on_hand = on_hand - 1 WHERE sku='SKU-1' AND on_hand > 0 -- 1 row
B BEGIN
B UPDATE stock ... (same statement) -- blocked
A INSERT INTO reservation(idem_key, sku, buyer_id) VALUES ('k-A','SKU-1','A')
A COMMIT -- lock released
B (re-checked) -- 0 rows, sold out
B COMMIT -- nothing was written
stock before: SKU-1 | on_hand = 1 after: SKU-1 | on_hand = 0
reservation before: (empty) after: k-A | SKU-1 | A
Why: the statement itself is the lock and the check, so there is no gap between "read 1" and "write 0" for another buyer to slip into.
The sale as numbers over time: the three moments of the 500-unit sale with the Redis front door.
# illustrative output
moment Redis counter stock.on_hand reservation rows
before the sale 500 500 0
after 500 winners 0 0 500
buyer #501 arrives DECR -> -1: rejected in Redis, never reaches Postgres
| Symptom | Root cause | Action |
|---|---|---|
| Stock goes below zero | Read-check-write over several round trips | Single conditional UPDATE, branch on row count |
| Most buyers see retries or version failures | Optimistic lock on one hot row | Drop @Version for this path |
| Latency climbs into seconds at 100,000 buyers | Lock-wait queue on the single row | Redis shed in front, or split stock into shards by user hash |
| Redis admitted more buyers than the database had | Counter seeded wrong or refund double-counted | Postgres wins; reconcile the counter downward |
Land it Under hot-row contention, the best lock is the one the database takes for a single conditional update, with a cache in front to shed the crowd.
- "The requirement changes: buyers can now purchase up to 5 units each, and a partial fill is not acceptable. What changes?"
The statement becomes
UPDATE stock SET on_hand = on_hand - :qty WHERE sku = :sku AND on_hand >= :qty, and the affected-row count still decides: one row means the whole quantity was reserved, zero means insufficient stock for that quantity, and there is no partial state because the check and the decrement are still one atomic operation. Fairness changes, though: a request for 5 can be starved by a stream of requests for 1 when stock is low, so if the business wants first-come ordering, the Redis front door becomes a queue token rather than a plain counter, and the database update runs in token order from a single worker per SKU. The Redis pre-check doesDECRBYwith a Lua script that only decrements when the remaining count is enough, mirroring the SQL condition, and refunds withINCRBYif the database later refuses.five-unit purchase, outcomes by stock levelruns offline# illustrative output UPDATE stock SET on_hand = on_hand - 5 WHERE sku = 'SKU-1' AND on_hand >= 5 on_hand = 7 -> 1 row reserved all 5, on_hand = 2 on_hand = 3 -> 0 rows insufficient stock, no partial fill, on_hand still 3- "What if Redis says yes to 500 buyers but the database then refuses some of them?"
Then the database is right and Redis is a hint, which is why the design says Postgres wins. It can happen when Redis was seeded wrong, when a refund path double-counted, or when an operator adjusted stock directly in the database.
The reservation call returns "sold out" to those buyers, and a reconciliation job compares the Redis counter with
on_handevery few seconds during the sale and corrects the counter downward, never upward, so the drift is bounded to a few seconds of optimistic admissions.The opposite failure, Redis saying no while the database has stock, loses sales, so the counter is refunded whenever a reserved buyer abandons checkout, using the reservation row's expiry: a sweeper releases reservations older than 10 minutes, does
on_hand = on_hand + 1, andINCRs Redis.The buyer-facing promise is "you have a reservation for 10 minutes", which is honest about both.
- "What would you cut with two days, and what breaks at ten times the buyers?"
With two days I would cut Redis entirely and rely on the atomic update alone.
PostgreSQL can execute a single-row conditional update at several thousand per second per row, since each holds the row lock for microseconds; 10,000 attempts arrive over seconds, not milliseconds, so the database handles it, and the losers get a fast "sold out" from the zero-row result.
What I keep is the reservation row with the idempotency key and the rate limit per user.
At ten times, 100,000 buyers, the same single row becomes the bottleneck: lock-wait queues form on the row, each attempt waits for the ones ahead, and latency climbs into seconds while connections pile up.
That is when the Redis shed is needed, because it turns 99.5 percent of attempts into a memory operation, and the database only ever sees a few hundred winners. Alternatively, split the stock into ten shards of 50 and route by user hash.
- "Why not SELECT ... FOR UPDATE with SKIP LOCKED, or a serializable transaction?"
SELECT ... FOR UPDATEthen decrement is correct but holds the row lock across two round trips and the application's think time, so throughput is bounded by round-trip latency, roughly a few hundred per second on a 2-millisecond network, versus thousands for the single statement.SKIP LOCKEDis for picking from many rows, such as a queue; on one row it just makes every concurrent attempt skip and report nothing, which is not a sold-out answer.SERIALIZABLEisolation makes conflicting updates abort with serialization failures, which under this contention means nearly every transaction retries, the same waste as optimistic locking with more database work. The single conditional update is the minimum: one statement, one lock, no retry.what SERIALIZABLE does under contentionruns offline# illustrative output ERROR: could not serialize access due to concurrent update (SQLSTATE 40001) Spring: CannotSerializeTransactionException -> the whole transaction must be retried under 10,000 buyers on one row: nearly every attempt takes this path, then retriesWhere I do use
FOR UPDATEis a multi-row invariant, such as reserving a bundle of SKUs, locked in a fixed order to avoid deadlocks.
Q98 · Scenario. "PostgreSQL logs 'deadlock detected' several times an hour, always involving two Boot service methods: transferStock and reconcile. Diagnose and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: recurring deadlocks between two known code paths, so the lock order is deterministic and fixable.
- Evidence: the Postgres log names both processes, the statements each was waiting on, and the rows.
- Enable
log_lock_waitsfor the waits that did not become deadlocks. - On the application side, Spring surfaces the loser as
CannotAcquireLockExceptionorDeadlockLoserDataAccessException.
- Enable
- Cause: two transactions take the same locks in opposite order.
transferStockupdates warehouse A then B within one transaction.reconcileiterates warehouses in id order and updates B then A when B's id is lower, or updates a parent row then children while the other does children then parent.- Each transaction holds one lock and waits for the other's.
- Contributing factor: long transactions, because the window for the interleaving is the transaction's lifetime.
- Fix:
- Enforce a global lock order, for example always lock rows in ascending primary-key order, by sorting the ids before updating in both methods.
- Where both rows are needed up front, take them together with
SELECT ... FOR UPDATE ... ORDER BY id. - Shorten the transactions so they hold locks for milliseconds.
- Add a bounded retry with backoff for the deadlock exception at the service boundary, because the database resolves a deadlock by killing one side and a retry usually succeeds.
- Foreign-key checks also take locks on parent rows, so insert order relative to parent updates matters.
- Prevention: document lock order per aggregate, and a concurrency test that runs both methods in parallel against Testcontainers a few hundred times.
Picture it two transactions take the same two rows in opposite order, the database log that results, and the same two methods after the lock order is fixed.
The setup: warehouse rows 1 and 2; transferStock moves 5 units from 1 to 2, while reconcile works through its list in a different order.
// ❌ TRAP: each method locks rows in the order its own logic produces
@Transactional
public void transferStock(long from, long to, int qty) {
jdbc.sql("UPDATE warehouse SET qty = qty - :q WHERE id = :id").param("q", qty).param("id", from).update(); // locks row 1
jdbc.sql("UPDATE warehouse SET qty = qty + :q WHERE id = :id").param("q", qty).param("id", to).update(); // then row 2
}
@Transactional
public void reconcile() {
for (long id : List.of(2L, 1L)) // work list order: 2 first, then 1
jdbc.sql("UPDATE warehouse SET checked_at = now() WHERE id = :id").param("id", id).update();
}
// ✅ FIX: both methods take the locks together, in ascending id order
jdbc.sql("SELECT id FROM warehouse WHERE id IN (:ids) ORDER BY id FOR UPDATE")
.param("ids", List.of(from, to)).query().listOfRows();
// Result: whichever method arrives second waits for the first, never the other way round
The trace: who holds what, one hop per line.
T1 transferStock(1 -> 2) T2 reconcile()
UPDATE row 1 holds lock on row 1 ✓ UPDATE row 2 holds lock on row 2 ✓
UPDATE row 2 waits for T2 UPDATE row 1 waits for T1 ✗ cycle: deadlock
What you see: the PostgreSQL log, then the SQL in the order it ran with the commit and rollback points, and the table before and after.
# illustrative output
ERROR: deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 9912; blocked by process 4130.
Process 4130 waits for ShareLock on transaction 9911; blocked by process 4121.
Process 4121: UPDATE warehouse SET qty = qty + $1 WHERE id = $2
Process 4130: UPDATE warehouse SET checked_at = now() WHERE id = $1
T1 BEGIN; UPDATE id=1 ... T2 BEGIN; UPDATE id=2 ...
T1 UPDATE id=2 -- waits T2 UPDATE id=1 -- waits ... after deadlock_timeout:
T2 ERROR deadlock detected -> ROLLBACK (T2 is the loser)
T1 resumes, COMMIT (Spring throws DeadlockLoserDataAccessException from T2)
warehouse before: id 1 qty 50 | id 2 qty 20 after: id 1 qty 45 | id 2 qty 25 (T1 committed, T2 rolled back)
Why: with a fixed order, the second transaction waits at its first row instead of holding one row and reaching for the other, so no cycle can form.
What you see now: the same two methods racing with sorted locks.
# illustrative output
T1 BEGIN; lock rows 1,2 in order ✓ T2 BEGIN; lock rows 1,2 in order ... waits at row 1
T1 UPDATE 1, UPDATE 2; COMMIT T2 resumes: UPDATE 1, UPDATE 2; COMMIT ✓
no "deadlock detected" in the log
warehouse after both: id 1 qty 45 (checked) | id 2 qty 25 (checked)
| Symptom | Root cause | Action |
|---|---|---|
| "deadlock detected" naming the same two statements | Opposite lock order in two methods | Sort ids / ORDER BY id FOR UPDATE in both |
| Deadlocks drop but do not vanish | Foreign-key locks, unique indexes, Hibernate flush order | Read the log statements, not the Java |
| Long waits that are not deadlocks | Long transaction holding a lock | Shorten the transaction; set lock_timeout |
Land it A repeating two-party deadlock is a lock-order bug, and sorted ids plus short transactions and a retry make it disappear.
- "You sorted the ids in both methods and deadlocks still occur, less often. What else takes locks?"
Locks you did not write.
Foreign keys: inserting a child row takes a
FOR KEY SHARElock on the parent, and updating the parent's key columns waits for it, so a method that inserts order lines while another updates the order header can deadlock without either touching the same table in code.Unique indexes: two inserts with the same candidate key block each other until one commits.
Hibernate's flush order: it issues inserts, then updates, then deletes, in an order determined by the entity graph, not by your code order, so sorting ids in Java does not guarantee sorted statements unless
hibernate.order_updates=trueis set and the batching is per entity type.And cascades, which write rows you did not mention. The PostgreSQL log shows the actual statements and rows involved, so I read that rather than the Java code, and set
deadlock_timeoutlower andlog_lock_waits=onto see near misses.- "How does the retry for a deadlock differ from the retry for optimistic locking?"
They share the rule that the retry wraps the transaction from outside, but the exception and the delay differ.
A deadlock surfaces as
DeadlockLoserDataAccessException, a subtype ofPessimisticLockingFailureException, thrown by the losing statement mid-transaction rather than at commit, so the method body is interrupted and the transaction is rolled back by the proxy.The retry should back off briefly with jitter, 50 to 200 milliseconds, because the winning transaction is still running and an immediate retry likely deadlocks again against it.
The attempt limit is small, three, and the metric matters more than the retry: a deadlock retry that succeeds hides a lock-order bug that will get worse with load.
With Spring Framework 7 that is
@Retryable(includes = DeadlockLoserDataAccessException.class, maxAttempts = 3, delay = 100, jitter = 50)on the outer bean; before 7, Spring Retry or Resilience4j's retry.- "What does the concurrency test look like, and how do you keep it from being flaky?"
It runs the two methods concurrently against a Testcontainers PostgreSQL enough times to make the interleaving likely, and it asserts on outcomes rather than on timing.
A
CountDownLatchreleases 20 threads at once, half callingtransferStock(A, B)and halfreconcile(), repeated 50 rounds; the assertion is that no call ended withDeadlockLoserDataAccessExceptionand that the final stock totals are consistent.Before the fix this test fails within a few rounds; after it, it passes every time, because the fix removes the possibility rather than reducing the probability.
To keep it fast and deterministic, the data set is small, the pool is sized for 20 concurrent transactions, and the test runs in the container-backed job rather than the unit job.
I also keep a variant with a deliberate lock-order violation, marked
@Disabledwith a note, to demonstrate the test can detect the bug.- "Is there a way to make the database refuse to wait rather than deadlock?"
Yes:
SET lock_timeout = '2s'on the session or role makes any lock wait longer than 2 seconds fail with a lock-not-available error, which is caught earlier than the deadlock detector and never lets two transactions hold each other for long.PostgreSQL's deadlock detector already runs after
deadlock_timeout, default 1 second, and kills one side, so the deadlock itself lasts at most a second; whatlock_timeoutadds is a bound on the non-deadlock waits that pile up behind a long transaction.I set it as a connection-init statement on the request pool,
spring.datasource.hikari.connection-init-sql=SET lock_timeout = '2s', not on the batch pool, and I map the error to a 503 with a retry. Neither setting fixes the lock order; they limit the damage while the order is fixed.what lock_timeout producesruns offline# illustrative output ERROR: canceling statement due to lock timeout (SQLSTATE 55P03, lock_not_available) service maps it to HTTP 503 with a Retry-After header
Q99. "How do @TransactionalEventListener phases work, and what happens to a listener that itself needs a transaction after commit?"
Reveal answer
Strong answer A plain @EventListener runs synchronously, in the publisher's thread, at the moment publishEvent is called, inside whatever transaction is open.
@TransactionalEventListener registers a TransactionSynchronization instead. The event is queued, and the listener runs at the chosen phase of the surrounding transaction:
BEFORE_COMMIT: still inside the transaction.AFTER_COMMIT: the default.AFTER_ROLLBACK: only when the transaction rolled back.AFTER_COMPLETION: after either outcome.
If no transaction is active when the event is published, the listener does not run at all unless fallbackExecution = true.
The subtle part is AFTER_COMMIT.
- The listener runs on the same thread while the original transaction's resources are still bound, but the transaction is already committed.
- A
@Transactionallistener withREQUIREDjoins a transaction that can no longer commit anything. - Its writes are silently lost.
The fix has two forms:
@Transactional(propagation = REQUIRES_NEW)on the listener, which opens a fresh transaction on a new connection.@Asyncon the listener, so it runs on another thread with its own transaction.- Spring Modulith's
@ApplicationModuleListenerbundles async,REQUIRES_NEW, and after-commit together. - It adds a persistent event publication log, so a failed listener can be replayed.
The reason the phase matters for correctness: sending a confirmation email in a plain listener sends it even if the transaction rolls back a millisecond later; after-commit is the only phase where the event describes something that actually happened.
@Service
public class OrderService {
@Transactional
public void place(Order o) {
repo.save(o);
events.publishEvent(new OrderPlaced(o.id())); // published, not yet delivered
}
}
@Component
public class OrderListeners {
// AFTER_COMMIT (default) — the durable work is committed. Correct place for
// anything with an external side effect that must not happen on rollback.
@TransactionalEventListener(phase = AFTER_COMMIT)
public void notify(OrderPlaced e) { mailer.send(e.orderId()); }
// BEFORE_COMMIT — still inside the transaction; a throw here rolls everything back.
@TransactionalEventListener(phase = BEFORE_COMMIT)
public void validate(OrderPlaced e) { ... }
// AFTER_ROLLBACK / AFTER_COMPLETION — for cleanup and metrics.
@TransactionalEventListener(phase = AFTER_ROLLBACK)
public void recordFailure(OrderPlaced e) { metrics.increment("order.failed"); }
// THE TRAP: after commit, THERE IS NO TRANSACTION. A listener that writes
// to the database here silently does nothing — the write is never flushed.
// ❌ TRAP: with plain @Transactional (REQUIRED) the save below joins the dead transaction.
// ✅ FIX: REQUIRES_NEW opens a fresh transaction that really commits.
@TransactionalEventListener(phase = AFTER_COMMIT)
@Transactional(propagation = Propagation.REQUIRES_NEW) // REQUIRED
public void writeAudit(OrderPlaced e) { auditRepo.save(...); } // Result: row appears only with REQUIRES_NEW
}
The silent write is the failure worth remembering. An AFTER_COMMIT listener runs outside any transaction, so a plain @Transactional on it does nothing useful — it needs REQUIRES_NEW to open its own, and without it the audit rows simply never appear.
Picture it the order in which the transaction runs its callbacks, what each listener variant does, and what the audit table holds at the end.
The setup: the OrderService and OrderListeners code above: place() saves an order and publishes OrderPlaced.
Make the invisible visible: the callbacks the transaction fires, in order, on one thread.
place() BEGIN (connection #4)
repo.save(order) INSERT order 4021 (not committed)
publishEvent(OrderPlaced) queued as a TransactionSynchronization, NOT delivered yet
beforeCommit BEFORE_COMMIT listeners run here, still inside the tx
COMMIT (connection #4)
afterCommit AFTER_COMMIT listeners run here, same thread, tx already over
afterCompletion(COMMITTED) AFTER_COMPLETION listeners run here
rollback path: ... ROLLBACK -> afterCompletion(ROLLED_BACK) AFTER_ROLLBACK listeners run here
The trace: a plain listener versus the after-commit listener when the commit fails.
publishEvent ──► plain @EventListener mail sent now, inside the tx ✗ then COMMIT fails: email for a ghost order
publishEvent ──► AFTER_COMMIT listener queued; COMMIT fails; listener never runs ✓ no email
What you see: the log of the plain listener, and the audit table for each variant of the after-commit listener.
# illustrative output
09:14:02.101 [exec-3] OrderService : INSERT order 4021 (uncommitted)
09:14:02.103 [exec-3] OrderListeners : plain listener: mail sent for 4021 <- ✗ before the commit
09:14:02.110 [exec-3] ... : duplicate key at commit -> ROLLBACK
(AFTER_COMMIT variant: no mail line at all for this request)
audit table after the request commits
listener on AFTER_COMMIT audit rows
REQUIRED (joins the dead tx) 0 ✗ write silently lost, as the answer above explains
REQUIRES_NEW (own transaction) 1 ✓ separate connection, real COMMIT
Why: after commit there is no live transaction left to commit anything, so database work in the listener needs its own transaction or its own thread.
The fix: REQUIRES_NEW on writeAudit, already shown in the code above.
Land it After-commit listeners describe reality, but they run inside a dead transaction, so any database work in them needs REQUIRES_NEW or a new thread.
- "Why are the writes silently lost rather than failing loudly?"
Because from Spring's perspective the transaction is still there. In the
AFTER_COMMITcallback the resources are still bound to the thread, so a@Transactional(REQUIRED)listener finds an existing transaction and joins it rather than starting one; Spring logs "Participating in existing transaction".The JDBC connection has already committed, and Hibernate's session is in a post-commit state where a flush does not happen at the end of the listener because there is no second commit; the listener's entity changes sit in the persistence context, and when the synchronisation cleanup runs, the session closes and discards them.
No exception is raised because no operation failed; the operation simply never ran. As of Aug 2026 Spring still behaves this way and documents it in the
TransactionSynchronization.afterCommitJavadoc.The detection is a test asserting that the listener's row exists after the publishing transaction commits, which fails clearly.
- "When would you choose BEFORE_COMMIT, and what is its risk?"
BEFORE_COMMITis right when the listener's work must be atomic with the publisher's: writing a derived row, updating a denormalised counter, or validating an invariant across aggregates that should veto the commit by throwing.Because it runs inside the still-open transaction, its writes commit with the original and a failure rolls everything back.
The risk is the same as any work inside the transaction: it extends the connection hold time, it must not do I/O to external systems, and an exception in it turns the publisher's successful operation into a failure the publisher did not anticipate.
It also runs even if a later synchronisation would have rolled back, which is fine because the whole thing rolls back together. I use it for in-database consistency work and never for notifications, and I keep it small enough that a reviewer can see its cost.
- "How does Modulith's @ApplicationModuleListener make the listener durable, and what does it cost?"
It combines
@TransactionalEventListener,@Async, and@Transactional(REQUIRES_NEW), and it adds the event publication registry: when the publishing transaction commits, Modulith writes anevent_publicationrow per listener in the same transaction, marks it completed when the listener finishes, and on startup or on schedule republishes incomplete rows, so a crash during the listener does not lose the event.The cost is one insert and one update per listener per event on the publisher's database, the table needs a retention job or the completed rows accumulate, and the listener must be idempotent because republication can run it twice.
Configuration:
spring.modulith.events.jdbc.schema-initialization.enabled=truecreates the table,spring.modulith.republish-outstanding-events-on-restart=trueenables replay. It is an in-process outbox, and its externalisation module can also forward the same events to Kafka.- "What happens if the publisher is not in a transaction, and how do you make that impossible to miss?"
The listener does not run.
TransactionalApplicationListenerchecks for an active synchronisation at publish time, and if none exists it drops the event unlessfallbackExecution = true, in which case the listener runs immediately in the publisher's thread with no transaction semantics at all.Both outcomes are surprising, and both are silent by default.
I make it visible with a test per event type that publishes from a non-transactional context and asserts the expected behaviour, and in production with a custom
ApplicationEventMulticasteror a small aspect that logs at WARN when a transactional event is published without an active transaction.The design fix is to publish from inside the aggregate's application service, which is always transactional, and to use Modulith's verification or ArchUnit to forbid
ApplicationEventPublisherinjection into controllers, where the missing transaction usually originates.who runs whenruns offlinepublish from @TransactionalEventListener with fallbackExecution = true @Transactional method runs at AFTER_COMMIT runs at AFTER_COMMIT no transaction never runs, silently dropped runs at once in the publisher thread, no tx semantics
Q100 · Scenario. "Customers occasionally receive 'order confirmed' emails for orders that do not exist. The email is sent from an event listener. Diagnose and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a side effect for a transaction that later rolled back. The email fired before the commit was known to succeed.
- Evidence: one of three listener setups.
- The listener is a plain
@EventListener. - Or it is a
@TransactionalEventListener(phase = BEFORE_COMMIT). - Or the event is published from a method that is not transactional, so the listener falls back to immediate execution.
- The listener is a plain
- Cause: the listener ran synchronously inside the transaction, sent the email, and then the commit failed. The email service cannot be rolled back.
- Fix:
- Change the listener to
@TransactionalEventListener(phase = AFTER_COMMIT)so it only runs for committed orders. - Make it
@Asyncso a slow mail server does not extend the request. - That closes the false-positive case. It opens the opposite one: a crash between commit and the listener running loses the email.
- If that matters, which for confirmations it does, use the outbox pattern: the order transaction inserts an
outboxrow, and a relay sends and marks it, so the email is exactly as durable as the order. - Modulith's event publication registry gives the same guarantee for in-process listeners with an
@ApplicationModuleListener.
- Change the listener to
- Prevention: a test that forces a commit-time failure and asserts no email was sent, and a rule that external side effects happen only after commit and only through an outbox when they must not be lost.
Picture it an email sent from inside a transaction that then rolls back, and the same request with the outbox row that commits or vanishes together with the order.
The setup: a confirmation flow where the unique order number is violated at commit time.
@Service
class OrderService {
@Transactional
public void confirm(Order o) {
orders.save(o); // INSERT, may fail at flush/commit
events.publishEvent(new OrderConfirmed(o.number()));
} // the commit happens AFTER this method body
}
@Component
class MailListener {
@EventListener // ❌ TRAP: runs inside publishEvent(), before the commit
void on(OrderConfirmed e) { mailer.send(e.number()); }
}
// ✅ FIX: the intent to send becomes a row in the SAME transaction
@Transactional
public void confirm(Order o) {
orders.save(o);
outbox.save(new OutboxRow(o.number(), "ORDER_CONFIRMED")); // commits or vanishes with the order
}
// Result: a relay sends only rows that exist, so only committed orders get an email
The trace: where the email leaves relative to the commit.
confirm() BEGIN
orders.save(ORD-77) INSERT pending
publishEvent ──► MailListener.on() mailer.send("ORD-77") ✗ email is gone, cannot be recalled
method returns ──► COMMIT duplicate key on orders.number
ROLLBACK ✗ order ORD-77 does not exist
What you see: the customer-visible evidence side by side with the table.
# illustrative output
mail provider log: ORD-77 "order confirmed" sent 09:14:02
orders table: (no row with number ORD-77) <- the transaction rolled back
Why: the mail server is outside the transaction, so it cannot be rolled back; anything that must follow the order has to be tied to the commit.
What you see now: the SQL of the outbox version in the order it runs, with commit points.
# illustrative output
BEGIN
INSERT INTO orders(number, ...) VALUES ('ORD-77', ...)
INSERT INTO outbox(order_id, type, sent_at) VALUES ('ORD-77', 'ORDER_CONFIRMED', NULL)
COMMIT -- both rows exist, or (on failure) neither
-- later, in the relay:
UPDATE outbox SET claimed_at = now(), attempts = attempts + 1 WHERE id = ? AND claimed_at IS NULL
send mail ...
UPDATE outbox SET sent_at = now() WHERE id = ?
commit fails: orders (no ORD-77) | outbox (no row) | mail log (nothing) ✓
commit works: orders ORD-77 | outbox ORD-77, sent_at set | mail log ORD-77 ✓
Land it An email in a transaction is a lie waiting to happen; move it after commit, and to an outbox if losing it is not acceptable.
- "You changed it to AFTER_COMMIT and now some customers get no email at all. What went wrong?"
The listener now runs only for committed orders, which fixed the ghosts, and it fails or is lost in the cases the old design did not have. Three candidates.
It is
@Asyncand the mail server timed out; the exception went to theAsyncUncaughtExceptionHandler, which logs and drops it, so there is no retry.The process was restarted between the commit and the listener running, which with a rolling deploy happens every day; the event lived in memory and died with the pod.
Or the listener is also
@TransactionalwithREQUIRED, joins the dead transaction as in Q99, and its "email sent" record never persists, so a later reconciliation sends nothing because it believes the email went out.The fix for all three is the outbox: the send becomes a durable row created in the order transaction, and a relay with retries and a dead-letter state sends it.
- "How does the outbox relay avoid sending the same email twice?"
It cannot fully, because sending an email is not idempotent and the relay is at-least-once, so the design minimises the window and makes duplicates rare and detectable.
The relay claims a row with
UPDATE outbox SET claimed_at = now(), attempts = attempts + 1 WHERE id = ? AND claimed_at IS NULL, sends, then markssent_at.A crash between the send and the mark leaves a claimed-but-unsent row, which a sweeper re-queues after a timeout, and that is the one duplicate case.
outbox row lifecycleruns offline# illustrative output state claimed_at sent_at attempts after the order commits NULL NULL 0 relay claims the row 09:14:03 NULL 1 send ok, row marked 09:14:03 09:14:04 1 crash between send and mark 09:14:03 NULL 1 <- sweeper re-queues after a timeout: the one duplicateTo shrink it further, the mail provider's idempotency key, which SES, SendGrid, and Postmark all support in some form as a message id or a custom header, is set to the outbox id, so a resend of the same id is de-duplicated on their side.
And a per-order unique constraint on the
(order_id, type)pair in the outbox prevents the application from creating two rows for one confirmation in the first place.- "The email must go out within a second of confirmation. Does the outbox make that impossible?"
No; it makes the latency the poll interval, which can be short, or zero with a nudge. The relay polls every 500 milliseconds by default, so the median delay is a quarter second.
To remove even that, the publishing transaction registers an
afterCommitsynchronisation that pokes the relay in-process, or the relay uses PostgreSQLLISTEN/NOTIFYon a channel that the outbox insert trigger notifies, which wakes the relay within milliseconds; Spring Framework 7's JDBC support and the pgjdbc driver both support this with a dedicated listening connection.The outbox row is still the source of truth, so if the nudge is lost the poll catches it within its interval.
What the outbox adds is a floor of one insert on the order path and a relay that is on the critical path for latency but not for correctness, which is the trade the product owner should be shown explicitly.
- "How would you find the affected customers and prove the fix, retroactively?"
The ghost emails were sent for orders that rolled back, so their order ids exist in the mail provider's send log and not in the orders table.
I export the provider's log for the period, join it against orders by the order id in the email's subject or metadata, and the unmatched rows are the affected customers, who get an apology through a separate template.
Going forward, every send records a row in an
email_logtable with the order id, written by the relay after the provider accepts, so this join becomes a query rather than an export.The proof of the fix is a test that opens a transaction, publishes the event, forces the commit to fail with a duplicate-key violation on a second insert, and asserts that the mail sender stub was never called; before the fix that test sends, after the fix it does not.
I keep that test as the regression guard for the whole event-listener convention.
These questions test whether you know what each test annotation starts, why suites slow down, and what a test with a real database is actually proving.
Q101. "How does Spring's test context cache work, and what exactly makes two test classes share or not share a context?"
Reveal answer
Strong answer The TestContext framework builds a MergedContextConfiguration for each test class from everything that could affect the container:
- the configuration classes and locations, and the active profiles;
- the property sources from
@TestPropertySourceand thepropertiesattribute of@SpringBootTest; - the context initialisers;
- the context customisers contributed by annotations such as
@MockitoBean,@MockitoSpyBean,@DynamicPropertySourceand@ServiceConnection; - the web environment mode, and the parent configuration.
That merged configuration is the cache key. Two classes with identical keys share one ApplicationContext for the whole JVM run. The cache holds up to 32 contexts by default, least recently used evicted.
What breaks sharing:
- a different set of mocked beans, because the customiser records the mocked types;
- a single extra property, or a different
@ActiveProfiles; @DirtiesContext, which closes the context after the class or method;- less obviously, a
@MockitoBeandeclared in a base class that some tests extend and others do not.
A context that is created but never reused is the most expensive object in the suite, 5 to 20 seconds each.
The practical discipline:
- a small number of shared test configuration base classes, with mocks declared in those bases rather than per class;
- Testcontainers wired through
@ServiceConnectionin the base, so the container is started once; - an audit with
logging.level.org.springframework.test.context.cache=DEBUG, which prints hit and miss counts at the end of the run.
Picture it four test classes and the cache registry that maps each class to a context, then the same classes after the mock and profile move into one base class.
The setup: four classes that look alike but differ in one detail each.
@SpringBootTest class OrderRepoIT { } // key K1
@SpringBootTest class CustomerApiIT { } // key K1: same key, shares ctx#1
@SpringBootTest class PaymentIT { @MockitoBean PaymentClient pay; } // ❌ TRAP: one extra mock = key K2, new context
@SpringBootTest @ActiveProfiles("it") class ReportIT { } // ❌ TRAP: different profile = key K3, new context
Make the invisible visible: the cache is a map from configuration key to a live ApplicationContext.
MergedContextConfiguration (the key) ApplicationContext
[classes=App, profiles=[], properties=[], customizers=[]] ctx#1 used by OrderRepoIT, CustomerApiIT
[classes=App, profiles=[], customizers=[MockitoBean PaymentClient]] ctx#2 used by PaymentIT
[classes=App, profiles=[it], customizers=[]] ctx#3 used by ReportIT
The trace: what each class pays.
OrderRepoIT key K1 ──► miss ──► start context (about 8 s) ✗ paid
CustomerApiIT key K1 ──► hit ──► reuse ctx#1 ✓ free
PaymentIT key K2 ──► miss ──► start context ✗ paid for one mock
ReportIT key K3 ──► miss ──► start context ✗ paid for one profile
What you see: the statistics line from the cache logger and the "Started" lines.
# illustrative output
Started OrderRepoIT in 6.2 seconds (process running for 7.4)
Started PaymentIT in 5.9 seconds (process running for 14.1)
Started ReportIT in 6.0 seconds (process running for 20.3)
Spring test ApplicationContext cache statistics: [DefaultContextCache size = 3, maxSize = 32, parentContextCount = 0, hitCount = 1, missCount = 3]
Why: the key is every property of the container; a context that differs in any one is a different container and is built again.
The fix: one abstract base that declares the profile and the mock, extended by all four classes.
@SpringBootTest
@ActiveProfiles("it")
abstract class AbstractIT {
@MockitoBean PaymentClient pay; // declared once, so every subclass has the same key
}
class OrderRepoIT extends AbstractIT { } // ✅ FIX: all four extend AbstractIT
class CustomerApiIT extends AbstractIT { }
class PaymentIT extends AbstractIT { }
class ReportIT extends AbstractIT { }
What you see now: the same statistics line, comparable line for line.
# illustrative output
Started OrderRepoIT in 6.2 seconds (process running for 7.4)
Spring test ApplicationContext cache statistics: [DefaultContextCache size = 1, maxSize = 32, parentContextCount = 0, hitCount = 3, missCount = 1]
Land it The number of distinct contexts, not the number of tests, decides suite time, so treat each new mock or property in a test class as a startup you are paying for.
- "Why does a @MockitoBean change the cache key, and is there a way to mock without paying for a new context?"
@MockitoBeanis implemented as aContextCustomizerthat records the set of mocked bean types and names, and that set is part ofMergedContextConfiguration.equals, because a context with a mockedPaymentClientis a different container than one with the real bean.Two classes mocking the same types in the same way share a key; a third class adding one more mock gets a new context.
The cheap alternatives are: declare the mocks once in a shared base class or a
@TestConfigurationincluded by all tests, so every class has the same set; replace mocking of outbound clients with WireMock orMockRestServiceServerconfigured through a property, which changes behaviour without changing the bean set; or use plain Mockito on a hand-constructed service with no Spring context for logic tests.As of Aug 2026, Boot 3.4 and later use
@MockitoBeanfrom Spring Framework 6.2; the old@MockBeanwas removed in Boot 4.- "How do you read the cache statistics, and what do the numbers mean?"
With
logging.level.org.springframework.test.context.cache=DEBUG, the framework prints a line after each context lookup: "Spring test ApplicationContext cache statistics: [DefaultContextCache size = 3, maxSize = 32, parentContextCount = 0, hitCount = 148, missCount = 3]".sizeis the number of distinct contexts alive,missCountis how many times a context had to be built, andhitCountis reuse. A healthy suite has a miss count in single digits.If
missCountexceedssize, contexts were evicted and rebuilt, which points at the 32 limit or at@DirtiesContext. Ifsizeis high, the classes have too many distinct configurations.I also count "Started Application in" lines in the test output as a cross-check, because each one is a startup paid for. Reading these two numbers first saves a day of profiling individual tests.
- "What is the danger of sharing a context across many test classes?"
Shared state.
Singleton beans are shared, so a mutable cache, a stateful
@Component, a CaffeineCacheManager, or a mocked bean whose stubbing another class configured all carry state between classes; Spring resets@MockitoBeanmocks after each test method, but a spy's real state and any singleton's fields persist.The database container is shared too, so committed rows from one class are visible to the next.
Static state in a library, such as a registered Micrometer registry or a Jackson module, survives the whole JVM. The disciplines that make sharing safe are: no test relies on a count of all rows, only on rows it created with unique keys; caches are cleared in
@BeforeEachthrough theCacheManager; and any test that must mutate a singleton either restores it in@AfterEachor runs in its own context deliberately with@DirtiesContext, paying the cost once and visibly.- "How would you enforce a context budget in CI?"
By turning the cache statistics into an assertion.
The simplest mechanism is a JUnit
LauncherSessionListenerregistered viaMETA-INF/servicesthat, at session close, readsDefaultContextCachestatistics through a smallTestExecutionListenerthat captures the cache, and fails ifmissCountexceeds a number stored in the build file, say 6.A cruder but effective version is a shell step that greps the test log for "Started .*Application in" and fails the build when the count exceeds the budget.
Either one turns "the suite got slow" from a gradual drift into a failed pull request naming the class that introduced the seventh context, which is the moment the fix is cheap.
The budget is raised only in a pull request that explains why a new configuration is needed, the same way a dependency is added.
Q102 · Scenario. "The integration suite went from 3 minutes to 25 minutes over six months. No single test is slow. Walk through finding and fixing the cause."
Reveal answer
Strong answer In diagnosis order:
- Symptom: total time grew without slow tests, which points at fixed costs paid many times: context startups and container startups.
- Evidence:
- Enable the context cache statistics logging.
- Count "Started Application in" lines in the test log.
- Count Testcontainers "Container started" lines.
- Run with
-Dspring.test.context.cache.maxSizelowered to see if eviction is thrashing.
- Likely causes, ranked:
- Dozens of test classes each declaring their own
@MockitoBeancombinations, so the cache key differs per class and each pays a full startup. - Scattered
@TestPropertySourceoverrides. @DirtiesContextsprinkled to "fix" state leaks.- Per-class Testcontainers instances instead of a shared singleton.
- The cache limit of 32 being exceeded, so contexts are evicted and rebuilt.
- Dozens of test classes each declaring their own
- Fix:
- Consolidate into a handful of abstract base classes, for example
AbstractWebTest,AbstractDataTest,AbstractFullTest, each with a fixed set of mocks and properties, and forbid per-class mocks by review. - Use a single static container per suite via a
@TestConfigurationwith@ServiceConnection, and Testcontainers' reuse flag locally. - Replace
@DirtiesContextwith data cleanup (a truncate in@AfterEachor transactional rollback). - Move pure logic tests off Spring entirely.
- Expect the suite to fall to a few contexts and a few minutes.
- Consolidate into a handful of abstract base classes, for example
- Prevention: a CI check that fails if the number of distinct contexts exceeds a budget, using the cache statistics, and suite time on the team dashboard.
Picture it where 25 minutes go when every test is fast, as counts of context and container startups at three moments, and the log lines that reveal them.
The setup: a suite where each class customises the context a little.
class A { @MockitoBean EmailClient mail; } // ctx 1
class B { @MockitoBean EmailClient mail; @MockitoBean SmsClient sms; } // ctx 2: one more mock
@TestPropertySource(properties = "feature.x=true") class C { } // ctx 3: one property
@DirtiesContext class D { } // ctx 4, closed after D, rebuilt for the next
class E { @Container static PostgreSQLContainer<?> db = ...; } // its own container as well
// ❌ TRAP: each line looks harmless; each one is a full application startup
Make the invisible visible: the fixed costs as a table of startups.
# illustrative output
phase contexts started containers started suite time
6 months ago 3 1 3 min
now 85 40 25 min
after consolidation 4 1 ~4 min
now: 85 contexts x ~10 s = 14 min, 40 containers x ~12 s = 8 min, the 2,000 tests themselves = 3 min
What you see: the cache statistics and the log counts that give it away.
# illustrative output
cache statistics: [DefaultContextCache size = 32, maxSize = 32, parentContextCount = 0, hitCount = 410, missCount = 85]
missCount (85) is bigger than size (32): contexts are being evicted and rebuilt
$ grep -c "Started .*Application in" test.log -> 85
$ grep -c "Container .* started" test.log -> 40
Why: the time is spent on startups, which are invisible when you look at individual tests.
The fix: abstract bases with a fixed set of mocks and one static container.
@SpringBootTest
@Import(ContainersConfig.class) // ✅ FIX: one PostgreSQL container for the whole JVM
abstract class AbstractDataTest { }
abstract class AbstractWebTest extends AbstractDataTest {
@MockitoBean EmailClient mail; // the set of mocks is fixed here, not per class
@MockitoBean SmsClient sms;
}
// Result: 3 base classes = 3 contexts, however many test classes extend them
What you see now: the same two numbers after the change.
# illustrative output
cache statistics: [DefaultContextCache size = 4, maxSize = 32, parentContextCount = 0, hitCount = 491, missCount = 4]
$ grep -c "Started .*Application in" test.log -> 4
$ grep -c "Container .* started" test.log -> 1
| Symptom | Root cause | Action |
|---|---|---|
| missCount higher than size | More than 32 distinct contexts, evicted and rebuilt | Consolidate configurations into a few bases |
| Many "Started Application in" lines | Per-class mocks, properties or @DirtiesContext | Move them to bases; replace @DirtiesContext with cleanup |
| Many "Container started" lines | Per-class containers | One static container per type per JVM |
Land it A suite that slows without slow tests is paying for context startups, and the cure is fewer distinct configurations, not faster tests.
- "You consolidated into three base classes and the suite is still 15 minutes. What next?"
Then the fixed costs are elsewhere, and I measure again rather than assume.
First, Testcontainers: if each base class starts its own container, or if reuse is off in CI, that is 5 to 15 seconds per container per context, and Kafka in particular is slow; I check for "Container started" lines and move to one static container per container type across the whole JVM. Second, Flyway: running 300 migrations against a fresh database per context takes tens of seconds, so I snapshot a migrated database image or use a template database in PostgreSQL that tests clone.
Third, per-test cleanup: a truncate of 80 tables after every test method costs 100 milliseconds each, and across 2,000 tests that is 3 minutes; truncating only the tables the test touched, or using a transactional rollback where safe, cuts it.
Fourth, parallelism: JUnit's
junit.jupiter.execution.parallel.enabled=trueacross classes, with each container test class safe to run alongside others.- "Why not just run test classes in parallel in separate JVMs and be done with it?"
It works and it is often the fastest short-term fix, but it multiplies the cost rather than removing it.
Surefire or Gradle forks each JVM with its own context cache, so every fork pays every context startup again; four forks of a suite with 40 contexts means 160 startups, using four times the CI CPU to finish in a quarter of the wall time, which shows up as a larger CI bill and slower feedback when the runners are shared.
It also needs each fork to have its own database, since two forks writing to one container collide, which Testcontainers gives you but at another container per fork.
So I use forking after consolidation, not instead of it: a suite with 4 contexts and one container per fork parallelises well, while a suite with 40 contexts parallelises expensively. The consolidation also makes local runs fast, which forking does not.
- "How do you stop the regression from creeping back over the next six months?"
Three guards. The context budget check from Q101, which fails a pull request that adds a distinct context.
An ArchUnit or Checkstyle rule that forbids
@MockitoBean,@TestPropertySource, and@DirtiesContextoutside the designated base classes, so the mechanism that creates new contexts is only available in reviewed places.And a suite-time trend on the team dashboard, taken from the CI job duration, with a threshold that opens a ticket when it crosses, say, 6 minutes.
The first two make the drift structurally hard; the third catches whatever else slows it, such as a growing migration set or a slow new container. A quarterly look at the slowest ten test classes, which Gradle and Surefire both report, is the human part.
- "What is the honest trade-off of replacing @DirtiesContext with data cleanup?"
@DirtiesContextgives a perfectly clean world for the price of a full restart; data cleanup gives a mostly clean world for milliseconds, and "mostly" is the trade.Cleanup resets the database but not singleton beans, caches, static state, or a Kafka topic's offsets, so a test that mutated one of those can still leak into the next.
The mitigations are targeted: clear caches through the
CacheManager, reset the Kafka consumer group by using a unique group id per test class, and for the rare singleton that truly must be reset, keep one@DirtiesContexton that class with a comment.The right way to decide is per class: if a class needs a dirty context, ask what state it is escaping, and usually the answer is a design smell in the code under test, such as a static registry, that is worth fixing rather than restarting around.
Q103. "@WebMvcTest with MockMvc versus @SpringBootTest(webEnvironment = RANDOM_PORT) with a real client: what does each actually exercise, and what can only the second one catch?"
Reveal answer
Strong answer @WebMvcTest starts a sliced context: controllers, @ControllerAdvice, filters, WebMvcConfigurer beans, Jackson, validation, and, if Security is on the classpath, the security filter chain; nothing else, so services must be mocked.
MockMvc then invokes the DispatcherServlet directly in the test thread with a mock request; no socket, no Tomcat, no real serialisation over the wire. It exercises routing, argument binding, validation, JSON mapping, error translation, and security rules on URLs, in about a second.
@SpringBootTest with a random port starts the whole context plus embedded Tomcat. The test talks to it with TestRestTemplate, RestClient, or WebTestClient over real HTTP.
Only this catches:
- Tomcat connector settings such as header size and multipart limits.
- The real filter ordering, including container-level filters.
- Behaviour of the error page mapping to
/error, and anything inserver.*properties. - Compression and encoding, and graceful-shutdown behaviour.
- Real async and streaming responses.
- The actual wiring of the service and repository beans.
- With Testcontainers, the SQL against a real database.
It costs 10 to 20 seconds per context and needs the whole configuration to be valid. The rule: many slice tests for the web contract, a few full tests for the wiring and the container, and everything else without Spring at all.
Since Spring 6.2 there is also MockMvcTester with AssertJ-style assertions, and RestTestClient in Spring Framework 7 for the real-server case.
// SLICE — loads only the web layer: controllers, converters, advice, filters.
// No repositories, no services, no database. Fast, and the context is cached
// per unique slice configuration.
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orderService; // anything the controller needs
@Test void returnsProblemDetailOnMissing() throws Exception {
given(orderService.find("4021")).willThrow(new OrderNotFound("4021"));
mvc.perform(get("/orders/4021"))
.andExpect(status().isNotFound())
.andExpect(content().contentType("application/problem+json"))
.andExpect(jsonPath("$.orderId").value("4021"));
}
}
// ❌ TRAP: a green slice test says nothing about Tomcat. MockMvc does NOT open a socket. It invokes the DispatcherServlet directly,
// so it does not test the connector, real serialisation over the wire,
// or anything a servlet container does.
// ✅ FIX: FULL — a real server on a random port, a real client, the whole context.
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Testcontainers
class OrderApiIT {
@Container @ServiceConnection
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");
@Autowired TestRestTemplate rest;
@Test void createsAndReadsBack() {
var created = rest.postForEntity("/orders", req, OrderDto.class);
assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED); // Result: passes only if connector, filters and wiring accept it
}
}
The trade is fidelity against speed and context reuse. A slice test cannot catch a serialisation problem that only appears over a real socket; a full test can, and costs a context plus a container. Most controller behaviour belongs in the slice, and a handful of journeys belong in the full test.
Picture it the same upload request sent through MockMvc and through a real port, with a table of what each one actually exercises.
The setup: one shared example, a multipart upload endpoint, tested both ways; the controller and the two kinds of test are in the code above (the upload test below uses the same style).
@PostMapping("/upload")
String upload(@RequestParam MultipartFile file) { return "stored " + file.getSize(); }
// slice: mvc.perform(multipart("/upload").file("file", fiveMegabytes)) -> 200
// full: rest.postForEntity("/upload", fiveMegabyteBody, String.class) -> rejected
Make the invisible visible: what each test builds.
@WebMvcTest(OrderController.class) loads:
OrderController, @ControllerAdvice, Jackson ObjectMapper, validator, WebMvcConfigurer beans, @Component filters
not loaded: OrderService (a mock), repositories, DataSource, Tomcat, FilterRegistrationBean filters
@SpringBootTest(RANDOM_PORT) loads: every bean, plus embedded Tomcat on a random port
The trace: how far each request travels.
MockMvc ──► DispatcherServlet.service(MockHttpServletRequest) ✓ routing, binding, validation, JSON mapping
no socket, no Tomcat connector, no multipart limit ✗ not exercised
TestRestTemplate ──► socket :52144 ──► Tomcat connector ──► filters ──► DispatcherServlet ✓ everything
What you see: the same request, two verdicts.
# illustrative output
slice POST /upload (5 MB file) -> 200 stored 5242880 passes locally
full POST /upload (5 MB file) -> rejected: MaxUploadSizeExceededException (spring.servlet.multipart.max-file-size defaults to 1MB)
| Action | @WebMvcTest + MockMvc | @SpringBootTest + real port |
|---|---|---|
| GET /orders/4021 when the service throws OrderNotFound | Works: 404 problem+json | Works: 404 problem+json |
| POST a 5 MB multipart file | Works (limit never applied) | Throws MaxUploadSizeExceededException |
| Exception thrown inside a filter | Rethrown to the test, /error never reached | Reaches /error, Boot error response |
| server.compression.* or header-size settings | Silently not applied | Applied |
| SQL against PostgreSQL | Not loaded, service is mocked | Runs with Testcontainers |
Why: the slice stops at the DispatcherServlet, and the limits live in Tomcat.
The fix: add one full test per boundary, for example rest.postForEntity("/upload", fiveMegabyteBody, String.class) in a RANDOM_PORT test, and set spring.servlet.multipart.max-file-size to the size you intend to accept.
Land it The slice proves your contract, the full test proves your deployment, and the difference is Tomcat and the wiring.
- "Give a concrete bug that passed every @WebMvcTest and failed in production."
A multipart upload endpoint. The slice test posted a 5-megabyte file with
MockMvc'smultipart()builder and passed; in production, uploads over 1 megabyte failed withMaxUploadSizeExceededExceptionbecausespring.servlet.multipart.max-file-sizedefaults to 1 megabyte andMockMvcnever goes through Tomcat's multipart parsing where the limit is enforced.A second real one: a filter registered as a
@Bean FilterRegistrationBeanwith an order that put it after Security in the container, whichMockMvcin the slice did not reproduce because the slice only included@Componentfilters.A third: an error page mapping where an exception thrown inside a filter reached Boot's
/errorand returned HTML, because the@ControllerAdviceonly covers exceptions from handlers;MockMvcrethrows filter exceptions to the test instead of dispatching to/error. Each of those is caught by one@SpringBootTest(RANDOM_PORT)test.- "How many full-context tests are enough, and what should they cover?"
Enough to touch every layer boundary once, which for a typical service is 5 to 15 tests in one class sharing one context.
One test per major write path end to end, from HTTP through service, database, and outbound event; one that exercises the error path through
/error; one for authentication with a real token against a real filter chain; one for a large or multipart request; one for graceful shutdown if the service has long requests; and one that boots with the production configuration overlay and dummy secrets to prove the wiring.These are not for business logic variations, which belong in unit tests; they are for the question "does the assembled application do the thing at all".
If the count grows into the dozens, the class is being used as a regression suite for logic, and those tests should move down a layer where they run a hundred times faster.
- "What does MockMvcTester add, and does it change what is exercised?"
It changes the assertion style, not the coverage.
MockMvcTester, in Spring Framework 6.2 and later, wrapsMockMvcwith an AssertJ-based API:assertThat(mvc.get().uri("/orders/1")).hasStatusOk().bodyJson().extractingPath("$.id").isEqualTo(1), which reads better than the hamcrest matchers and, importantly, does not throw on unresolved exceptions; an exception from the handler becomes something you can assert on withhasFailed(), rather than a test error.It still invokes the
DispatcherServletdirectly with a mock request, so the same things remain unexercised.@WebMvcTestauto-configures aMockMvcTesterbean alongsideMockMvc.For the real-server side, Spring Framework 7 added
RestTestClient, a fluent client likeWebTestClientbut built onRestClientfor MVC servers, which Boot 4 configures forRANDOM_PORTtests in place ofTestRestTemplate.- "If you could only keep one of the two kinds, which, and why?"
I would keep the full test with the real server and the real database, because it is the only one that can tell me the application works, and I would accept that each test is slower and less precise.
A slice test proves the contract of a controller in isolation, which is valuable but is also what a compiler-like tool could partly do; a full test proves the assembled system, which nothing else does.
The cost is that logic variations become expensive to test, so in that world I would push the variation testing down to plain JUnit on the service layer with no Spring at all, and keep the full tests to a handful of scenarios.
In practice the answer is both, but the order of importance is unit tests first, full wiring tests second, and slice tests third, which is the reverse of how many teams allocate their effort.
Q104 · Design. "Design the test strategy for a Boot service with a REST API, PostgreSQL, a Kafka consumer, and two outbound HTTP dependencies, so that CI runs in under 8 minutes and catches wiring bugs."
Reveal answer
Strong answer Requirements: fast feedback, confidence in real integrations, and a budget. Design, by layer:
- Domain logic: plain JUnit 5 with no Spring, thousands of tests in seconds. The design pressure is that services must be constructible with
newand mocks, which constructor injection gives. - Web contract:
@WebMvcTestper controller, with@MockitoBeanservices from one shared base. It asserts status codes, ProblemDetail shapes, validation, and security rules with@WithMockUseror a test JWT. About one context. - Persistence:
@DataJpaTestwith@AutoConfigureTestDatabase(replace = NONE)and a Testcontainers PostgreSQL via@ServiceConnectionin a shared base. It runs Flyway migrations and asserts queries and constraints against the real dialect. One container, one context. - Outbound HTTP:
@RestClientTestwithMockRestServiceServerfor the client's parsing and error mapping, plus WireMock in the full tests for timeouts and faults. - Kafka:
@SpringBootTestwith a Testcontainers Kafka via@ServiceConnection. It produces a message and awaits the database effect with Awaitility, including a duplicate delivery to prove idempotency. - Full wiring: a small number of
@SpringBootTest(RANDOM_PORT)end-to-end scenarios using all containers, from HTTP request to Kafka event to database row.
Around the layers:
- Containers are singletons per JVM, with reuse enabled for developers.
- Contract tests with Pact or Spring Cloud Contract guard the two dependencies' shapes.
- CI runs unit and slice tests in one job, in parallel with the container tests in another.
Trade-offs: Testcontainers needs Docker in CI and adds about a minute of startup, which the fidelity earns. What I would not do: H2 as a Postgres stand-in, mocking the repository in service tests, or one giant @SpringBootTest class per feature.
Picture it the test layers with what each one starts, the CI time budget at three moments, and one end-to-end path from HTTP to Kafka to the database.
The setup: one shared container definition used by every layer that needs a real dependency.
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
@Bean @ServiceConnection
PostgreSQLContainer<?> postgres() { return new PostgreSQLContainer<>("postgres:16"); }
@Bean @ServiceConnection
KafkaContainer kafka() { return new KafkaContainer(DockerImageName.parse("apache/kafka:3.8.0")); }
}
// ✅ FIX: one definition, started once per JVM, imported by the DB, Kafka and full tests
Make the invisible visible: what each layer starts, and what it costs.
# illustrative output
layer annotation / tool contexts containers time
domain logic plain JUnit 5 0 0 10 s
web contract @WebMvcTest + @MockitoBean (shared base) 1 0 20 s
persistence @DataJpaTest + Postgres container 1 1 60 s
outbound HTTP @RestClientTest + MockRestServiceServer 1 0 10 s
kafka consumer @SpringBootTest + Kafka container 1 1 80 s
end-to-end @SpringBootTest(RANDOM_PORT), all containers 1 2 120 s
CI job 1 (unit + slices) ~1:30 CI job 2 (container tests) ~5:30 both run in parallel
The trace: one end-to-end scenario, one hop per line.
POST /orders ──► controller ──► service ──► INSERT orders ──► kafka.send("order-placed") ✓
consumer ──► awaits row with Awaitility (at most 10 s) ──► INSERT shipment ✓
same message delivered again ──► idempotency table rejects it, count stays 1 ✓
malformed payload ──► DLT receives it with the exception header ✓
What you see: the CI budget at three moments.
# illustrative output
moment unit+slice job container job wall clock
first design 1:30 5:30 5:30
12-minute state 4:00 11:30 11:30 <- Spring in logic tests, container per context
after the cuts 1:40 6:20 6:20
| Symptom | Root cause | Action |
|---|---|---|
| Unit-and-slice job over 2 minutes | Spring used in logic tests | Move logic tests to plain JUnit |
| Container job over budget | Migrating per context, a second Kafka, fault tests | Template database, one container per type, fault tests nightly |
| Still over 8 minutes | Too many full scenarios | Contract tests nightly; PR job runs units, slices, one full scenario |
Land it Test each edge with its slice and the real dependency behind it, keep the contexts to a handful, and let the few full tests prove the wiring.
- "CI is at 12 minutes with this design. What do you cut and what do you keep?"
I measure the two jobs first. The unit-and-slice job should be under 2 minutes; if it is not, someone put Spring into logic tests, and moving those to plain JUnit is the fix.
The container job is where the minutes usually are, and the cuts in order: run Flyway once against a template database and clone it per context rather than migrating per context; ensure one Kafka and one PostgreSQL container for the whole JVM, since a second Kafka is 20 seconds; drop the WireMock fault tests to a nightly job, keeping only the timeout case in the main pipeline; and parallelise the container job by splitting the Kafka tests from the HTTP tests into two runners.
What I keep untouched is the end-to-end wiring tests and the Testcontainers PostgreSQL, because they are the tests that catch what nothing else catches.
If still over 8 minutes, the nightly job takes the contract tests, and the pull-request job becomes "unit, slices, one full scenario".
- "The requirement changes: the service also gains a gRPC API and a scheduled job. Where do they fit?"
The scheduled job is a plain method that a test calls directly, with
spring.task.scheduling.enabledeffectively disabled in tests by excluding the scheduling configuration or by putting@EnableSchedulingon a profile-guarded class, so the scheduler never fires during the suite and timing never enters a test.Its idempotency gets a test that runs it twice against the container database.
gRPC gets the same layered treatment as REST: the service implementation is unit-tested with a stub observer, and one full test starts the gRPC server on a random port through the Boot gRPC starter, which Spring gRPC provides as of Boot 3.4 and later, and calls it with a real channel, because interceptors, deadlines, and error status mapping are only observable over the wire.
Contract tests for gRPC come from the proto file itself, so the Pact layer is not needed for it.
- "How do you make a Kafka consumer test deterministic, and what does it assert?"
It asserts on a durable effect and waits for it explicitly, never with a sleep.
The test produces a message with
KafkaTemplateto the real topic on the Testcontainers broker, then uses Awaitility,await().atMost(10, SECONDS).untilAsserted(() -> assertThat(orderRepository.findById(id)).isPresent()), and then produces the same message again and asserts the count is still one, proving the idempotency table works.consumer test skeletonruns offlinekafka.send("orders", id, payload); await().atMost(10, SECONDS).untilAsserted(() -> assertThat(orderRepository.findById(id)).isPresent()); kafka.send("orders", id, payload); // duplicate delivery await().during(2, SECONDS).untilAsserted(() -> assertThat(orderRepository.count()).isEqualTo(1));Determinism comes from three settings: a unique consumer group per test class so committed offsets from a previous class do not interfere,
auto-offset-reset=earliestso the consumer sees what the test produced, and waiting for partition assignment before producing, withContainerTestUtils.waitForAssignment, because the first poll after a rebalance is the flaky part.The poison-message path gets the same shape: a malformed payload, then an assertion that the DLT received it with the exception header.
- "What is the case against contract tests with Pact here, and when do you skip them?"
Pact costs a broker, a consumer-driven workflow both teams must follow, and maintenance whenever a field changes, and it pays off only when the provider is another team whose deploys you cannot see.
When the two outbound dependencies are third-party APIs, such as a payment provider, Pact is the wrong tool because the provider will never verify your pacts; there the guard is a recorded-response test with WireMock stubs generated from the provider's OpenAPI document, plus a nightly smoke test against their sandbox.
When the dependencies are internal services owned by the same organisation with an OpenAPI spec, a lighter alternative is schema validation: the client's tests validate their stubs against the provider's published spec in CI, which catches most breaking changes with no broker.
I skip Pact unless there are several consumer teams and the provider team agrees to run verification.
Q105 · Scenario. "All tests pass with the embedded H2 database. In production on PostgreSQL, a query fails with a syntax error and another returns different ordering. What went wrong, and how do you fix the approach, not just the queries?"
Reveal answer
Strong answer In diagnosis order:
- Symptom: behaviour differs between test and production databases. The tests were testing H2's SQL dialect and semantics, not PostgreSQL's.
- Evidence: three kinds of difference.
- A native query using a Postgres-specific construct, such as
ON CONFLICT,ILIKE, or::jsonb, that H2 in its default mode either accepts differently or rejects. - An
ORDER BYon a text column, where H2 and Postgres collate differently, or a missingORDER BYwhere H2 happened to return insertion order. ddl-auto=create-dropin tests generating a schema that does not match the Flyway-migrated production schema.
- A native query using a Postgres-specific construct, such as
- Cause: H2's compatibility modes approximate other databases but do not replicate collation, locking, isolation, JSON operators, sequences, or error codes. Any test that passes on H2 proves only that the SQL is valid H2.
- Fix the approach:
- Replace H2 with Testcontainers PostgreSQL, the same major version as production, wired by
@ServiceConnection. - Run the real Flyway migrations in tests, with
spring.jpa.hibernate.ddl-auto=validateso entity mappings are checked against the migrated schema. - Remove H2 from the dependencies so nobody can fall back to it.
- Fix the queries under the real database, and add explicit
ORDER BYwith a deterministic tiebreaker wherever ordering is observed.
- Replace H2 with Testcontainers PostgreSQL, the same major version as production, wired by
- Prevention: a rule that the test database is the production engine, and a CI job that runs the migrations against a fresh container on every change.
Picture it the same repository tests running against H2 and against PostgreSQL, with the rows each one returns and the error production raised.
The setup: a repository with a native query and an unsorted-looking name listing, tested on H2 and then on PostgreSQL.
@Query(value = "SELECT ... FROM product ... /* H2-only construct */", nativeQuery = true)
List<Product> topFive(); // ❌ TRAP: parses on H2, not on PostgreSQL
List<Product> findAllByOrderByName(); // product names: 'apple', 'Banana', 'cherry'
// ❌ TRAP: the assertion only matches H2's ordering
assertThat(repo.findAllByOrderByName()).extracting(Product::getName).containsExactly("Banana", "apple", "cherry");
Make the invisible visible: the two engines side by side.
# illustrative output
rows inserted: 'apple', 'Banana', 'cherry'
H2 (default collation): ORDER BY name -> Banana, apple, cherry (compares by code point, uppercase first)
PostgreSQL en_US.UTF-8: ORDER BY name -> apple, Banana, cherry (case-aware collation)
schema in tests: ddl-auto=create-drop builds tables from the entities
schema in prod: Flyway migrations V1 ... V12 (the two can differ for months)
The trace: a test on H2 against production.
repo test ──► H2 in-memory ──► query parses, ordering matches the assertion ✓ green
same SQL ──► PostgreSQL ──► syntax error / different order ✗ production
What you see: what production logs.
# illustrative output
ERROR: syntax error at or near "..." (SQLSTATE 42601; the quoted token depends on the query)
Spring: InvalidDataAccessResourceUsageException wrapping org.hibernate.exception.SQLGrammarException
production returns apple, Banana, cherry; the H2-based test expected Banana first
Why: the tests proved the SQL was valid H2, which is a different engine with different collation and a different schema source.
The fix: the real engine in tests, with the real migrations.
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
@Bean @ServiceConnection
PostgreSQLContainer<?> postgres() { return new PostgreSQLContainer<>("postgres:16"); } // ✅ FIX: same major version as production
}
// application-test.properties: spring.jpa.hibernate.ddl-auto=validate (entities checked against Flyway's schema)
What you see now: the failures move into the test run, where they are cheap.
# illustrative output
Flyway: Successfully applied 12 migrations to schema "public", now at version v12
ProductRepositoryTest.topFive FAILED: syntax error at or near "..." <- found in CI, not in production
ProductRepositoryTest.ordersByName FAILED: expected Banana first, got apple first <- the real collation shows up; fix the query's ORDER BY and the expectation
Land it An in-memory substitute tests a different database, and with Testcontainers there is no longer a reason to accept that.
- "Docker is not available on the CI runners. How do you get a real PostgreSQL in tests?"
Several ways, none of which is H2.
Cloud CI services offer service containers natively: GitHub Actions'
services:block and GitLab'sservices:start a PostgreSQL alongside the job, and the tests connect throughspring.datasource.urlfrom an environment variable, with@ServiceConnectionreplaced by a plain property in that profile.Testcontainers Cloud runs the containers remotely with the same API, which keeps the code unchanged. Embedded PostgreSQL libraries, such as zonky's embedded-postgres, download a real PostgreSQL binary and run it as a process without Docker; it is the real engine, just not containerised.
As a last resort, a shared PostgreSQL server with a schema per build, created by the pipeline and dropped after. The rule that survives all of these is that the test engine is the production engine at the same major version; the delivery mechanism can vary.
- "Why is ddl-auto=validate the right test setting, and what does it catch that the queries do not?"
validatemakes Hibernate compare each entity mapping against the migrated schema at startup and fail with a message like "missing column [discount_code] in table [orders]" or a type mismatch.That catches the drift that queries alone do not: an entity with a new field whose Flyway migration was forgotten, a column type changed in a migration without updating the mapping, and a
@Column(length = 50)that the database defines as 40.With
create-dropthe tests generate a schema from the entities and never see the real one, so the migration can be wrong for months.The trade-off is that
validateis strict about types in ways that occasionally produce false positives, such as PostgreSQLtextagainst avarcharmapping; those are fixed with explicitcolumnDefinitionand are worth the noise.In production I also use
validate, because a pod that starts against a schema that does not match its code should not start.- "Do you ever keep H2 for anything, and if so what?"
Only for code whose SQL is deliberately generic and whose tests need no database semantics, and even then I would rather not.
The honest case is a library or a tool that must run on several databases and uses only ANSI SQL through JPA, where H2's compatibility modes give cheap breadth.
For an application with one production database there is no case: every difference between H2 and PostgreSQL, in collation, in
ON CONFLICT, in JSON operators, in sequence behaviour, in isolation levels, in error codes, is a place where the tests lie.The habit that keeps H2 around is startup time, and Testcontainers with reuse enabled locally and a cached image in CI removes that reason.
So my answer is no, and I remove the dependency from the build so the decision cannot be quietly reversed by someone adding a "quick" test.
- "What about the ordering bug: how do you prevent that category rather than that instance?"
The category is "observable ordering without an
ORDER BY", and it needs two guards.A query rule: any query whose result is paginated, displayed, or compared must have an
ORDER BYwith a unique tiebreaker, typically the primary key, because without the tiebreaker PostgreSQL can return equal-key rows in different orders between pages when a parallel plan or an index scan changes.In review this is a checklist item; in code it is enforceable with a custom ArchUnit-style check over
@Querystrings and derived method names, flaggingPageableparameters withoutSort.A test rule: tests that assert on lists insert rows in a deliberately shuffled order, so a test can only pass if the query sorts.
PostgreSQL's collation also matters, since
ORDER BY nameunderen_US.UTF-8ignores case differently from theClocale; the test container must use the production collation, which I set throughPOSTGRES_INITDB_ARGS.
Q106. "How does @ServiceConnection work, how does it differ from @DynamicPropertySource, and how do you make container startup a one-time cost for developers?"
Reveal answer
Strong answer Before Boot 3.1, a Testcontainers test declared a static container and a @DynamicPropertySource method. The method read the container's mapped port and wrote spring.datasource.url and friends into the environment. It worked, but it coupled every test to property names.
How @ServiceConnection replaces that:
- Declare: a
@Bean @ServiceConnection PostgreSQLContainer<?> postgres()in a@TestConfiguration. - Translate: Boot's
ContainerConnectionDetailsFactoryproduces aJdbcConnectionDetailsbean from the container. - Consume: the auto-configuration for the pool uses connection details in preference to properties.
The same works for Kafka, Redis, RabbitMQ, Mongo, Elasticsearch, and the OTLP collector. It also powers spring-boot-docker-compose for local runs.
Making startup a one-time cost:
- Per JVM: because the container is a bean, its lifecycle is tied to the context, and with the context cached across classes the container starts once per JVM.
- For developers: Testcontainers' reuse feature,
withReuse(true)plustestcontainers.reuse.enable=truein~/.testcontainers.properties, keeps the container running between test runs, so the second run pays nothing for startup. - In CI: reuse is generally off, and each container costs about 5 seconds.
Boot 3.1 also added a "test main" pattern: a TestApplication class that calls SpringApplication.from(Application::main).with(ContainersConfig.class).run(args), so ./mvnw spring-boot:test-run starts the app locally against the containers with no manual database setup.
Picture it how a container becomes the connection details the pool is built from, what the console shows on a first and a second run, and what wins when a property is also set.
The setup: one container definition used by tests and by the local run.
@TestConfiguration(proxyBeanMethods = false)
class ContainersConfig {
@Bean @ServiceConnection // typed connection, no property names
PostgreSQLContainer<?> postgres() {
return new PostgreSQLContainer<>("postgres:16").withReuse(true);
}
}
public class TestApplication { // local run: ./mvnw spring-boot:test-run
public static void main(String[] args) {
SpringApplication.from(Application::main).with(ContainersConfig.class).run(args);
}
}
Make the invisible visible: which ConnectionDetails bean the pool is built from.
# illustrative output
without a container bean: JdbcConnectionDetails = built from spring.datasource.url / username / password
with @ServiceConnection: JdbcConnectionDetails = built from the running container
url = jdbc:postgresql://localhost:32771/test (random mapped port)
properties not about the connection (spring.datasource.hikari.maximum-pool-size) still apply
The trace: the order of events when the test context starts.
context starts ──► container bean created, Docker starts postgres:16 ✓
customizer sees @ServiceConnection ──► registers JdbcConnectionDetails (host:port of the container)
DataSourceAutoConfiguration ──► @ConditionalOnMissingBean(JdbcConnectionDetails): details exist, properties-based one skipped ✓
Hikari ──► connects to jdbc:postgresql://localhost:32771/test
What you see: a first run and a second run with reuse enabled.
# illustrative output
run 1: Creating container for image: postgres:16 ... Container started in 4.8s tests: 9 s
run 2: Reusing container with ID: 3f9c... (same configuration hash) no container startup
Why: the container is an ordinary bean of the context, so one cached context means one container, and reuse keeps it alive between JVM runs.
| Configuration present | Result |
|---|---|
| @ServiceConnection container bean only | Pool built from the container |
| @ServiceConnection container bean and spring.datasource.url set | Connection details win silently; the property is ignored |
| No container bean, spring.datasource.url set | Pool built from the property |
| spring.datasource.hikari.maximum-pool-size with a container bean | Still applied |
Land it @ServiceConnection turns a container into typed connection details the auto-configuration understands, so tests and local runs share one definition and one startup.
- "How does the auto-configuration decide between connection details and properties, and what happens if both exist?"
Each auto-configuration that supports it, such as
DataSourceAutoConfiguration, declares aConnectionDetailsbean conditionally:@ConditionalOnMissingBean(JdbcConnectionDetails.class)creates aPropertiesJdbcConnectionDetailsfromspring.datasource.*.If a
@ServiceConnectioncontainer bean exists, theServiceConnectionContextCustomizerregisters aJdbcConnectionDetailsbean first, so the properties-based one is skipped and the pool is built from the container's URL and credentials.Properties that are not connection details, such as
spring.datasource.hikari.maximum-pool-size, still apply, since only the URL, username, password, and driver come from the details.If you set
spring.datasource.urland also have a service connection, the connection details win silently, which surprises people expecting the property to override; the container bean must be removed or the test must not include that configuration. The same precedence holds for Kafka'sKafkaConnectionDetailsand Redis.- "Container reuse locally sounds risky. What are the caveats?"
Reuse keeps the container running after the JVM exits and finds it again by a hash of its configuration, so it only works when the container definition is identical between runs; changing the image tag or an environment variable gives a new container.
State persists across runs, so tests must own their data or truncate, which they should anyway. The container is not stopped by Testcontainers' Ryuk reaper, so it stays until you remove it by hand, and a developer with several projects can accumulate containers.
Reuse is opt-in per developer through
~/.testcontainers.properties, so CI, which does not set the flag, always starts fresh, which is the behaviour you want there. Testcontainers logs a warning whenwithReuse(true)is set but the property is missing, which is harmless.The risk that matters is a schema migration that assumes an empty database; the fix is a migration set that is idempotent or a
flyway.cleanin the test bootstrap when reuse is detected.- "How does the same container definition serve both the tests and the local run?"
By putting the container beans in one
@TestConfiguration(proxyBeanMethods = false)class in the test source set, sayContainersConfig, and using it from both entry points. Tests import it with@Import(ContainersConfig.class)on the base class.The local run uses a second main class in the test source set,
TestApplication, whosemaincallsSpringApplication.from(Application::main).with(ContainersConfig.class).run(args); Boot's Maven and Gradle plugins exposespring-boot:test-runandbootTestRunto launch it with the test classpath.Because both paths use the same beans and the same
@ServiceConnectionwiring, the database the developer runs against is the same image and version as the tests, and there is noapplication-local.ymlpointing at a hand-installed database that drifts.With reuse on, the local run starts in the time of the application, not the container.
- "When would you still use @DynamicPropertySource?"
When the thing the container provides is not a supported connection-details type, or when the property is not a connection at all.
A WireMock container's base URL needs to land in
payment.base-url, which is my own property, so@DynamicPropertySource static void props(DynamicPropertyRegistry r) { r.add("payment.base-url", wiremock::getBaseUrl); }is the right tool.A container for a database Boot has no connection-details factory for, or a custom property like a bucket name for a LocalStack container, is the same.
Boot 3.4 and later also let you declare a
DynamicPropertyRegistrarbean for this, which works in a@TestConfigurationand keeps the container-as-bean lifecycle. So the split is:@ServiceConnectionfor anything Boot auto-configures, and dynamic properties for everything that is mine.
Q107. "What does @Transactional on a test method do, and name three situations where it gives you a false pass."
Reveal answer
Strong answer On a test, Spring's TransactionalTestExecutionListener opens a transaction before the method and rolls it back afterwards by default, so each test's writes disappear and tests do not need cleanup. @DataJpaTest applies it automatically.
The false passes come from the fact that the whole test now runs inside one transaction with one persistence context.
- The flush problem: JPA writes are only sent to the database at flush, and a rolled-back test may never flush. A constraint violation or a wrong column mapping that would fail at commit in production never surfaces. The guard is
TestEntityManager.flush()orsaveAndFlushbefore assertions. - The first-level cache problem: a
findByIdafter asavein the same transaction returns the same managed instance from memory without touching the database, so a broken mapping passes. The guard isflush()thenclear()before reading back. - The other-thread problem: anything that runs on another thread or another transaction sees nothing. An
@Asynclistener, aREQUIRES_NEWaudit write, a Kafka consumer, or a secondDataSourceall look at committed data, and the test's data is uncommitted. Assertions on their effects fail, or worse, the test asserts the absence of an effect and passes.
Also, code under test that relies on after-commit events never fires them, because there is no commit. For those cases, drop the test transaction, commit real data, and clean up with a truncate or Testcontainers' fresh database per class.
@SpringBootTest
@Transactional // Spring starts a transaction per test and ROLLS BACK after
class OrderServiceTest {
@Test void savesOrder() {
service.place(request);
assertThat(repo.count()).isEqualTo(1); // passes
}
}
// Convenient: no cleanup between tests. But it changes the semantics under test.
// FALSE PASS 1 — the flush never happened.
// ❌ TRAP: the unflushed version of this test is green, whatever the database would say.
// The assertion reads from the persistence context (first-level cache), not the
// database. A constraint violation or a column-length overflow that would occur
// at flush time is never triggered.
@Test void savesOrder() {
service.place(request);
em.flush(); // ✅ FIX: force the SQL to actually run
em.clear(); // and force the next read to hit the database
assertThat(repo.count()).isEqualTo(1); // Result: a violation now surfaces here, as in production
}
// FALSE PASS 2 — propagation is hidden.
// The test's transaction is already active, so a service method marked
// REQUIRES_NEW behaves differently than in production, and a method that
// relies on starting its own transaction appears to work.
// FALSE PASS 3 — after-commit work never runs.
// @TransactionalEventListener(AFTER_COMMIT) listeners, outbox publishers and
// commit callbacks are all skipped, because the test rolls back instead of
// committing. The code path is never exercised.
// -> for those, use @Commit or a non-transactional test with explicit cleanup. // ✅ FIX
The third one is the most dangerous, because it means the entire post-commit half of a feature — emails, events, outbox rows — has passing tests that never execute it.
Picture it a duplicate-email insert that the test transaction never sends to the database, shown as the SQL that ran in the test and in production, with the table at each end.
The setup: a service that registers a user, with a unique constraint on email and a sequence-generated id.
@SpringBootTest @Transactional // test transaction, rolled back at the end
class SignupTest {
@Test void duplicateEmailIsRejected() {
service.register("a@x.io");
service.register("a@x.io"); // ❌ TRAP: expects a violation, but nothing is flushed
} // Result: green
@Test void duplicateEmailIsRejectedHonestly() {
users.saveAndFlush(new User("a@x.io"));
assertThatThrownBy(() -> users.saveAndFlush(new User("a@x.io"))) // ✅ FIX: flush sends the INSERT now
.isInstanceOf(DataIntegrityViolationException.class); // Result: fails/passes like production
}
}
Make the invisible visible: the persistence context holds the pending inserts in memory.
# illustrative output
persistence context (memory): User(id=1, a@x.io) [INSERT pending], User(id=2, a@x.io) [INSERT pending]
database: (nothing sent yet)
The trace: the test against production.
test: register ──► save (pending) register ──► save (pending) ──► ROLLBACK ✗ pending inserts discarded, never sent
prod: register ──► save ──► COMMIT (flush sends INSERT) ✓ register ──► INSERT ──► ERROR ──► ROLLBACK ✓ violation raised
What you see: the SQL in the order it runs, with commit and rollback points, and the table contents.
# illustrative output
-- in the test (no flush)
BEGIN
select nextval('user_seq') -- id assigned, nothing inserted
select nextval('user_seq')
ROLLBACK -- the pending inserts vanish; test result: green (false pass)
-- in production
BEGIN; select nextval('user_seq'); INSERT INTO users(id, email) VALUES (1, 'a@x.io'); COMMIT;
BEGIN; select nextval('user_seq'); INSERT INTO users(id, email) VALUES (2, 'a@x.io');
ERROR: duplicate key value violates unique constraint "users_email_key"
ROLLBACK -- Spring throws DataIntegrityViolationException
users before: (empty) after the test: (empty) after production: 1 | a@x.io
Why: the test transaction never commits, so the persistence context never has a reason to send its pending statements.
| Situation | In production | In a @Transactional test |
|---|---|---|
| Unique violation on a pending insert | Throws DataIntegrityViolationException at commit | Silently not sent |
| findById right after save | Reads from the database after commit | Returns the managed instance from memory |
| @Async or REQUIRES_NEW work that reads the data | Sees the committed data | Sees nothing, the data is uncommitted |
| @TransactionalEventListener(AFTER_COMMIT) | Runs after the commit | Never runs, there is no commit |
Land it A rolled-back test transaction hides flush errors, cache effects, and every other-thread or after-commit behaviour, so use it for repository tests and drop it for anything asynchronous.
- "How do you test after-commit behaviour without dropping @Transactional on every test?"
By committing on purpose inside the test.
TestTransaction.flagForCommit()followed byTestTransaction.end()commits the test-managed transaction, which firesAFTER_COMMITlisteners, andTestTransaction.start()opens a new one for further assertions. The data is now really committed, so the test must clean it up, which is the price.The alternative that I prefer for event tests is to not use the test transaction at all and instead call the service method, which has its own
@Transactional, from a non-transactional test class with cleanup in@AfterEach.For the listener itself, a unit test calls the listener method directly and a separate test verifies the wiring by publishing through a transactional method and awaiting the effect.
Spring Modulith adds
@ApplicationModuleTestwithScenario, which publishes an event and awaits the outcome with proper commit semantics, purpose-built for this.- "Why is flush-then-clear enough to defeat the first-level cache, and what does it not catch?"
flush()sends the pending SQL, so constraint violations and mapping errors surface as exceptions in the test;clear()detaches every entity, so the nextfindByIdmust issue a realSELECTand rebuild the object from the row, which proves the read mapping.Together they turn a memory round trip into a database round trip.
What they do not catch: isolation-dependent behaviour, because the test still reads its own uncommitted writes; anything triggered by commit, such as deferred constraints, which PostgreSQL checks at commit when declared
DEFERRABLE INITIALLY DEFERRED; and concurrency, since there is one transaction.They also do not catch a missing transaction boundary in the service, because the test provides one, which is the false pass that hides a service method that would run in autocommit mode in production.
For that, the service under test needs a test without the test-managed transaction.
- "Is @DataJpaTest's rollback behaviour the right default, or would you change it?"
For repository tests it is the right default, because those tests are about queries and mappings, the rollback keeps the database clean at no cost, and the flush-and-clear guard covers the cache problem.
I keep it and add
@AutoConfigureTestDatabase(replace = NONE)so it runs on the container instead of trying to substitute an embedded database.I change it, with
@Transactional(propagation = NOT_SUPPORTED)on the class or@Rollback(false)on specific methods, when the test involves anything that must observe committed data: a native query using a separate connection, aREQUIRES_NEWpath, or an assertion on a sequence value.The trap to know:
@Rollback(false)commits the data and leaves it, so those tests need cleanup, and mixing the two styles in one class is a common source of the order-dependent failures in Q108.- "A test with the test transaction passed, and the same code fails in production with a constraint violation. Which of the three cases was it?"
The flush case, and it is the most common of the three.
The service inserted an entity that violates a unique constraint, but in the test the persistence context never flushed, because no query followed the insert and the test transaction rolled back instead of committing; Hibernate discarded the pending insert without ever sending it.
In production, the method's own transaction committed, the flush ran, and PostgreSQL raised the violation, which Spring translated to
DataIntegrityViolationException. The confirmation is to addentityManager.flush()at the end of the test or usesaveAndFlushand watch the test fail.The systematic fix is to set the test's
TestEntityManagerusage to flush after every write helper, or to configurespring.jpa.properties.hibernate.flushModetoALWAYSin the test profile, which makes the test slower but honest.
Q108 · Scenario. "A test passes alone and fails in the suite with 'expected 3 orders but found 7'. Diagnose the flakiness and fix it properly."
Reveal answer
Strong answer In diagnosis order:
- Symptom: order-dependent state; another test's data is visible. Since the context and the database container are shared across classes, anything committed by one test persists for the next.
- Evidence: run the suite with a fixed method order and a single failing pair to find the writer; check which tests are not
@Transactionalor useREQUIRES_NEWor async paths that commit for real; check for a static in-memory cache or a Caffeine@Cacheablethat survives across tests in the shared context. - Likely causes, ranked:
- A
@SpringBootTestclass writes committed data through the real service and never cleans up. - An asynchronous listener from an earlier test commits after that test ended.
- A cached bean, such as a cache manager or a stateful singleton, holds data across tests.
- A test assumes a count instead of asserting on its own rows.
- A
- Fix:
- Make assertions specific to data the test created, using a unique key per test, so counts of the whole table are never asserted.
- Add a cleanup strategy for committed tests, either a
@Sqltruncate script withexecutionPhase = AFTER_TEST_METHODor a JUnit extension that truncates all tables. - Wait for async effects with Awaitility inside the test that triggered them, so they cannot bleed into the next.
- Clear caches in
@BeforeEachvia theCacheManager. - Do not reach for
@DirtiesContext, which "fixes" it by paying a full restart.
- Prevention: run the suite in random order in CI, which turns hidden order dependence into consistent failures early.
Picture it two test classes sharing one database, the orders table after each, and the same tests after the fix.
The setup: a class that commits real rows and never cleans up, followed by a class that counts all rows.
@SpringBootTest class OrderImportIT {
@Test void imports() { importer.importAll(); } // ❌ TRAP: commits 4 orders, never cleans up
}
@SpringBootTest class ReportIT {
@Test void countsOrders() {
createThreeOrders();
assertThat(orders.count()).isEqualTo(3); // ❌ TRAP: counts the whole table
}
}
Make the invisible visible: the table after each test, in the order the suite ran them.
# illustrative output
test action orders rows
(start of suite) 0
OrderImportIT.imports importAll() commits 4 rows 4 (never cleaned)
ReportIT.countsOrders creates 3, asserts count == 3 7 ✗ expected 3, found 7
ReportIT.countsOrders run alone 3 ✓
What you see: the failure message.
# illustrative output
org.opentest4j.AssertionFailedError:
expected: 3
but was: 7
Why: the database container is shared across classes, so committed rows outlive the test that wrote them.
The fix: tests own their rows by unique key, and committed tests clean up.
@SpringBootTest
@Sql(statements = "TRUNCATE orders RESTART IDENTITY CASCADE", executionPhase = AFTER_TEST_METHOD) // ✅ FIX: committed tests clean up
class OrderImportIT { @Test void imports() { importer.importAll(); } }
@SpringBootTest class ReportIT {
@Test void countsOrders() {
String customer = "c-" + UUID.randomUUID();
createThreeOrders(customer);
assertThat(orders.countByCustomerId(customer)).isEqualTo(3); // Result: independent of every other test
}
}
What you see now: the same suite in any order.
# illustrative output
test action orders rows
OrderImportIT.imports importAll() commits 4 rows 4
(@Sql truncate after the method) 0
ReportIT.countsOrders creates 3 for its own customer 3 ✓ count for its customer is 3, in any order
| Symptom | Root cause | Action |
|---|---|---|
| Passes alone, fails in the suite | Another test committed rows | Unique keys per test; cleanup after committed tests |
| Count is higher after an async test | Listener committed late | Await the effect inside the test that triggered it |
| Stale values across classes | Cache or stateful singleton in the shared context | Clear caches in @BeforeEach |
Land it Shared contexts mean shared state, so tests must own their data by unique keys and clean up what they commit, and random ordering keeps everyone honest.
- "How do you find the writer quickly when the suite has 800 tests?"
Bisect by class, not by reading.
Run the failing test after each other class in turn using the JUnit Platform's class selector, or faster, run the suite with a deterministic order and a database snapshot: add a JUnit extension that, after each test, counts rows in the affected table and logs the test name when the count changed, then read the log for the last test before the failure that changed the count.
Fifteen minutes of one run beats an afternoon of guesswork. For asynchronous writers, the count changes after the test ended, so the same extension in
@BeforeEachof the next test logs "count was 3, now 7" with the previous test's name.row-count extension outputruns offline# illustrative output [rowcount] OrderImportIT.imports orders 0 -> 4 <- the writer [rowcount] CustomerIT.finds orders 4 -> 4 [rowcount] ReportIT.countsOrders orders 4 -> 7 <- victim: expected 3, found 7Once found, the writer is usually a
@SpringBootTestthat calls a real service without cleanup, or a test that starts an@Asyncpath and returns before it finished.- "You added truncation after every test and now the suite is three minutes slower. What is the better cleanup?"
Truncate only what changed, and truncate cheaply. A single
TRUNCATE t1, t2, ..., t80 RESTART IDENTITY CASCADEstatement is much faster than 80 separate statements, since it takes the locks once, and PostgreSQL's truncate is metadata-only.Better, track which tables a test touched: a JUnit extension reads
pg_stat_user_tables.n_tup_insbefore and after, or the application's own repository usage, and truncates only those.Better still for many tests, keep the test-managed transaction and rollback for everything that does not need a commit, and reserve real cleanup for the few classes that do.
And keep the schema small in tests: reference tables loaded by migrations are excluded from the truncate list. With those, per-test cleanup is under 10 milliseconds and the three minutes disappear. What I would not do is
@DirtiesContext, which trades three minutes for thirty.- "Is random test ordering in CI worth the pain of the failures it produces?"
Yes, because the failures it produces are real bugs in the tests that would otherwise appear as intermittent CI flakes nobody can reproduce, and intermittent flakes are the thing that makes a team stop trusting the suite.
Random ordering with a printed seed,
junit.jupiter.testclass.order.default=org.junit.jupiter.api.ClassOrderer$Randomand the seed logged, makes every order dependence reproducible: rerun with the seed and it fails again.The first week after enabling it is painful, because every hidden dependence surfaces at once; after that, new ones are caught in the pull request that introduces them.
The gentler rollout is to enable random order in a nightly job first, fix what it finds over a sprint, and then move it to the pull-request job. What I would not do is retry failed tests automatically, which hides exactly the bugs this exposes.
- "The count is 7 because a listener from a previous test committed late. How do you make the earlier test wait?"
The test that triggers asynchronous work owns waiting for it. With Awaitility, the earlier test ends with
await().atMost(5, SECONDS).until(() -> auditRepository.countByOrderId(id) == 1), so the side effect completes before the next test begins.When the effect has no observable row, the test can inject a synchronous executor: a
@TestConfigurationthat replacesapplicationTaskExecutorwith aSyncTaskExecutor, which makes@Asyncrun inline in the test thread, deterministic and fast; the base class for those tests declares it so the context is still shared.For Kafka consumers, the test awaits the consumer's effect the same way, or the consumer container is paused in tests that do not need it.
The principle is that a test's end means its work is done; anything less is a race the next test will lose eventually.
The last group of this section tests whether you know where every value came from, how to change it safely, and what the caching abstraction does and does not promise.
Q109 · Design. "Design configuration management for a Boot service across dev, staging, and production on Kubernetes, including secrets, so that a wrong value cannot reach production silently."
Reveal answer
Strong answer Requirements: one artifact for all environments, environment values outside the jar, secrets never in git or logs, validation at startup, and an audit trail.
Design:
- In the jar:
application.ymlwith safe defaults and every property the service understands, documented through@ConfigurationPropertiesrecords with validation constraints. A missing or malformed value stops startup with a message naming the property and its origin. - Non-secret values: a Kubernetes ConfigMap per environment, mounted as environment variables with the relaxed-binding names. It is managed in git with the Helm chart or Kustomize overlays, so a diff between staging and production is a code review.
- Secrets: they live in the cloud secret manager or Vault and are delivered to the pod by the External Secrets Operator into a Kubernetes Secret. The Secret is mounted as files under
/run/secretsand read withspring.config.import=optional:configtree:/run/secrets/, which maps each file to a property. That keeps secrets out of environment variables, which leak into/procand crash dumps. - Profiles: limited to
localfor laptops. Production and staging use the same profile-less configuration with different values, so there is no "prod profile" that only runs in production.
Guards:
- A startup smoke stage in the pipeline that runs the jar with the production ConfigMap and dummy secrets and asserts
ApplicationReadyEvent. - An Actuator
configpropssnapshot in staging diffed against production values with secrets masked. - A rule that any property change in the production overlay needs the same review as code.
Trade-offs: file-mounted secrets need a restart to rotate unless the client refreshes, which Q113 covers.
What I would not do: Spring Cloud Config Server as a first choice, since it adds a runtime dependency for values Kubernetes already delivers; or profile-specific files baked into the jar per environment.
Picture it where each kind of value lives, the three gates a wrong value must pass, and what a bad value looks like when a gate stops it.
The setup: the same jar in every environment; only the manifests differ.
# values-production.yaml -> ConfigMap (non-secret), reviewed like code
env:
PAYMENT_GATEWAY_URL: https://pay.example.com
PAYMENT_TIMEOUT: 5s
# Secret from the External Secrets Operator, mounted as files at /run/secrets
# application.yml inside the jar:
spring:
config:
import: optional:configtree:/run/secrets/
Make the invisible visible: which source supplies each property.
# illustrative output
application.yml (in the jar) defaults: payment.timeout=3s, every key documented
ConfigMap -> environment variables PAYMENT_GATEWAY_URL, PAYMENT_TIMEOUT (wins over the jar)
/run/secrets/db.password -> property db.password (file name = key)
/run/secrets/payment.api-key -> property payment.api-key
The trace: the path a change takes, with each gate marked.
PR changes values-production.yaml ──► review plus "dangerous key" label check ✓ unreviewed change stopped
CI: start the jar with the rendered production ConfigMap and dummy secrets ✓ unreachable or malformed value stops the pipeline
deploy ──► new pod binds @Validated properties ✗ bad value: startup fails, pod never becomes ready
old pods keep serving traffic while the rollout waits ✓ customers never see the bad value
What you see: what a bad value looks like at each gate.
# illustrative output
APPLICATION FAILED TO START
Description:
Binding to target ... failed:
Property: payment.timeout
Value: "banana"
Origin: System Environment Property "PAYMENT_TIMEOUT"
Reason: failed to convert java.lang.String to java.time.Duration
$ kubectl rollout status deployment/orders
Waiting for deployment "orders" rollout to finish: 1 out of 3 new replicas have been updated...
| Symptom | Root cause | Action |
|---|---|---|
| Malformed value (empty, out of range, bad URL) | No validation at bind time | @ConfigurationProperties records with @NotBlank, @Min, @Pattern |
| Valid-looking value pointing at the wrong place | Validation checks shape, not meaning | Smoke start with health checks against real endpoints |
| Value changed without review | Production overlay edited outside the pipeline | Same review as code; dangerous keys need an approval label |
Land it Defaults in the jar, environment values in reviewed manifests, secrets as mounted files, and validation at startup so a bad value fails the deploy instead of the customer.
- "The requirement changes: a value must change at runtime without a deploy, for example a feature flag. Where does that fit?"
Not in this configuration system, which is deliberately restart-shaped.
Runtime-changeable values are a different category and get a different mechanism: a feature-flag service such as Unleash or OpenFeature with a provider, or a small table in the service's own database read through a cached client with a 30-second TTL. The flag client is a bean the code asks at decision time,
flags.isEnabled("new-checkout", context), and its state is observable through a metric and an audit log of changes with who and when.What I avoid is making
@ConfigurationPropertiesbeans mutable through@RefreshScopefor this purpose, because it blurs the line between "the deployment's configuration" and "a knob someone turns at 2 a.m.", and the second needs its own audit and rollback story.Kubernetes ConfigMap updates mounted as files do change on disk, but Boot does not re-read them, so they do not help here.
- "Why configtree instead of environment variables for secrets? Environment variables are simpler."
Simpler, but leakier.
Environment variables are visible to every process in the container through
/proc/<pid>/environ, inherited by every child process such as a shell someone opens for debugging, printed by crash reporters and some diagnostic tools, and included in/actuator/envoutput unless masked, which Boot does for names matching password or secret patterns but not for arbitrary names.Files under a
tmpfsmount with mode 0400 are readable only by the application's user, are not inherited, and can be rotated by the platform by rewriting the file.spring.config.import=optional:configtree:/run/secrets/maps each file name to a property, so/run/secrets/db.passwordbecomesdb.password, and it composes with relaxed binding. The remaining leak is the application's own logging, which the masking converter and the rule against logging configuration handle.The
optional:prefix lets the same jar run locally without the mount.- "How does the startup smoke stage know the value is wrong, if the value is a valid-looking string?"
Validation catches shape, not meaning, so the smoke stage adds behaviour. Shape:
@ConfigurationPropertiesrecords with@NotBlank,@Min,@Pattern, and@DurationMinreject empty values, out-of-range numbers, and malformed URLs at bind time.Meaning: the smoke stage starts the jar with the production overlay and, instead of just asserting readiness, runs a set of connectivity checks through Actuator's health groups with the real endpoints reachable from the pipeline, so a wrong database host or a URL pointing at staging from production fails
dbor a custompaymentGatewayindicator.For values that cannot be checked live, such as a rate limit, the guard is a diff: the pipeline renders both overlays and fails on changes to keys tagged as "dangerous" in a manifest unless the pull request carries an approval label.
That combination catches malformed, unreachable, and unreviewed, which are the three ways a wrong value usually arrives.
- "What would you cut with a week, and what would you never cut?"
With a week I would cut the External Secrets Operator and the configprops diff, and keep everything else.
Secrets can start as Kubernetes Secrets created by the pipeline from the cloud secret manager, mounted as files exactly as designed, so the application side does not change when the operator arrives later. The diff is nice-to-have once the review rule exists.
I would never cut the validated
@ConfigurationProperties, because they are the cheapest guard and they are code; nor the "no production profile" rule, because a profile that only activates in production is untested by definition; nor the smoke start in the pipeline, which is a single job that runs the jar with the overlay and waits for readiness, an hour of work that catches the majority of bad-value incidents.The order of value is validation, then smoke start, then secrets-as-files, then everything else.
Q110. "@ConfigurationProperties versus @Value: what does each do at binding time, and what does the configuration processor add?"
Reveal answer
Strong answer @Value("${payment.timeout}") is resolved by the placeholder mechanism when the bean is created:
- the string is looked up in the
Environment; - it is converted to the field type by the conversion service, and injected;
- a missing key with no default fails at that bean's creation;
- each usage is a separate string literal nobody can search for reliably;
- it supports SpEL, which is both its power and its risk.
@ConfigurationProperties(prefix = "payment") uses the Binder, a different mechanism that binds a whole subtree onto an object:
- nested objects, lists, maps, durations and data sizes with units, relaxed names, and constructor binding for records;
- binding failures produce a structured report with the property, the value, the origin, and the reason;
- with
@Validated, Jakarta constraints run after binding and produce the same report, so a wrong value fails the boot before any request; - the bound object is a bean you can inject, test with
new, and inspect through/actuator/configprops.
The spring-boot-configuration-processor annotation processor generates META-INF/spring-configuration-metadata.json from the class, with types, defaults from the record's defaults or field initialisers, and Javadoc as descriptions.
- IDEs use it to autocomplete and validate
application.yml. - It lets you mark a property deprecated with a replacement, so a rename is guided rather than silent.
The rule: @ConfigurationProperties for anything with more than one key or that anyone else will read; @Value at most for a single literal in a one-off place.
// @Value — a single literal placeholder, resolved by string. No relaxed
// binding, no validation, no metadata, and it fails at INJECTION time.
@Service
public class PaymentClient {
@Value("${payment.gateway-url}") private String url; // ❌ TRAP: untyped, a missing key fails only when this bean is created
@Value("${payment.timeout-ms:5000}") private int timeoutMs; // default after :
}
// @ConfigurationProperties — a typed, validated, relaxed-bound object,
// validated at STARTUP so a bad value fails the deploy rather than the request.
@ConfigurationProperties(prefix = "payment")
@Validated
public record PaymentProperties(
@NotBlank String gatewayUrl, // ✅ FIX: binds payment.gateway-url,
// PAYMENT_GATEWAY_URL, payment.gatewayUrl...
@Positive Duration timeout, // "5s" / "500ms" parsed for you
@NotNull @Valid Retry retry) {
public record Retry(@Min(0) @Max(10) int maxAttempts, Duration backoff) {}
}
@EnableConfigurationProperties(PaymentProperties.class)
@Configuration
class PaymentConfig { }
// Result: a blank gateway URL stops startup with a binding report.
// Add spring-boot-configuration-processor and the IDE gets autocompletion
// and documentation for these keys in application.yml.
The startup-versus-runtime difference is the argument. A missing or invalid property under @ConfigurationProperties stops the application from starting, which a deployment pipeline catches; under @Value it can surface as a 500 on one endpoint weeks later.
Picture it the same configuration mistakes made against an @Value field and against a @ConfigurationProperties record, and the metadata file the processor writes.
The setup: the two classes in the code above, with this yaml.
payment:
gateway-url: https://pay.example.com
retry:
max-attempts: 50
Make the invisible visible: what the processor generates from the record.
{
"properties": [
{ "name": "payment.gateway-url", "type": "java.lang.String", "sourceType": "com.acme.PaymentProperties" },
{ "name": "payment.timeout", "type": "java.time.Duration", "sourceType": "com.acme.PaymentProperties" },
{ "name": "payment.retry.max-attempts", "type": "java.lang.Integer", "sourceType": "com.acme.PaymentProperties$Retry" }
]
}
What you see: one startup report from the record.
# illustrative output
APPLICATION FAILED TO START
Binding to target ... failed:
Property: payment.retry.max-attempts
Value: "50"
Origin: class path resource [application.yml] - 4:19
Reason: must be less than or equal to 10
| Action | @Value | @ConfigurationProperties |
|---|---|---|
| Key payment.gateway-url missing | Throws IllegalArgumentException (could not resolve placeholder) when that bean is created | Startup fails with a binding report naming the property |
| Yaml has payment.gateway-url, code asks for payment.gatewayUrl | Fails: placeholder cannot be resolved | Works: relaxed binding |
| max-attempts set to 50 where 10 is the limit | Accepted, no check | Startup fails: must be less than or equal to 10 |
| IDE autocomplete for the key | None | Works with the configuration processor |
| Appears in /actuator/configprops | No | Yes |
Land it The binder gives you structure, validation, and origin in errors, and the processor gives your teammates autocomplete, which is why @Value should be rare.
- "Show me how binding a record with nested objects and a Duration looks, and where it fails."
A record such as
@ConfigurationProperties("payment") @Validated record PaymentProps(@NotBlank String baseUrl, @DurationMin(millis = 100) Duration timeout, @Valid Retry retry) { record Retry(@Min(0) int attempts, Duration backoff) {} }, registered with@EnableConfigurationProperties(PaymentProps.class)or@ConfigurationPropertiesScan.The binder maps
payment.base-url,payment.timeout=2s, andpayment.retry.attempts=3onto the constructor, converting2sthrough theDurationStyleparser and defaulting a missing nested record to null unless@DefaultValueis present.Failure looks like a startup report: "Binding to target failed: Property: payment.timeout, Value: 2 seconds, Origin: class path resource [application.yml] - 12:14, Reason: failed to convert".
Constructor binding requires exactly one constructor or a
@ConstructorBindingmarker when there are several, and a record with no matching keys at all is bound with null components, which the validation then rejects. As of Aug 2026, records are the recommended form.- "Where does @Value still have a legitimate use?"
In three narrow places. A single value inside a framework-level component that cannot depend on a properties bean without creating a cycle, such as a
BeanPostProcessoror anEnvironmentPostProcessorconfiguration.A SpEL expression that genuinely computes something, such as
@Value("#{T(java.lang.Runtime).getRuntime().availableProcessors() * 2}"), which properties binding cannot express. And a test that overrides one value.Everywhere else it is a liability: the key is a string that refactoring tools do not see, the default lives in the annotation rather than in documentation, and a typo produces a startup failure naming the bean but not the intended key.
When a codebase has hundreds of
@Valueusages, the migration is mechanical: group by prefix, create a record per prefix, inject the record. The configuration processor then gives the team autocomplete for keys it never had before.- "How does relaxed binding map an environment variable, and where does it surprise people?"
Environment variables are uppercased with underscores, so
SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZEandSPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZEboth bind tospring.datasource.hikari.maximum-pool-size, because the binder strips dashes and compares case-insensitively; the canonical form is lowercase kebab-case. The surprises: a list is written with numeric indexes,APP_HOSTS_0andAPP_HOSTS_1, not a comma-separated value, unless the target type is aStringor an array bound from a single value; map keys with dots or dashes are lost in environment form because underscores become dots, soAPP_HEADERS_X_TRACEbecomesapp.headers.x.trace, and the fix is the bracket form in a properties file or a JSON blob inSPRING_APPLICATION_JSON. The other surprise is that environment variables are treated as a single flat source, so a partially-set nested object binds partially rather than failing.environment variable to propertyruns offlineSPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE=20 -> spring.datasource.hikari.maximum-pool-size=20 ✓ APP_HOSTS_0=a APP_HOSTS_1=b -> app.hosts[0]=a, app.hosts[1]=b ✓ APP_HOSTS=a,b -> one string "a,b" unless the target binds from a single value APP_HEADERS_X_TRACE=1 -> app.headers.x.trace (the key was meant to be "x-trace") ✗- "What does /actuator/configprops show, and what does it hide?"
It lists every
@ConfigurationPropertiesbean with its prefix and the bound values as the object currently holds them, which is what the application is actually using, not what the files say; that distinction is the reason to read it during an incident.It masks values whose keys match the sanitising patterns, and as of Boot 3.x it masks everything unless
management.endpoint.configprops.show-values=when-authorizedoralwaysis set, so on a production management port the default is fully redacted.It hides
@Valueinjections entirely, since those are not properties beans, and it cannot show a property that was bound and later mutated by code.The companion is
/actuator/env/<key>, which shows every property source containing the key and which wins, and the two together answer "what did we tell it" and "what did it hear".
Q111 · Scenario. "You changed spring.datasource.hikari.maximum-pool-size to 20 in the ConfigMap and redeployed, but /actuator/metrics/hikaricp.connections.max still says 10. Walk through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a property change did not reach the pool. Either the value never arrived, a higher-priority source overrode it, or the pool is not configured from that property.
- Evidence:
/actuator/env/spring.datasource.hikari.maximum-pool-sizeshows every property source that has the key and which one wins./actuator/configpropsshows what theDataSourcePropertiesand Hikari bean actually hold.kubectl exec envin the pod shows whether the variable is present.
- Likely causes, ranked:
- The pod was not restarted: a ConfigMap change does not restart pods and environment variables are read at start, so the "redeploy" only updated the map.
- The environment variable name is wrong: the relaxed form is
SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE, and a version with dashes or lowercase is not bound. - A command-line argument or a Java system property in the Dockerfile's
ENTRYPOINTsets it to 10 and outranks the environment. - The
DataSourceis built by a custom@Beanthat hardcodes the size or binds a different prefix such asapp.datasource.hikari.
- Fix per cause:
- Annotate the deployment with a checksum of the ConfigMap, so a change rolls the pods.
- Correct the variable name.
- Remove the hardcoded flag.
- Bind the custom pool with
@ConfigurationPropertieson the same prefix, or document the real one.
- Prevention: a startup log line listing the effective pool size, and a rule that configuration changes go through the same pipeline as code, which restarts pods and runs the smoke check.
Picture it the ConfigMap, the running pod that still has the old value, the Actuator output that shows which source won, and the pod after the rollout.
The setup: a ConfigMap changed from 10 to 20, and a Deployment that reads it as an environment variable.
apiVersion: v1
kind: ConfigMap
metadata: { name: orders-config }
data:
SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE: "20" # was "10"
---
# Deployment container: envFrom: [ { configMapRef: { name: orders-config } } ]
# ❌ TRAP: editing the ConfigMap does not change the pod template, so no rollout happens
Make the invisible visible: which sources hold the key and which one wins.
{
"property": { "source": "systemProperties", "value": "10" },
"propertySources": [
{ "name": "systemProperties", "property": { "value": "10" } },
{ "name": "systemEnvironment", "property": { "value": "20",
"origin": "System Environment Property \"SPRING_DATASOURCE_HIKARI_MAXIMUM_POOL_SIZE\"" } }
]
}
// values are shown because management.endpoint.env.show-values=always; systemProperties outranks systemEnvironment
The trace: what happens to the environment of a running pod.
kubectl apply ConfigMap (20) ──► running pod's environment: still 10 ✗ env is captured at container start
kubectl rollout restart ──► new pod starts, environment = 20 ✓
Boot binds the property ──► Hikari maximum pool size 20 ✓ (unless a -D flag or a custom bean overrides it)
What you see: the metric before the fix.
{
"name": "hikaricp.connections.max",
"measurements": [ { "statistic": "VALUE", "value": 10.0 } ],
"availableTags": [ { "tag": "pool", "values": [ "HikariPool-1" ] } ]
}
Why: the Deployment is a template and the ConfigMap is data: changing the data does not change the template, and environment variables never change inside a running container.
The fix: make the template depend on the data.
spec:
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} # ✅ FIX: config change = template change = rollout
What you see now: the same metric after the rollout.
{
"name": "hikaricp.connections.max",
"measurements": [ { "statistic": "VALUE", "value": 20.0 } ],
"availableTags": [ { "tag": "pool", "values": [ "HikariPool-1" ] } ]
}
| Symptom | Root cause | Action |
|---|---|---|
| Env source shows 20, metric says 10, pod is old | ConfigMap change did not restart pods | Checksum annotation on the pod template |
| systemProperties or commandLineArgs shows 10 | -D flag or program argument in ENTRYPOINT / JAVA_TOOL_OPTIONS | Remove the flag |
| Env source shows 20, configprops has no Hikari section | Custom DataSource bean ignores the prefix | @ConfigurationProperties("spring.datasource.hikari") on the bean |
| Metric pool tag is not the main pool | A second HikariDataSource | Check the pool tag against the bean names |
Land it The env endpoint tells you which source won, and the most common answer is that the pod never restarted to read the new one.
- "The pod did restart, the env variable is present, and the metric still says 10. Now what?"
Then the value arrived and something else won or something else built the pool.
/actuator/env/spring.datasource.hikari.maximum-pool-sizesettles the first: it prints each property source containing the key in precedence order, and ifcommandLineArgsorsystemPropertieslists 10 abovesystemEnvironment, a-Dflag or a program argument in the entrypoint or inJAVA_TOOL_OPTIONSis overriding it.If the environment source is the only one and shows 20, the pool is not bound from that key: a custom
DataSource@BeanusingDataSourceBuilderwithout@ConfigurationProperties("spring.datasource.hikari")takes Hikari's default of 10, and/actuator/configpropswill show no Hikari section under that prefix.A third possibility is that the metric is from a second
HikariDataSource, such as a batch pool, so I check the metric'spooltag against the bean names before concluding anything.- "Why does a ConfigMap change not restart pods, and how do you make it?"
Kubernetes treats a ConfigMap as data and a Deployment as a template; changing the data does not change the template, so no rollout is triggered.
Mounted files do update in place after up to a minute, but environment variables are captured at container start and never change.
The standard trick is to make the template depend on the data: a checksum of the rendered ConfigMap goes into the pod template as an annotation, which Helm charts do with
checksum/config: {{ include ... | sha256sum }}, and Kustomize does by appending a content hash to the ConfigMap's name so the Deployment references a new object.Either way a config change becomes a template change and rolls the pods through the normal strategy, with graceful shutdown and readiness gating as in Q117.
Tools like Reloader watch ConfigMaps and trigger rollouts too, but the checksum approach keeps the behaviour in the manifest where reviewers see it.
- "Can Hikari's pool size be changed without a restart at all?"
Yes, through its MXBean.
HikariDataSource.getHikariPoolMXBean()andgetHikariConfigMXBean()exposesetMaximumPoolSizeandsetMinimumIdleat runtime, and Hikari applies them: a larger maximum lets new connections be created on demand, and a smaller one retires connections as they are returned.Exposing that as an Actuator endpoint or through JMX is a few lines, and it is useful during an incident to test a hypothesis without a deploy.
It is not a configuration mechanism, because the change is invisible to the manifest and disappears on the next restart, so the rule is that a runtime tweak must be followed by the same change in the ConfigMap and a rollout, and the endpoint logs who changed what.
I would keep it disabled by default and enable it on the management port behind authentication.
- "How would you make a configuration change go through the same pipeline as code?"
By putting the environment overlays in the same repository as the Helm chart or Kustomize base, and making the pipeline the only thing that applies them.
A change to
values-production.yamlis a pull request with the same required review, the same rendering step that produces the manifests, a policy check with something like Conftest or Kyverno on the rendered output, a smoke start of the jar against the rendered ConfigMap as in Q109, and then the rollout with the checksum annotation so pods restart.The result is that
kubectl edit configmapin production is unnecessary, and I remove the permission to do it from humans, leaving it to the deployer identity. The audit trail is the git log; the rollback is a revert.The cost is that a configuration change takes as long as a deploy, ten minutes, which is the correct cost for changing production.
Q112. "When would you refresh configuration at runtime with @RefreshScope, how does it work, and what does it do to a bean like a connection pool?"
Reveal answer
Strong answer @RefreshScope comes from Spring Cloud Context. A bean in that scope is wrapped in a scoped proxy, and its real instance lives in a scope cache.
When a refresh is triggered, by the /actuator/refresh endpoint, a Spring Cloud Bus message, or a config watcher:
- The
Environmentis rebuilt from its sources. - An
EnvironmentChangeEventis published, and@ConfigurationPropertiesbeans are rebound in place. - Every
@RefreshScopebean's cached instance is discarded, and the old one gets its@PreDestroy. - The next call through the proxy constructs a fresh instance with the new values.
That is right for stateless beans that read a few settings, such as a feature-flag holder or a client with a changed URL.
For a connection pool it is a bad idea. The refresh destroys the pool while requests hold connections. Recreating it means every in-flight request either fails or waits for reconnection. If the refresh fires during a spike, you have manufactured an outage.
Boot 2 and 3 pools are therefore not refresh-scoped by default, and the honest way to change a pool size is a rolling restart.
When I would use refresh at all: for a small set of tunables where a restart is disproportionate, such as log levels, which Actuator's loggers endpoint already handles without Cloud, and rate limits or thresholds held in a properties bean.
For everything else, a rolling restart is the simpler, safer mechanism, and Kubernetes makes it cheap.
Picture it the proxy and the scope cache before and after a refresh, what two requests experience while it happens, and which kinds of bean survive it.
The setup: a client bean in refresh scope, whose URL comes from a property.
@Component
@RefreshScope
class PaymentClient {
private final RestClient http;
PaymentClient(@Value("${payment.base-url}") String baseUrl) { // baked in at construction
this.http = RestClient.builder().baseUrl(baseUrl).build();
}
@PreDestroy void close() { /* ❌ TRAP: closes resources an in-flight call may still be using */ }
}
Make the invisible visible: the proxy the callers hold and the cache behind it.
# illustrative output
bean "paymentClient" -> RefreshScope proxy (callers hold this)
scope cache before refresh: scopedTarget.paymentClient -> PaymentClient@1a2b (base-url = https://old.example.com)
POST /actuator/refresh -> ["payment.base-url"]
scope cache after refresh: scopedTarget.paymentClient -> (empty, instance destroyed)
first call after refresh: scopedTarget.paymentClient -> PaymentClient@9f8e (base-url = https://new.example.com)
The trace: two requests around a refresh.
request A ──► proxy ──► PaymentClient@1a2b.pay() in flight (old instance)
refresh fires ──► cache cleared ──► @PreDestroy on @1a2b ✗ A's connection pool closed under it: A fails midway
request B ──► proxy ──► no cached instance ──► construct PaymentClient@9f8e on B's thread B pays the construction cost
request C ──► proxy ──► PaymentClient@9f8e ✓
Why: refresh does not change a running object; it throws the old one away and builds a new one, and in-flight callers are standing on the old one.
| Bean | Effect of a refresh |
|---|---|
| Stateless holder of a few settings (flag holder) | Works: rebuilt cheaply, nothing in flight depends on it |
| Client with a changed base URL | Works if cheap to build and its @PreDestroy does not close shared resources |
| Connection pool | Destroys connections that requests hold; in-flight work fails or waits |
| Log level | Not needed: the loggers endpoint mutates the live LoggingSystem in place |
The fix: read the value at use time from one updatable object instead of recreating a bean.
@ConfigurationProperties("limits")
class LimitsProperties { private int threshold = 100; /* getter, setter */ } // rebound in place on EnvironmentChangeEvent
@Service
class Throttle {
private final LimitsProperties props;
boolean allowed(int n) { return n <= props.getThreshold(); } // ✅ FIX: read on each call, nothing is rebuilt
}
Land it Refresh scope rebuilds beans in place, which is fine for settings and dangerous for anything holding connections, so prefer a rolling restart unless the bean is trivial.
- "What exactly happens to a request that is mid-call through a refresh-scoped bean when the refresh fires?"
The call in progress completes on the old instance, because the proxy resolved the target at the start of the method invocation and holds a reference; refresh only clears the scope cache and calls
destroyon the old instance.So if the old instance's
@PreDestroycloses a resource the in-flight call is using, such as a client's connection pool, the in-flight call fails midway.The next call through the proxy triggers construction of a new instance, synchronously, on the request thread that made it, so that request pays the construction cost, which for a bean that builds a client is tens of milliseconds and for one that opens a pool is seconds.
Many refreshes in a short period, for instance a bus broadcast during a deploy, make that cost recurring. The design consequence is that refresh-scoped beans should be cheap to build and should not own resources that in-flight callers depend on.
- "Does Boot's own Actuator loggers endpoint use refresh scope?"
No. The
loggersendpoint talks directly to theLoggingSystemabstraction, which for Logback callsLoggerContext.getLogger(name).setLevel(level), an in-place change on a live object with no bean recreation, which is why it is safe under load and available without Spring Cloud.POST /actuator/loggers/com.acme.orderswith{"configuredLevel": "DEBUG"}takes effect immediately and is per instance, so during an incident I apply it to one pod through the management port, and it reverts on restart.The lesson generalises: a value that a bean can re-read on each use, such as a level, a threshold, or a flag, can be changed by mutating one object; a value baked into a bean's construction, such as a pool size or a client's base URL, needs recreation.
Design the tunable settings as the first kind and you rarely need refresh scope.
- "How would you make a threshold changeable at runtime without refresh scope?"
Read it at use time from something that is itself updatable.
The simplest form: the
@ConfigurationPropertiesbean that holds the threshold is not refresh-scoped but is rebound onEnvironmentChangeEvent, which Spring Cloud'sConfigurationPropertiesRebinderalready does for all such beans; the consumer readsprops.getThreshold()on each request rather than copying it into a field at construction.Without Spring Cloud, the same effect comes from a small
AtomicReferenceholder that a management endpoint or a database poll updates, and consumers read the reference. Boot 4's support forConfigDataEnvironmentPostProcessorre-loading on demand is limited, so the holder pattern remains the portable answer.The rule is to separate "what the value is" from "who reads it": the reader takes the value fresh, and the updater changes one object, so nothing is recreated and nothing in flight breaks.
- "When is Spring Cloud Config plus refresh the right architecture?"
When configuration has to change more often than deploys happen and the same value has to change on many services at once, and when the platform is not Kubernetes or does not offer a reviewed configuration pipeline.
A classic case is a fleet of services on virtual machines where a rollout takes an hour and an operations team needs to tune rate limits or toggle integrations several times a day; Config Server with a git backend gives them a reviewed change, and the bus refresh applies it fleet-wide in seconds.
On Kubernetes with a GitOps pipeline, the deploy is already the reviewed, fast, fleet-wide mechanism, and adding Config Server means a second source of truth and a runtime dependency at startup, so I would not.
As of Aug 2026 the middle ground many teams use is Kubernetes ConfigMaps for deploy-time values plus a feature-flag service for the runtime ones, and no refresh scope at all.
Q113 · Design. "Design database credential rotation for a fleet of Boot services with zero downtime: passwords must change every 24 hours without restarts."
Reveal answer
Strong answer Requirements: every service rotates within a day, no restarts, no failed connections during rotation, and a compromised credential is short-lived.
Design: dynamic credentials from Vault's database secrets engine or the cloud equivalent. Each service, on startup, obtains a lease: Vault creates a database role with a random password and a 24-hour time to live.
Feeding Hikari, the simplest approach that works:
- Hikari reads credentials only when it creates a new connection.
- A
DataSourcewrapper supplies the current username and password each time the pool asks for a new connection. - With
max-lifetimeset below the lease length, say 20 minutes, every connection is retired and recreated with whatever credential is current. - No restart is needed.
Spring Cloud Vault and the AWS JDBC wrapper both implement this pattern of a credentials provider consulted at connection creation.
Rotation overlap and renewal:
- Overlap: the secret manager keeps the old credential valid for a grace period, at least as long as
max-lifetime, so a connection created just before rotation is still authenticated until retired. - Renewal: a background renewer refreshes the lease before expiry, with jitter across the fleet so 60 services do not hit Vault in the same second.
- Failure handling: if Vault is unreachable at renewal, the service keeps the current credential until its expiry and emits a health detail and a metric. The alert fires long before expiry.
Trade-offs: dynamic roles mean database-side users appear and disappear, which audit tooling must understand; the JDBC wrapper adds a small layer. What I would not do: put the password in a ConfigMap and restart the fleet daily, or refresh-scope the pool.
Picture it how connections move from the old credential to the new one over a rotation, what the database shows during it, and what goes wrong if the old credential is revoked too early.
The setup: a DataSource wrapper that reads the current credential each time Hikari creates a connection.
class RotatingDataSource extends DelegatingDataSource {
private final Supplier<Credentials> creds;
@Override public Connection getConnection() throws SQLException {
Credentials c = creds.get(); // reads /run/secrets on EVERY new connection
return super.getConnection(c.user(), c.password()); // ✅ FIX: no restart; new connections use the new credential
}
}
// HikariDataSource ds = new HikariDataSource();
// ds.setDataSource(new RotatingDataSource(...)); ds.setMaxLifetime(Duration.ofMinutes(20).toMillis());
Make the invisible visible: the pool as a list of connections and the credential each was made with.
# illustrative output
t = 0 10 connections, all created with v-app-OLD
t = 24 h Vault issues v-app-NEW; the secret file is rewritten; v-app-OLD stays valid (grace period)
t + 0..20 m each connection reaches max-lifetime; its replacement is created by getConnection(), which reads v-app-NEW
t + 25 m v-app-OLD is revoked; no connection is using it any more
The trace: one connection through the switch.
conn #7 created at t-18m with v-app-OLD ──► still works after rotation (authenticated at connect time) ✓
conn #7 retired at max-lifetime ──► Hikari asks for a new one ──► RotatingDataSource reads the file ──► v-app-NEW ✓
if v-app-OLD were revoked at t+1m, a connection created from a stale read fails to authenticate ✗
What you see: the sessions the database reports while the old role drains.
# illustrative output
SELECT usename, count(*) FROM pg_stat_activity WHERE datname = 'orders' GROUP BY usename;
usename | count usename | count usename | count
v-app-OLD | 10 v-app-OLD | 4 v-app-OLD | 0
v-app-NEW | 6 v-app-NEW | 10
(t = 0) (t + 10 m) (t + 25 m)
too-early revocation: FATAL: password authentication failed for user "v-app-OLD" (SQLSTATE 28P01)
Why: PostgreSQL authenticates at connect time only, so existing sessions survive a rotation and only new connections need the new credential.
| Symptom | Root cause | Action |
|---|---|---|
| Authentication failures just after rotation | Old credential revoked sooner than max-lifetime plus sync period | Grace period of at least max-lifetime plus the sync period |
| Old role sessions never drain | max-lifetime too long or unset | Set max-lifetime below the lease, about 20 minutes |
| 60 services hit Vault at once | Renewal at the same instant | Jitter across the fleet |
Going deeper HikariCP itself gives you the two calls the rotation needs.
HikariDataSource.getHikariConfigMXBean().setUsername(...) and setPassword(...) change the credentials the pool uses for new connections, without touching existing ones, and getHikariPoolMXBean().softEvictConnections() marks every current connection for retirement as soon as it is returned to the pool, so the pool rebuilds itself on the new credential within one request cycle rather than waiting for max-lifetime.
A rotation listener, triggered by the secret manager's lease renewal, calls the first two, then the third, and reports through a health detail.
Verification is a metric of connection creation time and a query of pg_stat_activity grouped by usename, which shows the old role's sessions draining to zero.
The one thing to avoid is evicting during a traffic spike, so the listener checks hikaricp.connections.pending and defers if it is non-zero.
Land it Rotate by letting connections expire naturally with a credential supplier consulted at creation, and keep the old credential valid for one connection lifetime.
- "The requirement changes: the database does not support dynamic roles, only a fixed user whose password we set. Does the design survive?"
Mostly, with one problem: a single user with one password has no overlap window, because the moment the password changes, connections created with the old one fail authentication.
Existing sessions stay valid, since PostgreSQL authenticates at connect time only, but every new connection created between the rotation and the application learning the new secret fails. Two fixes.
Use two users,
app_aandapp_b, with identical grants, and alternate: rotate the idle user's password, tell the applications to switch to it, wait onemax-lifetime, then rotate the other; the secret carries the current user name as well as the password.Or, with one user, have the application retry connection creation by re-reading the secret file on an authentication failure, which Hikari supports through a custom
DataSourcewrapper that refreshes credentials on28P01 invalid_password; that gives a few failed connection attempts per rotation, which is acceptable if the pool is fixed-size and warm.- "How does the application learn the new credential if it is a mounted file?"
Kubernetes rewrites mounted Secret files when the Secret changes, within the kubelet sync period of about a minute, using an atomic symlink swap, so a reader always sees a complete old or new file, never a partial one.
The application's credentials provider reads the file on each connection creation rather than once at startup: a
DataSourcewrapper around the Hikari pool's underlying driver, or Hikari's owndataSourcePropertiessupplier pattern, callsFiles.readString(Path.of("/run/secrets/db.password"))when Hikari asks for a new connection.Because it reads on demand, no restart and no refresh scope is involved. A
WatchServiceon the directory can additionally trigger the soft eviction so the switch is immediate rather than waiting formax-lifetime.Note that
subPathmounts do not update, so the Secret must be mounted as a directory.- "What would you cut in a first version, and what goes wrong?"
I would cut the immediate eviction and the health detail and keep the on-demand credential read and a
max-lifetimeof 20 minutes, so rotation completes within 20 minutes of the secret changing with zero code beyond the wrapper.What goes wrong without the overlap guarantee: if the old password is revoked less than 20 minutes after the new one is published, connections still alive on the old credential keep working, but a connection created in the window between the file update and the kubelet's sync, up to a minute, is made with the old password and fails; Hikari logs the failure and retries, so the visible effect is a brief rise in connection acquisition time.
The fix on the secret-manager side is a grace period of at least
max-lifetimeplus the sync period, which is a policy setting rather than code. Cutting the overlap itself is the one cut I would refuse.- "How do you test rotation before trusting it in production?"
With a Testcontainers PostgreSQL and a fake secret file.
The test starts the application against the container with the credential in a temporary directory, runs a background load of queries, then does
ALTER USER app PASSWORD 'new'on the container, writes the new value to the file, and asserts that queries keep succeeding for the next two minutes withmax-lifetimeset to 30 seconds for the test, and thatpg_stat_activityeventually shows only sessions authenticated after the change, which I detect throughbackend_start.A second test revokes the old password immediately after publishing the new one and asserts the failure count stays under a threshold, which documents the grace period requirement.
In staging, I run the real rotation on the real schedule for a week with the alert on connection failures active before enabling it in production, and the first production rotation happens in a low-traffic window with someone watching.
Q114. "How does Spring's caching abstraction work, why is there no TTL on @Cacheable, and what does sync = true protect against?"
Reveal answer
Strong answer @EnableCaching, applied by auto-configuration when a cache starter is present, registers a CacheInterceptor that proxies beans with cache annotations; the self-invocation rule applies.
On a @Cacheable call, the interceptor computes a key from the parameters, by default all of them as a SimpleKey, or from the key SpEL expression, asks the named Cache from the CacheManager for it, and returns the hit or invokes the method and stores the result.
The other annotations:
@CachePut: always invokes the method and stores the result.@CacheEvict: removes the entry, optionally withallEntries.beforeInvocation: decides whether a thrown exception still evicts.
The abstraction deliberately has no TTL because expiry is a property of the store, not of the method: Caffeine expires by spring.cache.caffeine.spec=maximumSize=10000,expireAfterWrite=5m, Redis by spring.cache.redis.time-to-live, and each store's semantics differ, so the annotation cannot express them portably.
sync = true addresses the stampede.
- Without it: a hundred concurrent calls for a missing key all execute the method and all store the result. For an expensive query that is a hundred times the load exactly when the cache is cold.
- With it: the interceptor uses the store's atomic get-or-compute, so one caller computes while the others wait for that result.
It applies only to a single @Cacheable with no other cache annotations on the method, and for Redis the lock is per instance, so a distributed stampede needs a different approach such as early refresh.
Null results are cached unless unless = "#result == null" is set, which is usually what you want to avoid.
@Service
public class ProductService {
// No ttl attribute exists — deliberately. The abstraction is a facade over
// caches with very different capabilities, so expiry is configured on the
// CACHE PROVIDER, not the annotation.
@Cacheable(cacheNames = "products", key = "#id")
public Product find(String id) { return repo.findById(id).orElseThrow(); } // Result: a second call with the same id never reaches the repository
@CachePut(cacheNames = "products", key = "#p.id") // updates the cache
public Product update(Product p) { return repo.save(p); }
@CacheEvict(cacheNames = "products", key = "#id") // removes the entry
public void delete(String id) { repo.deleteById(id); }
// sync = true: on a miss, ONE thread computes and the rest wait for it.
// Without it, 500 concurrent misses on a cold cache all hit the database —
// a cache stampede, which is how a cache makes an outage worse.
// ✅ FIX: sync = true on the next annotation
@Cacheable(cacheNames = "prices", key = "#id", sync = true)
public Price price(String id) { return expensiveLookup(id); }
// ❌ TRAP: a call such as find("42") from another method of THIS class goes straight
// to the real object, skips the proxy, and is never cached.
}
# Caffeine
spring.cache.type = caffeine
spring.cache.caffeine.spec = maximumSize=10000,expireAfterWrite=10m
# Redis
spring.cache.type = redis
spring.cache.redis.time-to-live = 10m
spring.cache.redis.cache-null-values = false
Note that the annotations are proxy-based like @Transactional. A @Cacheable method called from inside the same class is not cached at all, and there is no warning — the same self-invocation failure as Q10 and Q40.
Picture it what the cache holds, how a cold-cache burst reaches the database with and without sync = true, and the self-invocation case that is never cached.
The setup: the ProductService in the code above, called by 500 concurrent requests for the same missing price.
Make the invisible visible: the cache registry and the entries.
# illustrative output
cacheManager "cacheManager" -> caches: "products", "prices" (Caffeine, expiry set by spring.cache.caffeine.spec)
products: "42" -> Product(id=42, name=Lamp)
prices: (empty, cold)
key forms: one parameter -> that value; two parameters -> SimpleKey [42, EUR]
The trace: 500 requests meet a cold key.
without sync: 500 requests ──► interceptor: miss ──► 500 x expensiveLookup() ──► 500 x store ✗ database takes 500 times the load
with sync=true: 500 requests ──► Cache.get(key, loader): first caller computes, 499 wait ✓ one lookup, one store
self-invocation: this.find("42") ──► real object, interceptor never entered ✗ every call hits the repository
What you see: the database call counter in each case.
# illustrative output
price("42") x 500 concurrent, cold cache
sync = false: SELECT ... FROM price x 500
sync = true: SELECT ... FROM price x 1 (per application instance)
Why: the cache is checked before the method runs, and without sync every thread that misses runs the method independently.
The fix: sync = true on the expensive read, and calls routed through the injected proxy rather than this.
| Call | Result |
|---|---|
| find("42") twice from a controller | Works: second call served from the cache |
| find("42") from another method of the same class | Silently not cached: no proxy involved |
| price("9") x 500 concurrent, sync = false | 500 database calls |
| price("9") x 500 concurrent, sync = true | 1 database call per instance |
Land it The annotations decide what is cached and the store decides for how long, and sync = true is the one-line fix for cold-cache stampedes.
- "How does sync = true actually work for Caffeine versus Redis?"
The interceptor calls
Cache.get(key, Callable)instead ofgetthenput. Caffeine's implementation isConcurrentHashMap.computeIfAbsentsemantics: the first thread holds the bin lock while it computes, and other threads for the same key block until the value is present, so exactly one computation runs per instance.Spring's Redis cache implements the same method with a per-instance lock keyed on the cache name, and optionally a Redis-side lock with
RedisCacheWriter.lockingRedisCacheWriter(), which usesSETNXso that across instances only one computes while others spin on the lock with a sleep; that adds latency and a lock-expiry failure mode, and it is off by default.So with Redis and ten instances, the default
sync = truestill allows up to ten computations for one cold key, one per instance, which is usually fine.The remaining hazard is a very slow compute holding Caffeine's bin lock and blocking unrelated keys that hash to the same bin.
- "What are the failure modes of caching null and of caching exceptions?"
Caching null turns "not found" into a fact for the TTL: a product created a second after a lookup stays invisible on that instance until expiry.
That is sometimes desired, since it protects against repeated misses for keys that never exist, but it needs an explicit short TTL or the
unless = "#result == null"guard.Exceptions are never cached by the abstraction: if the method throws, nothing is stored and the exception propagates, so a failing dependency gets hammered by every caller at full rate, which is the opposite of what you want during an outage.
The protection for that is to cache a fallback value with a separate short TTL, or to combine
@Cacheablewith a circuit breaker so the exception is replaced by a fast failure.Both cases share the rule that the cache should store answers, and "I could not get an answer" is not one; it is a state that needs its own policy.
null and exception behaviourruns offline# illustrative output find("999") -> null, cached for the whole TTL; product created 1 s later stays invisible on this instance find("1") -> throws nothing stored; the next 500 callers each hit the failing dependency- "How do you set different TTLs for different caches in one application?"
Through the store's configuration per cache name, since the annotation cannot carry it. For Caffeine, a
CacheManagerCustomizer<CaffeineCacheManager>or a hand-builtCaffeineCacheManagerwhereregisterCustomCache("products", Caffeine.newBuilder().expireAfterWrite(10, MINUTES).maximumSize(10_000).build())defines each, andspring.cache.cache-namesis left unset so no default cache is created for unknown names.For Redis,
RedisCacheManagerBuilderCustomizerwithwithCacheConfiguration("products", RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10))).I keep those definitions in one class next to a constant for each cache name, so the name, the TTL, the size, and the owner of eviction live together, and a
@Cacheable("prodcuts")typo fails at startup rather than creating a silent new cache; settingCaffeineCacheManager.setAllowNullValuesand disabling dynamic cache creation makes the typo an error.- "When is the caching abstraction the wrong tool, and what do you use instead?"
It is the wrong tool when the cache is the data structure rather than an accelerator: a session store, a rate-limiter's counters, a leaderboard, or anything that needs atomic operations such as increment, compare-and-set, or expiry per entry.
There the abstraction's get-and-put shape hides the operations you need, and I use the store's client directly,
StringRedisTemplateor Lettuce commands, or Caffeine's own API withasMap().compute.It is also the wrong tool for read-through caching of large objects that vary by many parameters, where the key expression becomes a hash of half the request and the hit rate is low.
And it is wrong when eviction must be exact across instances, such as an authorisation cache after a permission revocation; that needs a versioned key or a broadcast, which Q115 covers, and the abstraction has no notion of it.
For "make this expensive read cheaper for a few minutes", it is exactly right.
Q115 · Scenario. "After an update through the admin API, reads through the public API keep returning the old product price for up to 10 minutes, but only on some instances. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: stale reads bounded by a time window and varying by instance. That is a per-instance cache with a 10-minute expiry that the update path did not invalidate.
- Evidence:
@Cacheable("products")on the read service, with a Caffeine cache andexpireAfterWrite=10m.- The update service either has no
@CacheEvict, or has one with a different key expression: for example the read uses#idand the evict uses#product.idon a different type, or the update goes through a repository path that bypasses the annotated method entirely. - Caffeine is local, so the instance that handled the update evicted its own cache and the other nine kept theirs.
- Fix, by layers:
- Make the keys match by defining them explicitly on both annotations, or use a
@Cachinggroup with@CachePuton the update so the new value replaces the old. - Then solve the fleet problem, in one of two ways.
- Move the cache to Redis so one eviction is visible to all instances, accepting a network hop per read.
- Or keep local caches and broadcast invalidations through a Redis pub-sub channel or a Kafka topic so every instance evicts, with the local cache's TTL as the safety net for missed messages.
- Lower the TTL to what the business tolerates, since even a perfect invalidation has a window under load.
- Make the keys match by defining them explicitly on both annotations, or use a
- Prevention: an integration test with two contexts or two instances that updates on one and reads on the other, and a naming convention where every cache name has a documented owner of its eviction.
Picture it ten instances each holding their own copy of the price, which one evicted, and what a customer sees over six requests.
The setup: a read and an update whose cache keys are different types.
@Cacheable(cacheNames = "products", key = "#id") // id is a String: key "42"
public Product find(String id) { ... }
@CacheEvict(cacheNames = "products", key = "#product.id") // ❌ TRAP: product.id is a Long: key 42, a different key
public void update(Product product) { ... }
// ✅ FIX: same type on both sides, and a CachePut so the new value replaces the old
@CachePut(cacheNames = "products", key = "#product.id.toString()")
public Product update(Product product) { return repo.save(product); }
Make the invisible visible: each instance has its own cache.
# illustrative output (price changed from 24.99 to 19.99 at 09:05)
instance A (handled the update) products: "42" -> evicted at 09:05 next read loads 19.99
instance B products: "42" -> 24.99, cached 09:01 stale until 09:11 ✗
instance C products: "42" -> 24.99, cached 09:03 stale until 09:13 ✗
... instances D to J: the same, each with its own expiry time
The trace: the update and the reads, hop by hop.
admin PUT /products/42 ──► instance A ──► update() ──► @CacheEvict key 42 (Long) ✗ cached key is "42" (String): nothing matches
(even with matching keys, only A's local cache is touched) ✗ B..J keep 24.99
public GET /products/42 ──► load balancer ──► instance B ──► cache hit 24.99 ✗ stale
What you see: six requests behind the load balancer.
# illustrative output
$ for i in 1 2 3 4 5 6; do curl -s https://api.example.com/products/42 | jq .price; done
24.99
19.99
24.99
24.99
19.99
24.99 <- depends on which instance answered; 10 minutes later all show 19.99
Why: the key on the evict side is a different value than the key the read stored, and the cache is local to each instance.
What you see now: after matching keys and a broadcast eviction.
# illustrative output
$ for i in 1 2 3 4 5 6; do curl -s https://api.example.com/products/42 | jq .price; done
19.99
19.99
19.99
19.99
19.99
19.99 <- every instance evicted on the broadcast message; the TTL covers a missed message
| Symptom | Root cause | Action |
|---|---|---|
| No instance ever sees the update early | Evict key differs from read key | Same key expression or a shared KeyGenerator on both annotations |
| Only the instance that handled the update is fresh | Local cache, eviction not shared | Redis cache, or broadcast eviction with TTL as a backstop |
| One instance stale for the full TTL after broadcast | Message missed or different key | Shorter TTL, durable channel, verify key strings |
Land it A local cache invalidated on one instance is stale on the others, so either share the store or share the eviction, and always keep a TTL as the backstop.
- "You added a broadcast eviction and one instance still served the stale price for the full 10 minutes. Why?"
Either that instance never received the message or it evicted a different key. For pub-sub over Redis, messages are fire-and-forget: an instance whose subscriber connection was reconnecting at that moment misses it, and Redis does not replay.
The TTL was the intended backstop, so the observed behaviour is the design working at its worst case, and the fix is a shorter TTL or a durable channel, such as a Kafka topic with each instance in its own consumer group reading from the latest offset on startup.
If the message arrived, the evict may have targeted
products::42while the cached key wasproducts::SimpleKey [42, EUR], because the read method had two parameters; thekeyexpression on both sides must produce identical strings.I verify by logging the key in a
CacheErrorHandleror with Caffeine'srecordStatsand the eviction count, and by reproducing with two local instances.- "Why not just use Redis as the cache and be done with the fleet problem?"
It solves consistency and costs latency and a dependency.
Every read becomes a network round trip of roughly half a millisecond within a zone, and the price endpoint at 5,000 requests per second now depends on Redis being up and fast; a Redis stall becomes an application stall unless the client has short timeouts and a fallback to the database.
A local Caffeine cache answers in nanoseconds with no dependency.
The usual resolution is both, layered: Caffeine in front with a short TTL of 30 seconds to absorb hot keys, Redis behind it with the longer TTL as the shared truth, and invalidation clearing Redis and broadcasting to the local layers.
Spring's
CompositeCacheManagerdoes not implement layering correctly, so this needs a small customCacheimplementation or the two-level cache support in libraries such as jetcache. For a single hot endpoint, I would start with Redis alone and add the local layer when its latency shows.- "How do you make the update path and the read path agree on the key, structurally?"
By defining the key in one place and referencing it from both. A
@CacheConfig(cacheNames = "products")on the class sets the name once.A custom
KeyGeneratorbean,productKeyGenerator, that takes the first argument and extracts the id whether it is aLongor aProduct, referenced bykeyGeneratoron both annotations, removes the SpEL duplication.Better still, the update method takes the same id parameter as the read and applies the change from a separate command object, so both methods' signatures start with
Long productIdand the default key is already identical.The test that pins it: a slice test with a real
CacheManagerthat calls read, update, read, and asserts the second read hit the method, using a counter in a spied service. That test fails the moment someone changes one signature and not the other.- "What is the acceptable staleness, and who decides?"
The business, explicitly, and the engineer's job is to make the choice visible. For a product price, the questions are whether a customer can be charged the old price after an update, which is a legal and revenue question, and how often prices change.
The answer usually splits: the price shown in listings can be a minute stale, but the price at checkout must be read from the source of truth, so the checkout path bypasses the cache with a direct repository call or a
@Cacheable(condition = ...)that excludes it.Once the number is agreed, it goes in the cache definition next to the name, in a comment and in the TTL, and the invalidation is treated as an optimisation that makes the common case better, not as the guarantee.
Designing around "invalidation always works" is how the 10-minute stale price became a support ticket.
10 · DrillProduction Scenarios & Design — Q116–Q150
The last section is the one that decides senior versus staff.
It is mostly scenarios and designs: memory and startup in containers, rolling deploys that drop nothing, observability that names the culprit, resilience that fails small, scheduling and messaging across a fleet, and the migrations every Boot shop is living through in 2026.
Several questions reach into the Distributed Systems primer and Chapter E7, because a Boot service in production is a distributed-systems participant whether it wants to be or not. Answer scenarios in diagnosis order and designs with assumptions first.
These questions test whether you can run a JVM inside a container without being surprised by it, and roll a new version without dropping a request.
Q116 · Scenario. "A service's memory climbs steadily from 400 MB to its 1 GB limit over about two days after every deploy, then it is OOM-killed and the cycle restarts. Heap dumps show nothing obvious. Walk through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom: linear growth to the container limit, reset by restart, with a heap that does not explain it. Two families: a slow heap leak the dump analysis missed, or growth outside the heap.
- Evidence: compare
jvm.memory.usedfor heap and for non-heap against the container's working set over the two days. If heap used after a full GC keeps rising, it is a heap leak; if heap is flat and the working set rises, it is native memory. Enable-XX:NativeMemoryTracking=summaryand diffjcmd VM.native_memory summary.diffa day apart. Take two heap dumps a day apart and compare dominator trees rather than reading one. - Likely causes, ranked. Native side:
- Thread stacks: a thread leak, visible as a rising thread count in
jvm.threads.live, typically an executor created per request or per Kafka rebalance and never shut down. - Direct buffers: direct
ByteBuffers from an HTTP client or Netty without release. - Metaspace: growth from classes generated at runtime, such as a CGLIB proxy or a Groovy or SpEL expression compiled per call.
- glibc malloc fragmentation: shows as RSS above every JVM number and is fixed by
MALLOC_ARENA_MAX=2or jemalloc.
- Unbounded cache: a cache with no size limit.
- ThreadLocal: a
ThreadLocalnever removed on pooled threads. - Listeners: listeners registered per request.
- Persistence context: Hibernate's persistence context in a long-lived transaction.
- Meters: Micrometer meters with unbounded tag values.
- Thread stacks: a thread leak, visible as a rising thread count in
- Fix per cause: bound the cache with Caffeine's maximum size, shut down executors, cap the tag cardinality, release buffers, set
MaxMetaspaceSizeso metaspace growth fails loudly, and set the malloc arena variable in the container. - Prevention: alert on the slope of memory rather than the level, and keep NMT on at summary level in one canary pod permanently.
Picture it A pod whose heap stays flat while its thread count, and with it native memory, climbs until the container limit is hit.
The setup: a controller that builds a new executor on every request and never shuts it down. The heap dump looks innocent because a pool object is tiny; the cost is its threads.
@GetMapping("/reports/{id}")
Report report(@PathVariable long id) throws Exception {
// ❌ TRAP: a new pool per request; its 4 core threads never end and are never shut down
ExecutorService pool = Executors.newFixedThreadPool(4);
return pool.submit(() -> build(id)).get();
// Result: every call leaves 4 parked threads, each with a stack in native memory
}
Make the invisible visible: the same pod read at three moments. Heap after a full GC is flat, so the leak is outside the heap.
# illustrative output
moment heap after full GC jvm.threads.live NMT "Thread" container working set
deploy 210 MB 64 ~70 MB 400 MB
day 1 215 MB 2,900 ~380 MB 720 MB
day 2 220 MB 5,300 ~640 MB 1,000 MB -> OOMKilled, exit code 137
The trace: the order of questions that separates the two families.
working set rising toward the limit
├─ heap after full GC rising? yes ─► heap leak ─► two heap dumps a day apart, compare dominator trees
└─ heap flat? yes ─► native ─► jcmd <pid> VM.native_memory summary.diff
├─ "Thread" grows ─► jvm.threads.live rising ─► thread dump, group by name prefix
├─ direct buffers / class ─► jvm.buffer.memory.used, metaspace metrics
└─ NMT total flat, RSS grows ─► glibc arenas ─► MALLOC_ARENA_MAX=2 or jemalloc
What you see: the diff of two NMT snapshots a day apart points at one category.
# illustrative output
$ jcmd <pid> VM.native_memory summary.diff
- Thread (reserved=5,432,104KB +4,980,000KB, committed=655,000KB +590,000KB)
(thread #5300 +4800)
- Class (reserved=1,100,000KB +0KB, committed=62,000KB +300KB)
| Symptom | Root cause | Action |
|---|---|---|
| Thread count rises, NMT Thread grows | Executor or client created per request and never closed | One shared bean with close in @PreDestroy; name threads so the owner is visible |
| Heap after full GC rises, one class count grows between dumps | Unbounded cache, ThreadLocal on pooled threads, listeners per request | Bound the cache, remove the ThreadLocal in finally, unregister listeners |
| NMT total flat, RSS above every JVM number | glibc malloc arena fragmentation | MALLOC_ARENA_MAX=2 or jemalloc |
| Metaspace grows steadily | Classes generated per call (proxies, scripts, expressions) | Cache the compiled form; set MaxMetaspaceSize so it fails loudly |
The fix: one pool owned by the container, shut down with the context.
@Bean(destroyMethod = "shutdown")
ExecutorService reportPool() {
// ✅ FIX: one bean, named threads, closed on context shutdown
return Executors.newFixedThreadPool(4, Thread.ofPlatform().name("report-", 0).factory());
}
What you see now: the same table after the fix, flat on every line.
# illustrative output
moment heap after full GC jvm.threads.live NMT "Thread" container working set
deploy 210 MB 64 ~70 MB 400 MB
day 1 212 MB 66 ~70 MB 430 MB
day 2 214 MB 66 ~70 MB 440 MB
Land it Decide heap versus native from the metrics first, and diff two snapshots rather than reading one, because a slow leak is a slope, not a state.
- "Native memory tracking shows the growth is in 'Thread'. Walk me through pinning it to code."
The thread count tells me the shape:
jvm.threads.liverising steadily says threads are created and not ending.A thread dump,
jcmd <pid> Thread.print, lists them with names, and the name prefix names the creator:pool-37-thread-1is a defaultExecutors.newFixedThreadPoolwithout a name,kafka-producer-network-thread | producer-812is aKafkaProducercreated and never closed,lettuce-eventExecutorLoopmultiplied means a Redis client per call, andHttpClient-123-SelectorManagermeans ajava.net.http.HttpClientbuilt per request, which as of Java 21 has a selector thread each.Two dumps an hour apart, diffed by name prefix, show which family grows. From there the code search is for the constructor of that type, and the fix is a singleton bean with a proper
closein@PreDestroy. Java 21'sHttpClientbecameAutoCloseablefor exactly this reason.thread dump names, counted by prefixruns offline# illustrative output $ jcmd <pid> Thread.print | grep '^"' | sed 's/-[0-9]*.*//' | sort | uniq -c | sort -rn | head -3 5188 "pool <- Executors.newFixedThreadPool without a name: find the constructor call 64 "http-nio <- Tomcat, expected 12 "kafka-producer-network-thread | producer" <- one producer, fine; hundreds would mean one per call- "Heap dumps showed nothing because the leak is small objects. How do you make a dump useful?"
By comparing rather than reading.
One dump is a snapshot of a working application, and the leak is a few percent of it; two dumps a day apart, opened in Eclipse MAT with the histogram compared by class, show which class's instance count increased and by how much, and that class is the leak even if it is
String.Then the dominator tree for those instances shows what holds them: a
ConcurrentHashMapin a cache, aThreadLocalMapon pooled threads, a listener list on an event multicaster.Taking a dump on a 1-gigabyte heap costs a stop-the-world pause of a few seconds and produces a file of the heap's size, so it goes to a pod that has been drained from the load balancer, with
jcmd <pid> GC.heap_dump -all=false /tmp/h.hprofto include only live objects after a full GC. Heap sampling with JFR'sObjectAllocationSampleandOldObjectSampleevents gives the allocation sites too, continuously and cheaply.- "Why would glibc fragmentation show as a leak, and how would you confirm it?"
glibc's malloc creates a separate arena per thread up to 8 times the core count, and each arena grows in 64-megabyte heaps that are rarely returned to the operating system; a JVM with 200 threads doing small native allocations, through JNI, zip inflation, or direct buffers, fragments those arenas and the resident set grows even though the JVM's own accounting is flat.
The confirmation is the gap: NMT's committed total stays constant while the container's working set climbs, and
pmap -x <pid>shows many 64-megabyte anonymous regions.The fix is
MALLOC_ARENA_MAX=2in the container's environment, which caps the arenas, or replacing the allocator with jemalloc viaLD_PRELOAD, which many base images for JVMs do. After the change, the RSS curve flattens within a day, which is the proof.It is common enough that I set the arena variable in the platform base image by default.
- "What alert catches this before the OOM kill, and how do you avoid false pages?"
An alert on the slope of memory, projected to the limit. In Prometheus,
predict_linear(container_memory_working_set_bytes[6h], 24 * 3600) > container_spec_memory_limit_bytesfires when the six-hour trend would cross the limit within a day, which for a two-day leak gives a day of warning.The false-page control is duration and scope: require the condition to hold for 30 minutes so a warm-up ramp does not trigger, evaluate per pod and alert only when a majority of pods show it so a single busy pod does not page, and route it to a ticket rather than a page unless the projected time is under 4 hours.
Alongside it, a plain restart-count alert catches the OOM kills themselves. What I stop doing is alerting on "memory above 80 percent", which is normal for a JVM that sizes its heap to the container and pages constantly for nothing.
Q117 · Design. "Design the shutdown and probe configuration for a Boot service on Kubernetes so that a rolling deploy drops zero requests, including long-running ones of up to 40 seconds."
Reveal answer
Strong answer Requirements: no new traffic to a terminating pod, in-flight requests up to 40 seconds complete, the pod exits before the kill deadline, and new pods receive traffic only when actually ready. Design, in sequence.
Startup: a startup probe on /actuator/health/liveness with a generous failure threshold covers slow starts so liveness does not kill a pod mid-boot; readiness on /actuator/health/readiness with management.endpoint.health.probes.enabled=true, and any cache warming runs before ApplicationReadyEvent so readiness reflects it.
Shutdown: server.shutdown=graceful (the default in Boot 4) and spring.lifecycle.timeout-per-shutdown-phase=45s so the server waits up to 45 seconds for in-flight requests.
On SIGTERM, Boot's ReadinessState flips to REFUSING_TRAFFIC and the readiness probe fails, but endpoint propagation to every kube-proxy and ingress takes a few seconds, so a preStop hook of sleep 8 holds the process while the load balancers stop routing to it.
Then the server stops accepting new connections, drains, closes the context, closes pools, exits. Deadline: terminationGracePeriodSeconds must exceed preStop plus the drain timeout plus a margin, so 60. Rollout: maxUnavailable=0, maxSurge=1, so capacity never dips, and a PodDisruptionBudget for node drains.
Clients: the ingress idle timeout is set below the server's keep-alive so the balancer never reuses a connection the server is closing.
For Kafka consumers in the same pod, the listener container's shutdownTimeout is set so it finishes the current batch and commits offsets before the context closes.
Trade-offs: a 60-second grace makes deploys slower; that is the price of 40-second requests, and the better fix is making those requests asynchronous as in Q78.
What I would not do: rely on the readiness flip alone without the preStop delay, or set a drain timeout longer than the grace period, which guarantees SIGKILL mid-request.
Picture it A single terminating pod laid out on a clock, so every setting is a visible interval that must fit inside the next.
The setup: the properties and manifest in the code below, with these values from the answer: preStop sleep 8, drain timeout 45, grace period 60.
Make the invisible visible: the timeline of one pod from the moment the rollout replaces it.
t=0s pod marked Terminating; preStop runs: sleep 8 (app still ready, still serving)
t=0-3s endpoint removal reaches kube-proxy and ingress (traffic still arrives and is served ✓)
t=8s preStop ends; SIGTERM; ReadinessState = REFUSING_TRAFFIC; Tomcat stops accepting
t=8-48s in-flight requests (up to 40 s) finish (drain; limit is 45 s per shutdown phase)
t=48s context closes, pools close, JVM exits
t=60s terminationGracePeriodSeconds: SIGKILL deadline (never reached ✓)
The trace: the arithmetic that must hold, and what each broken variant looks like.
| Configuration | What happens | Outcome |
|---|---|---|
| preStop 8, drain 45, grace 60 (8 + 45 = 53 < 60) | Everything finishes before the deadline | Works |
| No preStop, graceful on | Pod refuses connections while the balancer still routes to it | Connection refused or 502 for a few seconds per pod |
| Drain 45, grace 40 | SIGKILL arrives while a 40 s request is mid-flight | Request cut, connection reset |
| Readiness flip only, no preStop delay | Endpoint propagation lags the flip | Small constant error rate on every deploy |
| maxUnavailable 0, maxSurge 1 | New pod must be ready before an old one stops | Capacity never dips |
What you see: a load test that spans the rollout, before and after.
# illustrative output (k6, mix of short and 40 s requests, kubectl rollout restart mid-run)
before: http_req_failed ... 0.31% (62 of 20000) 502 from ingress / connection refused
after : http_req_failed ... 0.00% (0 of 20000)
Going deeper One version detail: graceful shutdown has been Boot's default since 3.4, released November 2024, not only since 4.x; server.shutdown=immediate restores the old behaviour.
The default drain budget, spring.lifecycle.timeout-per-shutdown-phase, is 30 seconds, and it applies per lifecycle phase, so the web server's drain and the Kafka container's stop each get their own 30 seconds in sequence if they are in different phases, which is why the sum can exceed a 60-second grace period.
During the drain, Tomcat stops accepting new connections but keeps existing keep-alive connections open and serves requests on them until they are idle, so a client that keeps reusing a connection can stretch the drain to its full timeout.
Verification is a load test that starts a rollout mid-run and asserts zero non-2xx responses, with the pod's Terminating duration read from the events.
# 1. ✅ FIX: stop accepting new requests, let in-flight ones finish.
server.shutdown = graceful
spring.lifecycle.timeout-per-shutdown-phase = 30s
# 2. Separate liveness from readiness. Without this, Boot exposes only
# /actuator/health and you cannot distinguish "restart me" from "not ready".
management.endpoint.health.probes.enabled = true
management.endpoints.web.exposure.include = health,info,prometheus
# -> /actuator/health/liveness and /actuator/health/readiness
# Result: SIGTERM -> readiness fails -> Tomcat drains in-flight requests for up to 30s -> exit
containers:
- name: order-service
lifecycle:
preStop:
exec:
# THE CRITICAL PIECE. On termination, kubelet sends SIGTERM and
# removes the pod from Endpoints AT THE SAME TIME - and endpoint
# propagation to every kube-proxy is not instant. Without this sleep,
# traffic is still being routed to a pod that has stopped accepting it.
# That is the 0.3% of failed requests during a rolling deploy.
# ❌ TRAP: omit this hook. ✅ FIX: keep it. Result: the 0.3% disappears.
command: ["sh", "-c", "sleep 10"]
# Must exceed preStop sleep + graceful shutdown timeout.
terminationGracePeriodSeconds: 45
readinessProbe: # "route traffic to me" - remove on failure
httpGet: { path: /actuator/health/readiness, port: 8080 }
periodSeconds: 5
failureThreshold: 2
livenessProbe: # "restart me" - must NOT check dependencies
httpGet: { path: /actuator/health/liveness, port: 8080 }
periodSeconds: 10
failureThreshold: 3
initialDelaySeconds: 30
The preStop sleep is what most teams are missing, and it explains the small, constant percentage of failed requests on every rolling deploy: the pod stops accepting connections before the load balancer has finished being told to stop sending them.
Land it Stop being routable, wait for the balancers to notice, drain within the grace period, and make sure the numbers add up in that order.
- "Why sleep 8 in preStop, and how would you pick the right number for a given cluster?"
Because readiness failing and the endpoint being removed from every proxy are separate events with a lag between them.
When the pod gets SIGTERM, the kubelet marks the pod terminating and the endpoints controller removes it from the Service's endpoints; kube-proxy on every node, the ingress controller, and any service mesh then have to observe that change and rewrite their routing, which takes from under a second to several seconds depending on cluster size and the ingress's sync interval.
The
preStophook runs before SIGTERM is delivered, so sleeping there keeps the process serving while routing catches up.The number comes from measurement: the ingress controller's own metric for sync duration, and a test rollout under load where the sleep is reduced until errors appear, then doubled. Five to ten seconds covers most clusters; a mesh with slow endpoint discovery may need fifteen. It is also worth noting that the sleep counts against
terminationGracePeriodSeconds.- "The requirement changes: requests can now take up to 5 minutes. Does the design scale to that?"
It scales, but the numbers become unpleasant enough to argue for a redesign.
Mechanically, the drain timeout becomes 5 minutes plus margin,
terminationGracePeriodSecondsbecomes about 330, and every rolling deploy of 20 pods withmaxSurge=1now takes up to two hours, node drains take as long, and a cluster upgrade is a day.The kubelet honours it, so correctness holds.
What I would say to the requirement is that a 5-minute synchronous request is a client timeout waiting to happen, at the load balancer, at the client library, or at a corporate proxy, and it is the case Q78 exists for: turn it into a job with an id and a poll, and the deploy problem disappears along with the client timeout problem.
If the requirement cannot change, I would isolate those endpoints in their own deployment with the long grace period, so the fast API deploys quickly and only the slow one drains slowly.
- "What would you cut under time pressure, and what breaks?"
The minimum that works is three settings:
server.shutdown=gracefulwith a drain timeout above the longest request, apreStopsleep, and aterminationGracePeriodSecondsthat covers both.Those stop the two main sources of errors, requests arriving after the pod stopped listening and requests cut by SIGKILL. What I would cut first is the startup probe, if startup is reliably fast, and the
PodDisruptionBudget, if the cluster is not autoscaled and nodes are not drained often.What breaks without them: without the startup probe, a slow start on a busy node trips liveness and the pod restarts in a loop; without the budget, a node drain can evict several pods at once and capacity dips.
Both are ten-line manifests, so "time pressure" would have to be severe. What I would never cut is the arithmetic check that grace exceeds sleep plus drain, because that one produces errors on every deploy.
- "How do you prove zero dropped requests rather than assert it?"
With a load test that spans a rollout and counts failures at the client.
A generator such as k6 or Gatling runs a steady load with a mix of short and 40-second requests against the ingress, and mid-run the pipeline triggers
kubectl rollout restart; the client counts non-2xx responses and connection errors, and the acceptance criterion is zero, not a percentage.The rollout is repeated three times in one run, since the first may be lucky. On the server side, I correlate
http.server.requestsby pod with the pod termination events, and check the ingress logs for any 502 or 499 in the window.This runs in staging on every change to the deployment manifest or the shutdown properties, and once a week in production during a low-traffic window with the same client.
A rollout that drops nothing in this test drops nothing in practice, because the test exercises exactly the race the design addresses.
Q118 · Scenario. "During every rolling deploy about 0.3 percent of requests fail with connection reset or 502, then everything is fine. Graceful shutdown is enabled. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: errors only during rollouts, small and consistent, with graceful shutdown on. Graceful shutdown drains requests already accepted; these failures are requests arriving at a pod that has stopped accepting, or at a new pod not yet able to serve.
- Evidence: correlate the error timestamps with pod termination and pod ready events; check the ingress logs for which upstream failed and whether it was a connect failure (old pod gone) or a reset on a reused connection (keep-alive race).
- Likely causes, ranked:
- No preStop delay: the pod stops accepting while the ingress still routes to it for a few seconds.
- Keep-alive race: the ingress or client reuses a keep-alive connection that Tomcat closed at shutdown, which surfaces as a reset on the next request over that connection.
- Cold caches and pools: readiness passes before the new pod's caches and pools are warm, so the first requests time out.
- JIT cold start: the first few hundred requests on the new pod are slow and exceed the client timeout.
- Short drain: the old pod's drain timeout is shorter than some requests.
- Fix: add
preStop: sleep 8; make the ingress idle timeout shorter than the server keep-alive and enable retries on idempotent methods at the ingress for connection-level failures; delay readiness until warm-up is done, and warm the JIT with a few synthetic requests in anApplicationRunnerbefore flipping readiness; extend the drain timeout to cover the longest request. - Prevention: a deploy dashboard panel that overlays error rate on rollout events, so a regression is seen on the next deploy, and a canary step that watches that panel before proceeding.
Picture it The few seconds in which the balancer still sends traffic to a pod that has already stopped listening, with the evidence that proves it.
The setup: a rolling deploy of a pod with server.shutdown=graceful but no preStop delay.
Make the invisible visible: two components with different views of the same pod, at three moments.
# illustrative output
moment pod state ingress routing table errors
t=0 SIGTERM pod stops accepting new still lists the pod 0 (requests in flight drain)
t=2s graceful drain running STILL lists the pod new connects -> refused ✗
t=5s drain finished or idle pod removed 0 again
The trace: the race, one hop per line.
kubelet ──► SIGTERM to pod pod: stop accepting
endpoints controller ──► remove pod from endpoints (takes a moment)
ingress ──► request arrives at t=2s
└─► routed to old pod ✗ connect refused / reset
ingress ──► learns of removal at t=5s later requests go elsewhere ✓
What you see: the ingress error log names the failure type, and that tells you the cause.
# illustrative output (nginx-style)
connect() failed (111: Connection refused) while connecting to upstream -> old pod gone: routing lag
upstream prematurely closed connection while reading response header -> keep-alive reused after server closed it
upstream timed out (110: Operation timed out) while reading response header -> slow first requests on a cold new pod
| Symptom | Root cause | Action |
|---|---|---|
| Connection refused at the ingress, only at pod termination | Pod stops accepting before routing is updated | preStop sleep, then drain |
| Reset on a reused connection | Ingress reuses a connection Tomcat closed | Ingress idle timeout below server keep-alive; retry connection-level failures on idempotent methods |
| Timeouts or 503 from the new pod's first requests | Readiness passes before warm-up | Warm up before readiness; fast cached readiness indicator |
| Errors only for the longest requests | Drain timeout shorter than the request | Raise timeout-per-shutdown-phase and the grace period together |
The fix: a delay in the pod spec, as in the code under Q117.
lifecycle:
preStop:
exec:
command: ["sh", "-c", "sleep 8"] # ✅ FIX: keep serving while routing catches up
terminationGracePeriodSeconds: 60 # must exceed preStop + drain
What you see now: the same log across the rollout.
# illustrative output
rollout window: 0 lines matching "Connection refused" or "prematurely closed"; error rate 0.00%
Land it Graceful shutdown drains what was accepted; the 0.3 percent is what the balancers sent in the seconds before they noticed, and the preStop sleep is what closes that gap.
- "You added the preStop sleep and the error rate halved but did not vanish. What next?"
Half gone means the routing lag was one cause and something else remains, and the ingress logs decide which.
If the remaining errors are resets on reused connections, the keep-alive race is still there: the ingress reuses an upstream connection that Tomcat closed during drain, and the fix is to make the ingress's upstream keep-alive timeout shorter than Tomcat's and to enable retries on connection failure for idempotent methods, which nginx-ingress does with
proxy-next-upstreamsettings.If the remaining errors are slow first requests on new pods that exceed a client timeout, the cause is on the arrival side, and the fix is warm-up before readiness, from Q142.
If they are 503s from readiness flapping on the new pod because a dependency check is slow, the readiness group needs a cached, fast indicator. Each remaining cause has a distinct signature in the ingress log, so I classify first and then fix the largest.
- "How does the keep-alive race differ between HTTP/1.1 and HTTP/2, and what if the ingress uses gRPC?"
Under HTTP/1.1 a connection carries one request at a time, so the race is a single request lost when the server closes an idle connection the client was about to reuse; the mitigation is the timeout ordering plus retries. Under HTTP/2, one connection multiplexes many streams, and a clean shutdown sends a
GOAWAYframe that tells the client to stop opening new streams while finishing the in-flight ones, so a well-behaved client migrates without errors; Tomcat sendsGOAWAYon graceful stop, but only if HTTP/2 is enabled end to end, which it rarely is behind an ingress terminating TLS. gRPC is HTTP/2 and depends on thatGOAWAYbehaviour, so a gRPC service on Boot needs the server's graceful stop configured soGOAWAYprecedes the close, and clients configured with retry policies forUNAVAILABLE. In every case the same rule holds: the side that closes first must announce it, and the client must be allowed to retry connection-level failures on idempotent calls.- "How do you make the ingress retry safely without duplicating writes?"
By restricting what is retried to failures that happened before the request reached the application.
A connection refused, a connection reset before any bytes were sent, or a timeout on connect are safe to retry for any method, because the server never saw the request; nginx's
proxy_next_upstream error timeoutwithouthttp_502covers those.A 502 or a reset after the request was sent is ambiguous for a POST, since the server may have processed it, so those are retried only for GET, HEAD, and OPTIONS, and for POST only when the request carries an idempotency key that the application honours as in Q48.
Envoy expresses this with
retry_on: connect-failure,refused-stream,resetand a separate policy for idempotent methods. The application side is the idempotency key store, which makes even the ambiguous retry harmless; with it in place the ingress can retry more aggressively, and the 0.3 percent becomes invisible to users.- "Is a canary step worth it for a service that deploys ten times a day?"
Especially then, because ten deploys a day means ten chances for a regression in shutdown or warm-up behaviour, and a canary makes each one a small blast radius instead of a fleet-wide one.
The canary is one pod of the new version receiving a few percent of traffic for five minutes while an automated check compares its error rate and p99 with the old pods, using the same
http.server.requestsmetric tagged by pod version; Argo Rollouts or Flagger implement this with the analysis as a Prometheus query and automatic rollback.The cost is five minutes per deploy, which at ten deploys is under an hour a day of pipeline time, not developer time.
What makes it cheap is that the error-rate-during-rollout panel already exists from the prevention step; the canary just automates the decision that a human would make from that panel, which at ten a day nobody actually makes.
Q119. "How do you size JVM memory for a Boot service in a 1 GB container, and what are the pieces outside the heap that people forget?"
Reveal answer
Strong answer Since JDK 10 the JVM reads the container's cgroup limit, so -XX:MaxRAMPercentage=60 to 75 sizes the heap as a fraction of the container rather than of the node; -Xmx is a hard number that ignores limit changes and should be avoided in manifests.
The reason the heap cannot be 90 percent is that the container limit must also cover:
- Metaspace: loaded classes, typically 60 to 120 megabytes for a Boot service with Hibernate.
- Code cache: JIT output, up to 240 megabytes reserved by default though far less used.
- Thread stacks: up to 1 megabyte each, so 200 Tomcat threads plus pools is 200 to 300 megabytes reserved, though only touched pages count.
- Direct memory: NIO buffers used by Tomcat, Netty, and HTTP clients, bounded by
-XX:MaxDirectMemorySize. - GC data structures: for G1 a few percent of heap.
- Other: symbol tables, JIT compiler working memory, and the native allocator's own overhead.
A working budget for 1 gigabyte: 600 megabytes heap, and the rest for everything else, with -XX:+ExitOnOutOfMemoryError so a heap OOM restarts the pod cleanly rather than limping. Set -Xss512k if thread counts are high, or use virtual threads whose stacks live in the heap.
For small containers under 512 megabytes, Serial or Parallel GC uses less overhead than G1, and the JVM already picks Serial below 2 CPUs and 2 gigabytes.
Check the numbers with jcmd VM.native_memory summary after a load test, and set the container request equal to the limit so the pod is not evicted for bursting.
# The heap is not the container's memory. These are the pieces OUTSIDE it,
# and they are what get a pod OOM-killed while heap sits at 60%:
#
# metaspace ~ 50-100 MB (classes; Spring loads a lot)
# code cache ~ 30-60 MB (JIT-compiled methods)
# thread stacks ~ 1 MB each (200 Tomcat threads = 200 MB!)
# GC structures ~ 5-10% of heap
# direct byte buffers, JNI, malloc arenas
# ❌ TRAP: -Xmx1g in a 1 GB container. Heap alone can reach the limit,
# and everything above is then over it. The kernel kills the process;
# the JVM never sees an OutOfMemoryError, which is why the logs show nothing.
# ✅ FIX: let the JVM read the cgroup limit and take a percentage.
JAVA_OPTS="-XX:MaxRAMPercentage=70.0 \
-XX:MaxMetaspaceSize=128m \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/dumps"
# Result: heap max is about 700 MB in a 1 GB pod; the rest stays free for non-heap
# Verify what the JVM actually decided, inside the container:
java -XX:MaxRAMPercentage=70 -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|MaxRAM'
# And track the whole picture, not just heap:
# jcmd 1 VM.native_memory summary (needs -XX:NativeMemoryTracking=summary)
Read the thread-stack line. A Tomcat pool of 200 threads reserves roughly 200 MB of stack outside the heap — which on a 1 GB pod is a fifth of the budget, and is why reducing the thread pool is sometimes the fix for an OOM kill that looks like a heap problem.
Picture it The 1 GB container drawn as a budget, so you can see the heap is only part of what the kernel counts.
The setup: the sizing flags in the code above, applied to a 1 GB pod with 200 Tomcat threads.
Make the invisible visible: where the memory goes at peak, with illustrative numbers.
# illustrative budget, 1024 MB container, MaxRAMPercentage=60 -> heap max ~614 MB
heap (at its maximum) 614 MB
metaspace 90 MB
code cache (used) 60 MB
thread stacks, 200 touched 120 MB
direct buffers 40 MB
GC structures 50 MB
malloc and other 40 MB
-------
1014 MB ✓ under 1024, tight
The trace: the same pod with different heap settings; non-heap is taken as 300 MB for all rows.
| Setting | Heap max | Total at peak | Outcome |
|---|---|---|---|
| -Xmx1g | 1,024 MB | about 1,324 MB | Kernel OOM kill, exit code 137, no OutOfMemoryError in the log |
| MaxRAMPercentage=90 | about 921 MB | about 1,221 MB | Kernel OOM kill |
| MaxRAMPercentage=70 | about 717 MB | about 1,017 MB | At the edge |
| MaxRAMPercentage=60 | about 614 MB | about 914 MB | Fits |
What you see: the JVM's decision, and the fix when threads are the problem.
# illustrative output
$ java -XX:MaxRAMPercentage=60 -XX:+PrintFlagsFinal -version | grep MaxHeapSize
size_t MaxHeapSize = 643825664 (about 614 MB in a 1 GB container)
# thread stacks: server.tomcat.threads.max=200 reserves about 200 MB; 100 threads halves that
Land it Heap is a percentage of the container, and the other 25 to 40 percent is real memory the JVM will use whether or not you budgeted it.
- "How would you verify the 600-megabyte heap budget is right rather than just plausible?"
With a load test and two readings. During steady load at the expected peak,
jcmd <pid> VM.native_memory summaryprints committed memory by category: heap, class, thread, code, GC, internal, symbol, and so on; the sum is what the JVM believes it uses.The container's working set from cAdvisor,
container_memory_working_set_bytes, is what the kernel will judge against the limit. The difference between them is allocator overhead and anything outside NMT's view.If working set at peak is under 85 percent of the limit with the heap at its maximum, the budget holds; if not, the heap fraction comes down.
I also force a full GC and read
jvm.memory.usedfor the old generation afterwards, which is the live data set; the heap should be two to three times that for G1 to run efficiently.Those numbers then go into the manifest as comments so the next person knows where they came from.
- "What changes with virtual threads, and what changes with ZGC?"
Virtual threads move stacks from native memory into the heap: each virtual thread's stack is a heap object that grows and shrinks, so 10,000 concurrent requests cost a few hundred megabytes of heap rather than 10 gigabytes of reserved native stack, and the
Threadline in NMT stops growing with concurrency; the heap budget therefore needs headroom for that, and-Xssbecomes nearly irrelevant.The carrier threads, one per core, still have native stacks.
ZGC, generational since Java 21 and the default form of ZGC as of Java 23, keeps pauses under a millisecond but needs more heap headroom than G1, typically 20 to 30 percent more, because it collects concurrently while allocation continues, and it uses extra memory for its forwarding tables and colored pointers.
For a 1-gigabyte container I would stay on G1 or even Serial; ZGC pays off on large heaps where G1's pauses grow, which is not the small-container case.
- "Why request equal to limit? It wastes cluster capacity."
It wastes some, and it buys predictability, which for memory is the right trade.
Memory is not compressible: if a node is oversubscribed on CPU, pods slow down; if it is oversubscribed on memory, the kernel kills pods, and it kills the ones that burst above their request first.
A JVM whose heap grows to the container limit by design will always run near its limit, so a request below the limit is a promise the pod will break.
Setting request equal to limit gives the pod the Guaranteed QoS class, which makes it the last to be evicted under node pressure, and makes the scheduler place it only where the memory really exists.
For CPU the calculus is different, and there I set a request with no limit or a generous one, because CPU throttling during JIT warm-up is a real cost and bursting is harmless.
The cluster capacity saving from memory oversubscription is small compared to the cost of an unpredictable OOM kill.
- "How does the Paketo buildpack's memory calculator do this, and would you trust it?"
It computes the heap as what is left after budgeting the other regions from counts it can observe: it estimates metaspace from the number of classes in the jar, roughly 5,800 bytes per class, reserves thread stacks as thread count times stack size with a default of 250 threads at 1 megabyte, code cache at 240 megabytes, direct memory at 10 megabytes, and a fixed head room, then sets
-Xmxto the remainder of the container limit and writes the flags intoJAVA_TOOL_OPTIONSat container start.It is conservative and sound, and I trust it as a starting point; where it is wrong is thread count, since a service with a 200-thread Tomcat pool plus executors exceeds 250, and direct memory, since a Netty-based client uses far more than 10 megabytes.
Both are overridable with
BPL_JVM_THREAD_COUNTandBPL_JVM_HEAD_ROOM, and I set them after the same load test.
Q120 · Design. "We run 30 Boot services. Leadership wants 'faster startup and lower cloud cost'. Design the decision between GraalVM native images and JVM with the AOT cache, and the rollout."
Reveal answer
Strong answer Assumptions: most services are long-running HTTP and Kafka workloads, a few are event-driven functions that scale to zero, Java 25 is available, and build time and debuggability matter to the teams.
Analysis: native image gives about 50-millisecond startup and roughly a third of the memory at rest, at the cost of several-minute builds, a closed-world model that breaks runtime reflection and some libraries, lower peak throughput than a warmed JIT, and a different debugging and profiling story.
JDK 24's AOT cache (JEP 483, extended in 25) gives 30 to 50 percent faster startup on the normal JVM with one training run, no code changes, full compatibility, and full JIT throughput; Boot 3.3 and later support CDS and AOT-cache archives directly with the layered jar tooling.
Decision rule: native for the scale-to-zero functions and any service where instances are frequently created, such as burst autoscaling on tiny pods, because there the startup and memory dominate cost; JVM with the AOT cache for the long-running services, because their cost is steady-state throughput, which native does not improve.
Rollout: first, measure, since "faster startup" often turns out to be a 90-second startup from Q32 that has nothing to do with the JVM. Second, apply the AOT cache to all 30 through the platform Dockerfile, which is low risk and immediate.
Third, pilot native on one function with the native test profile in CI, budgeting a sprint for hints and library issues. Fourth, right-size memory requests after both, since that is where the cloud saving actually appears.
Trade-offs and what I would not do: converting all 30 to native for a startup metric nobody experiences, because the build and debugging tax is paid by every developer every day.
Picture it Three ways to run the same service side by side, so the decision becomes a table of numbers instead of a slogan.
The setup: one service built three ways.
# 1. plain JVM
java -jar app.jar
# 2. JVM with the AOT cache (Java 25): one training run, then use the archive
java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app.jar
java -XX:AOTCache=app.aot -jar app.jar
# 3. native image
./mvnw -Pnative native:compile
Make the invisible visible: what each run reports, with illustrative figures for a typical service.
# illustrative output
variant startup log line RSS at rest build time peak throughput
plain JVM Started App in 6.1 seconds 520 MB 1 min 100% (reference)
JVM + AOT Started App in 3.5 seconds 520 MB 1 min + 15 s 100%
native Started App in 0.06 seconds 150 MB 6 min lower than warmed JIT
| Service type | What dominates cost | Choice |
|---|---|---|
| Scale-to-zero function, burst autoscaling on tiny pods | Startup and memory per instance | Native |
| Long-running HTTP service | Steady-state throughput | JVM with AOT cache |
| Steady Kafka consumer | Records per second per core | JVM with AOT cache |
| Heavy runtime reflection, Java agents, no appetite for 5-minute builds | Build and debug tax | JVM |
The trace: the rollout order, each step with what you measure.
1. measure startup log line and pod memory vs actual need (is "slow" really 90 s of app code?)
2. AOT cache platform Dockerfile, all 30 services -> startup log line drops
3. native pilot one scale-to-zero function, native test profile in CI
4. right-size memory requests after both -> the actual cloud saving
Land it Native pays off where instances are born often; the AOT cache is the free win for everything else, and the cloud saving comes from right-sizing after either.
- "What exactly does the AOT cache store, and how is it produced in a build pipeline?"
On Java 24 with JEP 483, the AOT cache holds the loaded and linked classes from a training run, so startup skips parsing, verifying, and linking them; Java 25 with JEP 515 adds method profiles from the training run, so the JIT starts compiling the hot methods immediately rather than waiting to observe them, and JEP 514 simplifies it to one flag.
The production is a training run in the container build:
java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app.jar, where the Spring property makes the application start fully, refresh the context, and exit without serving, so the run exercises the real startup path; then the runtime entrypoint adds-XX:AOTCache=app.aot.The archive is only valid for the same JDK build and the same classpath, so it must be created in the final image stage with the exact runtime JDK, and it adds tens of megabytes to the image. Boot's
spring-boot:process-aotis a separate, complementary step that pre-computes bean definitions.- "Which of the 30 services would you refuse to make native, and why?"
Any service with heavy reflection or runtime bytecode generation that is not covered by hints: ones using Groovy scripting, dynamic JPQL through Criteria with unusual mappings, JSON schema validators that generate classes, older libraries without GraalVM reachability metadata, or extensive SpEL. Any service where peak throughput is the cost driver, as in Q121.
Any service whose team lacks the appetite for 5-minute native builds and a different profiler, because the build and debugging tax is paid daily and is the reason native migrations get reverted.
And any service with JVM-agent dependencies, such as an APM agent that instruments bytecode at load time, since native images do not support Java agents; the observability story must be Micrometer-based first.
The decision for each one is a quick spike: run
native-imagewith Boot'snativeprofile, count the hint failures, and if they exceed a handful, that service stays on the JVM.- "Leadership wants a number: how much cheaper will it be?"
I would give them a measured range rather than a promise, and the measurement is cheap.
For the long-running services the saving is memory: a JVM service that needs 1 gigabyte often runs at 512 megabytes with the same throughput once the heap is sized from a load test rather than by habit, and CDS or the AOT cache do not change that; the saving comes from right-sizing, typically 30 to 50 percent of memory per pod, which is the cloud bill line that matters.
For the scale-to-zero functions, native reduces both the memory floor and the cold-start latency, so instances can be scaled away more aggressively; there the saving is instance-hours, often 60 to 80 percent for bursty workloads.
So the number is: measure current pod memory versus actual need on three representative services for a week, and multiply. That produces a defensible figure in two weeks, before committing a quarter to a runtime change.
- "What would you cut under time pressure?"
The native pilot. It has the longest lead time, the most unknowns, and the smallest population of services that benefit.
What I would keep is the two-step plan that pays off across all 30: the AOT cache in the platform Dockerfile, which is a one-time change to the shared build, and the right-sizing pass, which is a load test per service and a manifest change.
Those two ship in a month with no code changes and deliver most of the cost saving and a visible startup improvement. Then the native pilot runs when there is slack, on the one function that scales to zero, where the benefit is unambiguous.
The mistake to avoid under time pressure is the opposite: starting native on a flagship service because it is the most visible, and spending the quarter on hint files while the cheap wins wait.
Q121 · Scenario. "A service converted to a native image starts in 60 ms and uses a quarter of the memory, but its p50 latency under sustained load is 40 percent higher than the JVM version. Explain and decide."
Reveal answer
Strong answer In diagnosis order:
- Symptom: excellent startup and footprint, worse steady-state latency. That is the expected profile of ahead-of-time compilation versus a warmed just-in-time compiler.
- Evidence: profile both under load; the native binary shows more time in generic code paths where the JVM would have inlined and speculated, and its garbage collector is the simpler Serial GC by default in the community edition, so allocation-heavy code pays more.
- Cause: the JIT observes the running program and compiles the hot paths with profile-guided inlining, escape analysis, and speculative optimisations; native image compiles everything ahead of time with static assumptions. GraalVM's Oracle edition can use profile-guided optimisation for native images, and G1 is available there, which narrows the gap, but the community edition does not.
- Decision: if the service is a long-running one with steady traffic, the 40 percent latency cost is a real cost paid on every request, while the 60-millisecond startup is paid once a day; go back to the JVM with the AOT cache. If it scales to zero or is deployed in large numbers of tiny instances, the memory saving multiplies across instances and the latency difference may be inside the budget; stay native and consider PGO. Also check that the comparison is fair: the JVM version measured after warm-up, the native one with the same GC settings, and the same container CPU.
- Prevention: define the performance target as steady-state p99 under load before choosing a runtime, so startup numbers do not decide a throughput question.
Picture it Latency over time for the same service on the JVM and as a native image, showing why startup numbers cannot decide a throughput question.
The setup: same container, same CPU and memory limits, same load of 600 requests per second for 15 minutes, once per variant.
Make the invisible visible: p50 at three moments.
# illustrative output
minute JVM p50 native p50 what is happening
0-1 95 ms 28 ms JVM still interpreting and compiling; native already at speed
5 22 ms 31 ms JVM hot paths compiled
15 20 ms 28 ms native about 40% slower; JVM profile-guided inlining has paid off
The trace: where the extra time goes per request.
JVM hot call site seen 100,000 times ──► inlined, speculated, escape-analysed ✓ fast path
native same call site, compiled ahead of time with static assumptions ✗ generic path
native community edition GC is Serial by default ✗ allocation-heavy code pays
| Situation | Root cause | Action |
|---|---|---|
| Steady traffic, cost per request | Peak throughput matters, startup paid once a day | Back to JVM with AOT cache |
| Scale to zero or many tiny instances | Memory and cold start multiply across instances | Stay native, consider PGO |
| Gap looks too large | JVM measured before warm-up, or GC settings differ | Re-run the fair comparison before deciding |
Land it Native trades peak throughput for startup and footprint, and the right choice depends on whether your cost is per instance-hour or per request.
- "How would you make the comparison fair before deciding anything?"
Same container, same CPU limit, same memory limit, same load profile, and both measured after warm-up.
The JVM version needs at least five minutes of representative traffic before measurement, because until then it is interpreting and the comparison flatters native; the native version needs its GC configured comparably, since the community edition defaults to Serial GC and the JVM defaults to G1 on a 2-CPU container, so either give the JVM Serial too or give native the memory headroom Serial wants.
I measure p50, p99, and throughput at a fixed concurrency with a tool like k6 for 15 minutes, twice, and I look at CPU utilisation at the same request rate, because native often uses more CPU per request, which matters for the cost argument.
A common finding is that the 40 percent gap is really 15 percent after warm-up and GC alignment, which changes the decision.
- "What does profile-guided optimisation do for native, and what does it cost?"
PGO gives the ahead-of-time compiler the same kind of information the JIT gathers at runtime: which branches are taken, which call sites are monomorphic, which methods are hot.
You build an instrumented binary, run a representative workload against it to produce a profile file, and build again with
--pgo=profile.iprof; the resulting binary inlines and lays out code according to the profile and typically recovers a large part of the JIT gap.The cost is a second build of several minutes, a workload harness that must be representative or the optimisation is aimed at the wrong code, and, as of Aug 2026, availability only in Oracle GraalVM under its licence, not in the community edition.
GraalVM community also lacks G1 for native, so allocation-heavy services pay on the collector as well. If both are acceptable, PGO plus G1 makes native competitive; if not, the JVM with the AOT cache is the honest choice.
- "The service is a Kafka consumer, not an HTTP API. Does that change the decision?"
It sharpens it. A consumer's cost is throughput per core: how many records per second it processes, and how much lag it accumulates during a burst. Startup time matters only during rebalances and deploys, and memory matters only if consumers are numerous.
Native's 60-millisecond startup buys almost nothing, since a rebalance takes seconds anyway, and its lower peak throughput means more lag under load or more instances. So for a steady consumer, the JVM wins clearly, and the AOT cache reduces the deploy-time lag spike.
The exception is a consumer that scales to zero on an empty topic, such as a KEDA-scaled worker for infrequent events, where the memory floor and cold-start decide the cost and native wins.
The general rule from Q120 holds: native where instances are born often, JVM where they live long, and a consumer is usually the second.
- "If you stay native, what do you give up operationally?"
Several things people discover late.
No Java agents, so any APM or security agent that instruments bytecode is out; observability must be library-based through Micrometer and OpenTelemetry's SDK. No
jcmd, no heap dumps in the usual format, no JFR by default, so a memory investigation uses different tools, though JFR support in native has improved.Reflection, proxies, resources, and serialisation need reachability metadata, so a new library or a new Jackson feature can fail at runtime with a missing-hint error that only a native test run catches, which means CI must build and test the native image on every change, not only the JVM tests.
Builds take minutes and gigabytes of memory. Debugging is with native debuggers rather than a JVM debugger. And a JDK update means rebuilding rather than swapping a base image. For a small number of functions that is fine; for 30 services it is a platform commitment.
Q122 · Design. "Design the container build for a Boot service: small image, fast rebuilds, non-root, reproducible, with startup optimisation. Sketch the Dockerfile stages."
Reveal answer
Strong answer Requirements: a rebuild after a code change should push kilobytes, not the whole 80-megabyte jar; the runtime image should carry no build tools; the process should not run as root; the same inputs should produce the same image; and startup should use the JDK's AOT cache.
Design: a multi-stage build.
Stage one, build, uses a pinned JDK image, copies the wrapper and the Maven or Gradle files first and resolves dependencies with ./mvnw dependency:go-offline, so the dependency download is cached as a layer, then copies the source and runs ./mvnw -q package -DskipTests.
Stage two, extract, runs java -Djarmode=tools -jar target/app.jar extract --layers --destination extracted, producing the dependencies, spring-boot-loader, snapshot-dependencies, and application directories.
Stage three, runtime, uses a pinned, slim JRE image such as a distroless or Temurin JRE, creates a non-root user, and copies the four layer directories in that order with separate COPY instructions, so only the application layer changes between builds.
Then a training run: java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app.jar on Java 25 (or -XX:ArchiveClassesAtExit for CDS on 21) produces the archive as one more layer, and the ENTRYPOINT runs java -XX:AOTCache=app.aot -XX:MaxRAMPercentage=70 -XX:+ExitOnOutOfMemoryError org.springframework.boot.loader.launch.JarLauncher.
Reproducibility: pin base images by digest, set project.build.outputTimestamp so the jar's entries have fixed timestamps, and let Boot's build plugin produce a build-info file.
Alternatively, the Paketo buildpacks via ./mvnw spring-boot:build-image do all of this by convention, including the memory calculator, which is the right default for a team that does not want to own a Dockerfile.
What I would not do: a single-stage image with the JDK and the source, or latest tags anywhere. The Docker mechanics behind the layers are Chapter E9.
Picture it The image drawn as layers with sizes, so you can see what a code change re-pushes and what it leaves cached.
The setup: the three stages as a Dockerfile.
FROM eclipse-temurin:25-jdk@sha256:<pinned digest> AS build
WORKDIR /src
COPY .mvn .mvn
COPY mvnw pom.xml ./
RUN ./mvnw -q dependency:go-offline # cached until pom.xml changes
COPY src src
RUN ./mvnw -q package -DskipTests
FROM eclipse-temurin:25-jdk@sha256:<pinned digest> AS extract
WORKDIR /x
COPY --from=build /src/target/app.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination extracted
FROM eclipse-temurin:25-jre@sha256:<pinned digest>
RUN useradd --system --uid 10001 app # non-root
WORKDIR /app
COPY --from=extract /x/extracted/dependencies/ ./
COPY --from=extract /x/extracted/spring-boot-loader/ ./
COPY --from=extract /x/extracted/snapshot-dependencies/ ./
COPY --from=extract /x/extracted/application/ ./
RUN java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app.jar
USER 10001
ENTRYPOINT ["java", "-XX:AOTCache=app.aot", "-XX:MaxRAMPercentage=70", "-XX:+ExitOnOutOfMemoryError", "-jar", "app.jar"]
Make the invisible visible: the layers the runtime image ends up with, ordered from least to most often changed.
# illustrative output
LAYER SIZE changes when
dependencies 76 MB a dependency upgrade (about monthly)
spring-boot-loader 0.3 MB a Boot upgrade
snapshot-dependencies 0 B snapshot libraries change
application 2 MB every commit
app.aot 40 MB every commit (training run repeats after the application layer)
What you see: the push after a one-line code change, as a single fat jar versus layers.
# illustrative output
fat jar layer : 1 layer pushed 80 MB ✗ every build moves everything
extracted layers: dependencies Layer already exists ✓
spring-boot-loader Layer already exists ✓
snapshot-dependencies Layer already exists ✓
application pushed (2 MB), app.aot pushed (the archive layer is rebuilt each time)
| Need | Choice | Reason |
|---|---|---|
| Fast rebuild and small pushes | Extracted layers in change order | Only the last layers change |
| No build tools or root in production | Multi-stage, slim JRE, USER 10001 | Smaller attack surface |
| Reproducible | Digest-pinned bases, outputTimestamp | Same inputs, same bytes |
| No Dockerfile ownership | spring-boot:build-image (Paketo) | Does all of this by convention |
Land it Build, extract layers, copy them in change order onto a slim non-root JRE, and add the AOT archive as the last layer, or let buildpacks do exactly that.
- "Why extract layers rather than just copying the fat jar?"
Because Docker caches and pushes by layer, and a fat jar is one layer that changes on every build.
The typical Boot jar is 80 megabytes, of which 78 are dependencies that change once a month and 2 are application classes that change every commit; copying the jar means every push and every pull moves 80 megabytes, and every node pulls the whole thing on deploy.
Extracting with
java -Djarmode=tools -jar app.jar extract --layersand copying the four directories in order,dependencies,spring-boot-loader,snapshot-dependencies, thenapplication, means the first three layers are cache hits and only the last one, a couple of megabytes, changes.Registry storage, pull time on scale-out, and CI push time all shrink. Startup also benefits slightly, since the extracted form runs classes from directories without the nested-jar loader. Boot 3.3 and later use the
toolsjar mode; before that it waslayertools.- "How does the AOT cache interact with the layers, and what invalidates it?"
The cache is bound to the exact classpath and JDK it was trained with, so it must be created after the layers are in place in the runtime image, and it becomes one more layer on top of them.
Any change to the application layer invalidates it, which is every build, so the training run is part of every build and costs ten to twenty seconds; that is acceptable and it is what makes the cache accurate.
A JDK patch update invalidates it too, and the JVM detects the mismatch and falls back to normal startup with a warning rather than failing, so a stale cache is a performance regression, not an outage; I make that visible with a startup log check in the smoke test that greps for the AOT cache being used.
For the CDS variant on Java 21, the same rules hold with
-XX:SharedArchiveFile, and Boot'sextract --layersoutput has a stable layout that keeps the archive valid across builds where dependencies did not change.- "What about the JDK image itself: full JDK, JRE, or jlink?"
A JRE image from a vendor such as Temurin is the pragmatic default: about 100 megabytes smaller than the JDK, still including the tools the runtime needs.
A distroless Java image is smaller still and has no shell, which is a security gain and a debugging loss; with Kubernetes ephemeral debug containers the loss is manageable.
jlinkcan build a custom runtime with only the modules the application uses, often 50 to 60 megabytes total, but a Boot application on the classpath does not declare modules, so you have to discover the needed ones withjdepsand you can miss one that a library loads reflectively, which fails at runtime; I use it only when image size is a measured problem, such as a scale-to-zero function.Whichever base is used, it is pinned by digest, rebuilt weekly for security patches, and scanned; the choice of base is a security policy as much as a size decision.
- "How do you make the build reproducible and verify that it is?"
Reproducible means the same inputs produce a byte-identical artifact. For the jar, Maven's
project.build.outputTimestampor Gradle'spreserveFileTimestamps=falseandreproducibleFileOrder=truefix entry timestamps and order, and Boot's plugin honours them.Dependencies are pinned through the BOM and a lockfile or dependency verification, and the wrapper pins the build tool. Base images are pinned by digest, not tag. The build runs with a fixed locale and timezone, since some plugins embed them.
Verification is a CI job that builds twice from the same commit in separate runners and compares SHA-256 hashes of the jar; for the image, tools like
diffocicompare layers.The value beyond tidiness is supply-chain: a reproducible build lets an auditor rebuild and confirm the artifact, and a SBOM from the CycloneDX plugin attached to the image lists exactly what is in it.
Q123 · Scenario. "Pods are OOM-killed by Kubernetes while the JVM reports heap usage at 60 percent and never throws OutOfMemoryError. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the kernel's OOM killer, not the JVM, ended the process. The JVM only throws when the heap is exhausted; the kernel kills when the container's total resident memory exceeds the limit. The heap was fine; something else was not.
- Evidence:
kubectl describe podshowsOOMKilledwith exit code 137; the container's working-set metric at the time of death versus the JVM's heap max; Native Memory Tracking output from a surviving pod; the thread count and direct memory metrics. - Likely causes, ranked:
- Heap fraction too high:
MaxRAMPercentageset too high, for example 90, leaving no room for metaspace, threads, and buffers. - Stale -Xmx: a hard
-Xmxlarger than the container permits after a limit was lowered. - Thread leak: each stack adds to native memory.
- Direct buffers: from an HTTP client, Kafka client, or Netty.
- Metaspace growth: from generated classes.
- glibc arenas: fragmentation on a service with many threads.
- Another process: in the same container, such as a sidecar-in-container or a shell tool, sharing the limit.
- Heap fraction too high:
- Fix: lower the heap fraction to leave 30 to 40 percent for non-heap, cap direct memory and metaspace explicitly so they fail visibly, fix the leak the metrics point at, set
MALLOC_ARENA_MAX=2, and set the memory request equal to the limit so the scheduler places the pod where the memory actually exists. - Prevention: dashboards that show container working set alongside heap, with an alert when the gap between them grows, and a load test that reports the peak working set, not just the heap.
Picture it The same pod seen by the JVM and by the kernel at three moments, where only the kernel's number reaches the limit.
The setup: a 1 GB pod with MaxRAMPercentage=90, a Netty-based client and 200 request threads.
Make the invisible visible: two views of one container.
# illustrative output
moment JVM heap used heap max non-heap (NMT) working set (kernel) result
t0 380 MB 921 MB 210 MB 590 MB fine
t1 620 MB 921 MB 280 MB 900 MB JVM sees 60% heap
t2 640 MB 921 MB 390 MB 1,030 MB kernel kills; no OutOfMemoryError
The trace: who decides.
JVM heap check ──► used 640 MB < max 921 MB ✓ no OutOfMemoryError
kernel cgroup ──► resident 1,030 MB > limit 1,024 MB ✗ SIGKILL to the container process
What you see: the pod status, with no application stack trace.
Last State: Terminated
Reason: OOMKilled
Exit Code: 137
| Symptom | Root cause | Action |
|---|---|---|
| 137 with heap below max | MaxRAMPercentage too high | Lower to 60 to 70 |
| Thread line in NMT grows | Thread leak | Fix creator; check name prefixes in a thread dump |
| Direct buffers grow | Netty, Kafka or HTTP client buffers | -XX:MaxDirectMemorySize so it fails visibly |
| NMT total flat, working set grows | glibc arenas | MALLOC_ARENA_MAX=2 |
The fix: a smaller heap share and explicit caps.
# ✅ FIX: leave 30-40% for non-heap and make the real consumers fail visibly
JAVA_OPTS="-XX:MaxRAMPercentage=65 -XX:MaxDirectMemorySize=128m -XX:MaxMetaspaceSize=128m"
MALLOC_ARENA_MAX=2
What you see now: the same table once the heap is capped lower.
# illustrative output
moment JVM heap used heap max non-heap (NMT) working set result
t2 640 MB 665 MB 330 MB ~970 MB stays under 1,024 MB; GC runs a little more often
Land it Exit code 137 with a healthy heap means native memory, and the cure is a smaller heap fraction plus caps that make the real consumer visible.
- "How do you get native memory numbers from a pod that is about to be killed?"
From a survivor with the same behaviour, since the killed one is gone.
I pick a pod of the same deployment that has been running the longest and run
kubectl exec <pod> -- jcmd 1 VM.native_memory summary, which requires NMT enabled at startup with-XX:NativeMemoryTracking=summary; if it was not enabled, I enable it in the manifest and wait for the next generation, which is why I keep it on permanently in one canary pod.The output lists committed memory per category, and I compare against the container's working set from
kubectl top podor the cAdvisor metric. Alongside that,jvm.buffer.memory.usedtaggeddirectandmappedfrom Micrometer,jvm.threads.live, andjvm.memory.used{area="nonheap"}over the pod's lifetime show which region grew.If the kill happens too fast to catch, a
preStophook that dumps NMT to a mounted volume captures the last state.NMT from a surviving podruns offline# illustrative output $ kubectl exec orders-6f7-abc -- jcmd 1 VM.native_memory summary | grep committed - Java Heap (reserved=614400KB, committed=614400KB) - Thread (reserved=410000KB, committed=96000KB) - Class (reserved=1100000KB, committed=84000KB) - Internal (reserved=310000KB, committed=310000KB) <- direct buffers and similar: the grower here $ kubectl top pod orders-6f7-abc MEMORY 1010Mi <- working set near the 1 GiB limit- "The numbers show direct buffers at 300 megabytes. Where does that come from and how do you cap it?"
Direct buffers are off-heap memory allocated through
ByteBuffer.allocateDirect, used by NIO for sockets and files, Netty for its pooled allocator, the Kafka client for its network buffers, and the JDK's ownHttpClient.A Netty-based client such as
WebClientor Lettuce pools direct memory per event-loop thread and sizes arenas in chunks of 16 megabytes, which grows with concurrency and rarely shrinks.The cap is
-XX:MaxDirectMemorySize=256m, which makes an allocation past the limit throwOutOfMemoryError: Direct buffer memoryvisibly instead of the kernel killing the pod; the default is equal to the maximum heap, which for a 600-megabyte heap in a 1-gigabyte container is a guaranteed OOM kill if ever reached.Netty's own limit,
-Dio.netty.maxDirectMemory, and its allocator's arena count,io.netty.allocator.numDirectArenas, tune the pool. The metric to watch isjvm.buffer.memory.used{id="direct"}.- "Why would lowering MaxRAMPercentage fix an OOM kill? That gives the application less memory."
It gives the heap less and the rest more, which is the point, because the kill is triggered by the total.
With
MaxRAMPercentage=90in a 1-gigabyte container, the heap is allowed to grow to 900 megabytes, and G1 will grow it under load because it is allowed to; add 100 megabytes of metaspace, 100 of thread stacks, and 50 of direct buffers, and the working set is 1,150, past the limit, so the kernel kills.With 65 percent, the heap tops out at 650 megabytes, G1 collects more often to stay within it, which costs a little CPU, and the total stays near 900.
The application does not need the extra heap unless its live data set is close to it, which the post-full-GC old-generation size tells you; if the live set really needs 800 megabytes, the fix is a bigger container, not a bigger percentage.
The percentage is a division of the container between the heap and everything else, and 90 percent leaves nothing for everything else.
- "Could a sidecar cause this, and how would you tell?"
A sidecar in its own container has its own limit and cannot cause the application container's OOM kill, but it can cause the pod to be evicted under node pressure if the pod's total requests are below its usage.
What can cause the application container's kill is a process inside the same container: a log shipper started by the entrypoint script, a shell someone left running, or a JVM tool like
jcmdthat itself starts a JVM and allocates a few hundred megabytes while dumping the heap.kubectl exec <pod> -- ps auxshows every process in the container with its resident memory, and the cgroup'smemory.statshows the container total. The event inkubectl describe podnames the container that was killed.The prevention is one process per container, which also makes the JVM PID 1 and lets it receive SIGTERM directly for graceful shutdown, rather than through a shell that swallows it.
This group tests whether your service can tell you what is wrong, and whether one slow dependency can take it down.
Q124. "How does Micrometer Observation unify metrics and tracing in Boot 3 and 4, how does context propagate across threads and services, and what decides your sampling rate?"
Reveal answer
Strong answer An Observation is one unit of work with a name, low-cardinality tags, and a start and stop.
The ObservationRegistry has handlers: the metrics handler turns each observation into a Micrometer timer and counter, and the tracing handler turns it into a span through Micrometer Tracing, which bridges to OpenTelemetry (or Brave) under the hood.
Boot instruments Spring MVC and WebFlux servers, RestClient, WebClient, JDBC through the datasource-micrometer library, Kafka, scheduled tasks, and @Observed methods, all through observations, so one instrumentation point feeds both systems consistently.
Propagation within a process uses the ObservationThreadLocalAccessor and the context-propagation library: Boot's task executors and the Reactor context carry the current observation across thread hops when you use the framework's executors or ContextSnapshot.
Across services, the tracing handler injects the W3C traceparent and tracestate headers on outbound HTTP and Kafka headers, and extracts them on the way in, so the trace id is the same across the call graph.
The logging MDC gets traceId and spanId automatically, which is what makes a log line clickable into its trace.
Sampling: management.tracing.sampling.probability defaults to 0.1; the honest rule is that metrics are complete and cheap, traces are sampled and expensive, and the rate is set by the trace backend's cost against how rare the problems you need to see are.
Head-based sampling at 10 percent misses rare errors, so a collector-side tail-sampling policy that keeps all traces with errors or high latency and a fraction of the rest is what mature setups run.
Tag discipline: observation tags must be low cardinality, meaning no user ids or raw URLs, and high-cardinality detail goes on the span as an event, not on the metric.
Picture it One observation fanning out into a timer, a span, a header and a log field, and the point where a thread hop loses the link.
The setup: a manual observation with one bounded tag and one high-cardinality value.
Observation.createNotStarted("checkout.price", registry)
.lowCardinalityKeyValue("currency", "EUR") // becomes a metric tag and a span tag
.highCardinalityKeyValue("order.id", orderId) // span only; never a metric tag
.observe(() -> price(order));
Make the invisible visible: what that single call produced in each system.
# illustrative output
metrics checkout_price_seconds_count{currency="EUR",error="none"} 1
tracing span "checkout.price" traceId=4bf92f3577b34da6a3ce929d0e0e4736 order.id=A-1001
logging INFO c.e.Pricing : priced order traceId=4bf92f3577b34da6a3ce929d0e0e4736 spanId=00f067aa0ba902b7
http out traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
The trace: propagation across a thread hop and across a service call.
HTTP thread ──► observation held in a ThreadLocal
└─► plain executor.submit(...) ✗ worker thread has no current observation: orphan span
└─► applicationTaskExecutor (context-propagating) ✓ same trace, correct parent
└─► RestClient call ──► traceparent header ──► downstream extracts it ✓ same trace id
| Need | Approach | Cost |
|---|---|---|
| Statistics about typical latency | Head sampling at 10 percent | Nothing at the collector; misses rare errors |
| See every error and slow request | Tail sampling at the collector | Every span exported, stateful collector tier |
| Cheap middle | Head sampling plus always-on rule for error header or debug flag | Small |
Land it One observation produces a timer and a span, the trace id rides the headers and the MDC, and sampling is a cost decision that belongs at the collector.
- "A trace stops at the point where a request hands work to an executor. Why, and what is the fix?"
The observation is held in a
ThreadLocalthroughObservationThreadLocalAccessor, so a task submitted to a plain executor starts on a thread with no current observation, and spans created there have no parent; the trace shows the HTTP span ending and an orphan span, or nothing.Boot's auto-configured
applicationTaskExecutoris context-propagating when the context-propagation library is present, and since Boot 3.2 theTaskExecutorBuildercan apply aTaskDecorator.For a custom executor, wrap it:
ContextExecutorService.wrap(executor, ContextSnapshotFactory.builder().build()::captureAll), or configureContextPropagatingTaskDecoratoras the decorator bean, which captures the observation and MDC on submit and restores them on the worker.For
CompletableFuture.supplyAsyncwith the common pool, there is no hook, so the fix is to pass the wrapped executor explicitly. Virtual threads created through Boot's executors get the same decorator; rawThread.ofVirtual().startdoes not.- "How would you verify propagation across services in a real deployment?"
End to end with a single request I can find.
I send a request to the edge with a known
traceparentheader, for example00-<32 hex>-<16 hex>-01, wait a few seconds for export, and query the trace backend for that trace id; the trace should show the edge span, the service span, the outbound client span, the downstream service's span, the JDBC spans, and any Kafka produce and consume spans, all with the same trace id and correct parent links.Then I check a log line from each service for that id in its
traceIdfield, which proves the MDC bridge.Gaps show exactly where propagation breaks: a missing downstream span means the downstream does not extract, a missing client span means the client is not the auto-configured
RestClient.Builder, and a consumer span with a new trace id means Kafka headers were not propagated, which for Spring Kafka needs the observation-enabled container factory,spring.kafka.template.observation-enabled=trueandspring.kafka.listener.observation-enabled=true.- "What does tail sampling cost, and when is head sampling good enough?"
Tail sampling means every service exports every span to the collector, and the collector decides per trace after it has seen all its spans, so the export bandwidth and the collector's memory scale with full traffic: at 5,000 requests per second with 20 spans each, that is 100,000 spans per second flowing to a collector that buffers each trace for a decision window of about 10 seconds, which needs a stateful collector tier with traces routed by trace id so one collector sees the whole trace.
Head sampling at 10 percent decides at the first span, costs nothing at the collector, and is good enough when the questions are statistical, such as "where is the typical latency", and when errors are frequent enough that 10 percent still catches them.
It is not good enough when a rare failure needs to be seen, or when a long-tail latency outlier is the thing under investigation.
The cheap middle is head sampling at 10 percent plus an always-on rule for requests with an error header or a debug flag.
- "What is the overhead of observations, and where does it bite?"
Per observation, a timer update and a span object with a few tags: a microsecond or two of CPU and a few hundred bytes, invisible for HTTP requests.
It bites in high-frequency, low-value places: an observation per JDBC statement in a batch of 50,000 inserts creates 50,000 spans and doubles the batch time; an
@Observedon a method called a million times a second; a Kafka consumer at 100,000 records per second with a span per record.The controls are the
ObservationPredicatebean, which disables observations by name, for instance excludingjdbc.queryfor the batch datasource, and the sampling rate for spans, which reduces export but not creation. Metrics cardinality is the other cost, covered in Q125.The rule I apply is one observation per unit of work a human would ask about, and batch internals are not that; they get one span for the whole batch with a count attribute.
Q125 · Scenario. "Prometheus memory doubled and the metrics endpoint takes 4 seconds to scrape. http.server.requests has 300,000 series for one service. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: cardinality explosion on the request metric. Each unique combination of tag values is a time series; 300,000 means some tag has hundreds of thousands of values.
- Evidence: query
/actuator/prometheusand look at theuritag values; if they contain concrete ids like/orders/48213instead of the template/orders/{id}, the tag is unbounded. Also check for a customObservationFilterorMeterFilteradding a user or tenant tag. - Likely causes, ranked:
- Unmatched paths: Boot tags unmatched paths as
UNKNOWNorrootby design, but a catch-all controller mapping like/**or a customWebMvcTagsContributorthat records the raw path defeats that. - Header-derived tags: a filter that adds tags from headers.
- Custom timer: a timer in application code with
Tags.of("customer", id). - Exception tag: an old exception tag with the exception message rather than the class.
- Unmatched paths: Boot tags unmatched paths as
- Fix: keep the
uritag as the route template, which Boot does when a handler matches, and for 404 scanning traffic ensure it maps to a single value; remove per-user tags from metrics and put such detail on spans or logs; add aMeterFilter.maximumAllowableTags("http.server.requests", "uri", 100, MeterFilter.deny())as a safety net so the registry refuses to create more series past a cap; and setmanagement.metrics.web.server.max-uri-tagsin older lines. Restart to clear the existing series, and let Prometheus expire the stale ones. - Prevention: a Prometheus recording of series count per job with an alert, and a review rule that any new tag must have a bounded, enumerable value set.
// CAUSE: a tag whose value is unbounded. Every distinct value creates a new
// time series, permanently, in both the application and Prometheus.
// 300,000 series from one metric is a high-cardinality label.
// ❌ TRAP: the URI tag contains the path variable's VALUE.
// /orders/4021, /orders/4022, ... one series per order ever requested.
@GetMapping("/orders/{id}") // if templating is lost, uri="/orders/4021"
public Order get(@PathVariable String id) { ... }
// Also broken, and more obviously so:
Metrics.counter("orders.processed", "customerId", customerId).increment();
Metrics.counter("orders.processed", "email", user.email()).increment();
// ✅ FIX: tag with the TEMPLATE, never the value. Boot does this correctly
// out of the box; it breaks when a filter or a manual timer overrides the tag.
Metrics.counter("orders.processed", "status", order.status().name()) // bounded set
.increment(); // Result: a handful of series, however many orders
// ✅ FIX: cap what can ever be published.
management.metrics.tags.application=order-service
management.metrics.enable.jvm.gc.pause=true
// ✅ FIX: past 200 distinct uri values, new series are denied
@Bean
MeterFilter cardinalityGuard() {
return MeterFilter.maximumAllowableTags(
"http.server.requests", "uri", 200, MeterFilter.deny());
}
// Plus a deny-list for known offenders, applied before they are ever created:
@Bean MeterFilter denyUnbounded() {
return MeterFilter.denyNameStartsWith("http.server.requests.customer");
}
// Result: series count per job has a ceiling, so Prometheus memory is bounded
The rule to state: a tag value must come from a set you can enumerate — a status, a method, an outcome. Anything derived from user input or an identifier belongs in a log line or a trace span, never in a metric label.
Picture it Series counts at three moments and the scrape lines that explain them.
The setup: a service that tags a metric with a per-user identifier, using the code above.
Make the invisible visible: the series the registry holds.
# illustrative output (PromQL: topk(3, count by (__name__) ({job="orders"})))
moment http_server_requests_* orders_processed scrape time Prometheus memory
before release 1,900 6 120 ms 2 GB
day 2 61,000 48,000 1.4 s 3 GB
day 5 300,000 210,000 4 s 4 GB
What you see: scrape lines that betray the unbounded tag.
# illustrative output
http_server_requests_seconds_count{method="GET",status="200",uri="/orders/48213"} 1 # ✗ value, not template
http_server_requests_seconds_count{method="GET",status="200",uri="/orders/48214"} 1 # ✗ another series
orders_processed_total{customerId="c-77231"} 1 # ✗ one series per customer
| Symptom | Root cause | Action |
|---|---|---|
| uri tag contains ids | Catch-all mapping or custom tag contributor records the raw path | Tag the template; fix the source |
| Tag has customer or email | Identifier used as a tag | Move it to spans or logs |
| Series count keeps climbing after fix | Stale series in the registry | Restart; let Prometheus expire the old ones |
| Count must never explode again | No cap | MeterFilter.maximumAllowableTags as a safety net |
What you see now: the same query after the fix, using the code above.
# illustrative output
moment http_server_requests_* orders_processed scrape time Prometheus memory
after fix 1,900 6 120 ms 2 GB
Land it A metric tag is a promise that its values are few, and the fix is templates and caps, with the unbounded detail moved to traces.
- "You added the MeterFilter cap and now dashboards for some legitimate routes are missing. What happened?"
The cap keeps the first hundred distinct
urivalues it sees and denies the rest, and which hundred it keeps is decided by traffic order after startup, not by importance.If the unbounded values arrived before a legitimate route had its first request, the legitimate route lost its slot. So the cap is a safety net, not a fix; the fix is that the
uritag never has unbounded values in the first place.I confirm by listing the series with
curl -s :8081/actuator/prometheus | grep http_server_requests | sed 's/.*uri="\([^"]*\)".*/\1/' | sort | uniq -c, and if concrete ids still appear, the source is still there, usually a catch-all mapping or a custom tag contributor.Once the source is fixed, a restart clears the registry, the legitimate routes claim their slots, and the cap sits unused, which is the state I want.
I would also set the cap well above the real route count, say 500 for 120 routes, to leave room.
which uri values existruns offline# illustrative output $ curl -s :8081/actuator/prometheus | grep http_server_requests | sed 's/.*uri="\([^"]*\)".*/\1/' | sort | uniq -c | sort -rn | head -3 6 /orders/{id} 6 /customers/{id}/addresses 1 /orders/48213 <- a concrete id: the source is still there- "Why does Boot use the route template for the uri tag, and when does it fall back to something else?"
The template,
/orders/{id}, is the bounded name of the handler, so tagging by it gives one series per endpoint regardless of how many ids exist; Boot'sServerRequestObservationConventionreads it from theHandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTEthat theDispatcherServletsets after routing.When no handler matched, there is no pattern, so the convention uses fixed fallbacks:
NOT_FOUNDfor 404s,REDIRECTIONfor 3xx,rootfor/, andUNKNOWNwhen nothing else applies, all bounded.The fallback breaks when a handler does match a huge space, such as a
@GetMapping("/**")that then returns 404 from code, because the pattern is/**but a custom convention or filter records the actual path; or when aResourceHandlerserves static files and someone tags by file name.Reading the convention class once is the fastest way to reason about which values are possible.
- "How do you keep per-customer detail available without putting it in metrics?"
Exemplars and spans.
Exemplars attach a trace id to a histogram bucket sample, so a latency spike on the dashboard links to one representative trace, and that trace carries the customer id as a span attribute; Boot enables exemplars for Prometheus when the tracing bridge is present and the Prometheus registry is configured with an
ExemplarSampler, and Grafana shows them as dots on the histogram.Spans carry high-cardinality attributes freely, because a span is one record, not a series, and the trace backend indexes attributes for search: "all traces for customer 4711 with latency over a second" is a trace query, not a metric query.
Logs carry the same ids and the trace id, so a customer complaint becomes a log search that leads to a trace. The division is: metrics answer "how many and how fast" by bounded dimensions, traces and logs answer "which one and why".
- "What is the actual cost of a series, so I can budget?"
In Prometheus, an active series costs a few kilobytes of memory in the head block plus index entries, and roughly one to two bytes per sample on disk after compression; the memory is what hurts, since it is per active series regardless of sample rate.
A timer with percentile histograms is not one series but one per bucket plus count, sum, and max, so with Boot's default of about 70 buckets for
http.server.requestseach route-method-status-outcome combination is around 75 series.A service with 120 routes, 3 methods, 5 statuses, and histograms is roughly 130,000 series, which is why histograms are enabled per route rather than globally.
Budget rule of thumb as of Aug 2026: a Prometheus instance handles a few million active series comfortably; a service should stay under 20,000, and the per-job series count is a standing dashboard panel with an alert at double the expected number.
Q126 · Design. "Design observability for a new checkout service: which metrics, traces, and logs, how they connect, and the SLOs and alerts on top."
Reveal answer
Strong answer Requirements: know when users are hurt, find the cause in minutes, keep cost bounded. Design in four layers.
Metrics from Micrometer to Prometheus via the Actuator endpoint on the management port: the built-in http.server.requests with percentile histograms enabled for the checkout routes (management.metrics.distribution.percentiles-histogram.http.server.requests=true), http.client.requests per dependency, Hikari pool metrics, JVM and GC, Tomcat threads, Kafka consumer lag, Resilience4j breaker states, and a small set of business counters such as checkout.completed and checkout.failed tagged by reason, all with bounded tags.
Traces via Micrometer Tracing to an OpenTelemetry collector with tail sampling that keeps every error and every trace over 2 seconds plus 5 percent of the rest; spans for the HTTP server, each outbound call, each JDBC statement through datasource-micrometer, and Kafka produce and consume; span attributes carry order id and customer id, which metrics must not.
Logs as structured JSON with logging.structured.format.console=ecs, automatically including traceId and spanId, shipped by the platform's log agent; the application logs one line per request at INFO with route, status, duration, and outcome, and errors with an error id that appears in the client's ProblemDetail.
Connection: the trace id is the join key across all three; dashboards link a latency spike to the exemplar trace, and the trace links to its logs.
SLOs: availability, the fraction of checkout requests not returning 5xx, at 99.9 percent over 30 days; latency, 95 percent of checkouts under 800 milliseconds; freshness for the Kafka side, 99 percent of order events processed within 10 seconds.
Alerts are burn-rate alerts on those SLOs, a fast burn paging at 14 times budget consumption over an hour, a slow burn ticketing at 2 times over a day, plus a few symptom alerts: pool pending, breaker open for 5 minutes, consumer lag rising.
No alerts on CPU or memory levels alone. Trade-offs: histograms cost series, so they are enabled only for the routes that matter. What I would not do: log request bodies, tag metrics by customer, or page on causes rather than symptoms.
Picture it One failing checkout followed through metric, trace and log by a single trace id, with the SLO arithmetic behind the pages.
The setup: a checkout request that is slow because the payment call is slow.
Make the invisible visible: the same request in the three signals, joined by one id.
# illustrative output
metric http_server_requests_seconds_bucket{uri="/checkout",le="1.0"} ... exemplar trace_id=4bf92f35...
trace POST /checkout 2,310 ms
├─ inventory 180 ms
├─ pricing 140 ms
└─ payment 1,890 ms ✗ slow dependency
log INFO checkout route=/checkout status=200 duration=2310ms outcome=SUCCESS traceId=4bf92f35... spanId=a1b2c3d4
The trace: from alert to cause.
burn-rate alert (latency SLO) ──► dashboard spike ──► exemplar dot ──► trace ──► payment span slow ──► its logs by traceId
What you see: the error budget as numbers.
SLO 99.9% over 30 days -> budget 0.1% = 43.2 minutes of full outage
burn rate 1 -> budget gone in 30 days
burn rate 14.4 -> budget gone in 50 hours; 1 hour of it costs 2% of the month -> page
burn rate 2 -> budget gone in 15 days -> ticket
| Symptom | Root cause | Action |
|---|---|---|
| Fast burn alert fires | Users hurt now | Follow exemplar to trace; check the dependency span |
| Latency alert, no error alert | Slow dependency | http.client.requests per dependency, then the breaker |
| Log line has no traceId | Tracing bridge missing | Add Micrometer Tracing; the MDC fills automatically |
| Alert on CPU level only | Cause rather than symptom | Delete; page on SLO burn |
Land it Metrics say when, traces say where, logs say what, the trace id joins them, and the pages come from SLO burn rates rather than from resource levels.
- "Explain the burn-rate alert numbers: why 14 times over an hour?"
Burn rate is how fast the error budget is being consumed relative to the rate that would exhaust it exactly at the end of the window.
A 99.9 percent availability SLO over 30 days allows 0.1 percent errors, so an error rate of 0.1 percent is a burn rate of 1 and uses the budget in 30 days.
A burn rate of 14.4 uses it in 30 days divided by 14.4, which is about 50 hours, and sustaining that for one hour consumes 2 percent of the monthly budget; that is a big enough loss to page a human.
The rule is written as: the error ratio over the last hour exceeds 14.4 times 0.001, and to avoid paging on a brief spike, the same condition must also hold over the last 5 minutes.
The slow burn, 2 times over a day, uses 2 percent of the budget too, but takes a day to do it, which is a ticket. Those pairs come from the Google SRE workbook and they map well to how humans should be interrupted.
- "The requirement changes: the checkout service now handles payments and must keep card data out of everything. What changes in observability?"
The data path changes and the tools stay.
Logs: a masking converter in Logback that redacts anything matching a card-number pattern, and a rule with a test that request and response bodies are never logged on payment routes; structured logging helps, because fields are explicit and the body is simply not a field.
Traces: span attributes for payment calls carry a payment id and a masked last-four, never the PAN, and the
ObservationFilterthat adds attributes is reviewed against a list; the trace backend is in scope for PCI if any card data could reach it, so keeping it out of scope requires proving it does not.Metrics: nothing changes, since they carry no identifiers. Access: the observability stack gets its own access control and retention, and an audit of who queried what.
The verification is a periodic scan of logs and traces in staging with synthetic card numbers, which should find zero hits.
- "What would you cut in the first week, and what is the risk?"
Traces and the Kafka freshness SLO. Metrics with histograms on the checkout routes, structured logs with trace and span ids, and the two burn-rate alerts on availability and latency ship in week one, because they are configuration in Boot and a few Prometheus rules, and they cover "are users hurt".
The trace pipeline needs a collector, sampling policy, and storage, which takes longer; the risk of shipping without it is that when the first latency alert fires, finding the slow dependency means reading logs and the
http.client.requestsmetric per dependency, which works but is slower.The freshness SLO waits until the Kafka consumer's lag metric is proven, since a wrong SLO alert is worse than none.
What I would not cut is the trace id in logs, even before tracing exists, because it costs nothing and makes the later trace pipeline immediately useful with the existing logs.
- "How do you keep the alerts from becoming noise over time?"
By reviewing every page. Each page gets a one-line entry: was it actionable, what was done, and if not actionable, which of three fixes applies, raising the threshold, adding a duration, or deleting the alert.
Monthly, the count of pages per alert and the fraction that were actionable go on the team's review; an alert that paged five times and was actionable once gets changed or removed.
Symptom alerts on SLOs age well because they are tied to what users experience; cause alerts on pool pending or breaker open are the ones that drift, so they are few and each has an owner.
I also keep the alert definitions in the service's repository next to the code, so a change to the alert is a reviewed pull request and the history explains why a threshold is what it is.
The goal is that every page is a real problem, because the first time someone ignores a page, all pages become optional.
Q127 · Design. "Design the resilience of a checkout endpoint that calls inventory, pricing, payment, and a fraud-scoring service in sequence, with a 1.5-second latency budget."
Reveal answer
Strong answer Requirements: stay under 1.5 seconds at p95, never charge without a reservation, degrade where possible, fail fast where not, and never let one dependency consume the thread pool. Design: classify each call.
Inventory and payment are required and must be correct; pricing and fraud can degrade, pricing to the last known price, fraud to a rules-based check. Budget the 1.5 seconds: inventory 200 milliseconds, pricing 150, fraud 300, payment 600, leaving margin.
Each client is a RestClient with connect timeout 200 milliseconds and read timeout at its budget, built through the platform customiser so a client without timeouts cannot exist.
Each dependency has its own protections:
- Bulkhead: a Resilience4j bulkhead capping concurrent calls, say 30 for payment and 20 for the others, so the worst case is 100 threads waiting rather than 200.
- Circuit breaker: a 20-call sliding window and a 50 percent failure threshold, open for 20 seconds.
- Retry, only where safe: one retry with 100 milliseconds of jitter on inventory and pricing reads, none on payment unless the payment idempotency key from Q48 is in place, in which case one retry on connection failures only.
Fallbacks for pricing and fraud are annotated fallbackMethods that record a metric so degraded checkouts are counted.
The sequence runs under a deadline: the handler computes the remaining budget after each step and passes it as the read timeout of the next call, so a slow inventory call does not push payment past the limit.
Ordering: reserve inventory, then price, then fraud, then payment, then confirm, with compensation on failure, meaning release the reservation if payment fails, done through a state machine on the order so a crash mid-sequence is resolved by a sweeper.
Parallelism: pricing and fraud are independent and run concurrently on virtual threads with a structured scope so both complete or both are cancelled. Trade-offs: degraded pricing may sell at a stale price for a few seconds, which the business accepts within a threshold.
What I would not do: retry payment blindly, share one bulkhead across dependencies, or let the sequence run inside a database transaction.
Picture it A 1.5-second budget spent step by step, with what each dependency state does to the clock and the thread pool.
The setup: the sequence with its deadline check.
Instant deadline = Instant.now().plusMillis(1500);
Duration remaining = Duration.between(Instant.now(), deadline).minus(reserve);
if (remaining.isNegative()) {
// ✅ FIX: refuse early instead of starting a call that cannot finish
throw new ResponseStatusException(HttpStatus.SERVICE_UNAVAILABLE);
}
// pass 'remaining' as the next call's timeout
Make the invisible visible: the budget at three moments.
# illustrative output
moment inventory pricing||fraud payment total bulkhead payment
healthy 120 ms 150 ms 420 ms 690 ms 4 of 30 in use
fraud breaker open 120 ms 150 ms (fallback 5 ms) 420 ms 690 ms 4 of 30
payment slow (read timeout) 120 ms 150 ms 600 ms ✗ 870 ms 30 of 30 in use, 12 rejected (BulkheadFullException)
The trace: the order of calls with what is parallel.
reserve inventory 200 ms
└─► pricing 150 ms || fraud 300 ms (parallel on virtual threads; slowest of the two counts)
└─► payment 600 ms
└─► confirm; on payment failure ─► release reservation (sweeper if that fails)
| Symptom | Root cause | Action |
|---|---|---|
| Whole service slow when payment is slow | Shared pool, no bulkhead | Bulkhead per dependency |
| Requests exceed 1.5 s though each call is within its timeout | Fixed per-call timeouts add up | Pass remaining budget |
| Pricing outage stops checkout | Degradable call without fallback | Last known price, counted metric |
| Charged without a reservation | Wrong order or no state machine | Reserve first, sweeper for compensation |
Land it Classify each dependency as required or degradable, give each its own timeout, bulkhead, and breaker, and spend the latency budget explicitly across the sequence.
- "Payment failed after inventory was reserved and the compensation call to release the reservation also failed. Now what?"
The order is in a state that records exactly that, and a background process finishes it. The orchestration writes the order's state before each step:
RESERVEDafter inventory,PAYMENT_FAILEDwhen payment fails,RELEASE_PENDINGwhen the release call fails.Nothing is lost, because the state is in the database, and the request returns a clean failure to the user with the reservation held for a short time.
A sweeper, every 30 seconds, picks up
RELEASE_PENDINGorders withSKIP LOCKEDand retries the release with the same idempotency key, backing off and moving to a manual queue after a bounded number of attempts; inventory reservations also carry an expiry, so even a sweeper failure resolves itself within, say, 15 minutes when the reservation lapses.That double safety is the point: compensation is a best effort that makes the common case fast, and expiry is the guarantee. The user sees a failed checkout, never a phantom reservation.
- "How does the remaining-budget deadline actually get into the RestClient call?"
Through a per-request timeout rather than the client's default.
The orchestrator keeps
Instant deadlinefrom the start of the request; before each call it computesDuration remaining = Duration.between(Instant.now(), deadline), subtracts a reserve for the steps that must follow, and refuses immediately with a 503 if the result is negative.RestClientdoes not take a timeout per call in its fluent API, so the mechanism is either a request factory whose read timeout is set per call through aClientHttpRequestFactorywrapper that reads a scoped value, or, simpler, Resilience4j'sTimeLimiterdecorating aCompletableFutureof the call with the remaining duration, cancelling the future on expiry.On virtual threads, the JDK
HttpClientaccepts a per-request timeout onHttpRequest.Builder.timeout, which is the cleanest path. I also forward the deadline as a header so the downstream can shed work it cannot finish.- "The requirement changes: fraud scoring must now be mandatory. What does that do to the budget?"
It removes a degradable step and makes the sequence more fragile, so I would renegotiate the shape rather than just the numbers.
Fraud stays at 300 milliseconds but loses its fallback, so a fraud outage means checkout is down, and the breaker's open state becomes a full failure rather than a degradation.
To recover slack, I run fraud in parallel with pricing, which already happens, and I move it earlier: score the cart before payment, ideally when the user reaches the checkout page rather than when they press pay, so the score is cached for a few minutes and the pay request finds it ready.
That takes 300 milliseconds off the critical path in the common case.
If the business also insists that scoring happens at the moment of payment, the honest answer is that the 1.5-second budget now has less margin, and the p95 target might need to move to 1.8 seconds, with the number shown to the product owner.
- "What would you cut under time pressure?"
The adaptive parts, not the protective ones. Every client gets connect and read timeouts and its own bulkhead on day one, because those are configuration through the platform customiser and they prevent the thread-pool exhaustion that takes the whole service down.
Circuit breakers come second and are also configuration.
What I would defer is the remaining-budget deadline propagation, using fixed per-call timeouts that sum to under 1.5 seconds instead, at the cost of some requests exceeding the budget when two calls are both slow; the parallel pricing and fraud calls, running them sequentially at first; and the fallback for pricing, failing the checkout instead of using a stale price until the fallback's business rules are agreed.
The compensation sweeper is not deferrable, because without it a payment failure leaks reservations, and that is a correctness bug from the first day.
Q128 · Scenario. "A circuit breaker around the payment gateway never opened during a 20-minute gateway outage; every request waited for the timeout. Another breaker opens several times an hour on a healthy dependency. Diagnose both."
Reveal answer
Strong answer In diagnosis order, for the breaker that never opened:
- Evidence: Resilience4j's
resilience4j.circuitbreaker.callsmetric by kind; if failed calls are counted as successful, the exception is not being recorded. - Likely causes:
- Exception not recorded: the timeout exception type is not in
recordExceptions, or is inignoreExceptions. - Swallowed: the client catches the timeout and returns an error object, so from the breaker's view every call succeeded.
- Slow calls ignored: slow calls are not counted as failures because
slowCallDurationThresholdis unset, so a 10-second wait is a "success". - Self-invocation: the annotation is on a method called by self-invocation, so no breaker is applied.
- Low traffic: the minimum number of calls in the window was never reached.
- Exception not recorded: the timeout exception type is not in
- Fix: record all exceptions by default, throw rather than swallow, set
slow-call-duration-threshold=2sandslow-call-rate-threshold=50, and verify with the state gauge in a test that injects failures.
For the breaker that flaps on a healthy dependency:
- Evidence: the failure-rate metric and which exceptions triggered transitions.
- Likely causes:
- Small window: 5 calls, so two client-side errors such as validation 400s open it.
- Business errors counted: a 404 or 422 from the dependency is a correct response, not a failure.
- Short wait: a wait duration so short the breaker flaps.
- Shared instance: one breaker across unrelated endpoints of the same host, where one endpoint's errors open the breaker for all.
- Fix: window of 50 or more calls with a minimum of 20, ignore 4xx client errors via
ignoreExceptionsor arecordFailurePredicateon the status, one breaker per logical operation, and a wait of 30 seconds with the half-open state allowing 5 trial calls.
Prevention for both: a fault-injection test per breaker in CI that asserts the transition, and the breaker state on the dashboard.
// ❌ TRAP: a circuit breaker counts FAILURES. A call that hangs is not a
// failure until something declares it one — and with no timeout, nothing does.
// Every request waited 30 seconds, no exception was recorded, the failure rate
// stayed at 0%, and the breaker had nothing to trip on.
// ✅ FIX: the timeout is the prerequisite, not the breaker.
factory.setReadTimeout(Duration.ofSeconds(2)); // now a hang becomes a failure. Result: failure rate climbs and the breaker opens
// ✅ FIX: a time limiter, applied BEFORE the breaker in the decorator chain.
@Bean
Customizer<Resilience4JCircuitBreakerFactory> gatewayConfig() {
return factory -> factory.configure(builder -> builder
.timeLimiterConfig(TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofSeconds(2))
.build())
.circuitBreakerConfig(CircuitBreakerConfig.custom()
.slidingWindowType(SlidingWindowType.COUNT_BASED)
.slidingWindowSize(20)
.minimumNumberOfCalls(10) // do not trip on the first two calls
.failureRateThreshold(50) // percent
.slowCallRateThreshold(50) // ALSO count slow calls as failures
.slowCallDurationThreshold(Duration.ofSeconds(1))
.waitDurationInOpenState(Duration.ofSeconds(30))
.permittedNumberOfCallsInHalfOpenState(3)
.build()),
"payment-gateway");
}
slowCallRateThreshold is the setting that would have saved this outage. Without it a dependency that responds slowly but successfully never trips the breaker, and slow-but-successful is by far the most common way a downstream service degrades.
Picture it Two breakers read through their own metrics: one that sees no failures at all, and one that sees too many.
The setup: the code above, with the original configuration that had no timeout and no slow-call threshold.
Make the invisible visible: the first breaker during the 20-minute outage.
# illustrative output
moment calls kind=successful kind=failed failure rate state request latency
before outage 600 0 0% CLOSED 120 ms
minute 5 of out. 12 0 0% CLOSED 30 s ✗ hangs counted as nothing
minute 20 9 0 0% CLOSED 30 s
The trace: what the breaker sees per call.
call ──► breaker ──► client.get() hangs 30 s ──► no exception yet ✗ nothing recorded
call ──► breaker ──► client catches timeout, returns error object ✗ counted as success
call ──► breaker ──► 2 s read timeout throws ──► failure recorded ✓ rate climbs, opens
What you see: the flapping breaker on a healthy dependency.
# illustrative output (slidingWindowSize=5, minimumNumberOfCalls=5)
window: 200 200 400 400 200 -> failure rate 40% CLOSED
window: 200 400 400 200 200 -> failure rate 40% CLOSED
window: 400 400 400 200 200 -> failure rate 60% OPEN (three validation 400s from a client's bad input)
| Symptom | Root cause | Action |
|---|---|---|
| Never opens, latency high | No timeout or slow-call threshold; exception not recorded | Read timeout, slow-call rate and threshold, recordExceptions |
| Never opens, rate 0 percent | Error object returned, call swallowed | Throw instead of returning an error |
| Opens on healthy dependency | Small window, 4xx counted as failure | Window 50 or more, ignore 4xx |
| One endpoint's errors open all | One shared breaker per host | One breaker per operation |
Land it A breaker only sees what you let it see: count slow calls and real failures, ignore client errors, and give it enough calls to judge.
- "How does the sliding window work, and why does a small window flap?"
Resilience4j records the outcome of each call in a ring buffer of the last N calls, count-based, or of the calls in the last N seconds, time-based, and after at least
minimumNumberOfCallsoutcomes it computes the failure rate and the slow-call rate over that window; crossing either threshold opens the breaker.With a window of 5 calls, one failure is 20 percent and three is 60 percent, so a couple of unrelated errors from a client's bad input open the breaker for a healthy dependency; and once the breaker moves to half-open, it permits a few calls and judges on those, so one more failure re-opens it, which looks like flapping.
A window of 100 with a minimum of 50 needs a sustained failure pattern to trip and gives a stable reading. Time-based windows suit low-traffic dependencies, where 100 calls could span an hour and a count-based window would react to ancient history.
- "Slow calls count as failures now. What is the right slow-call threshold, and what is the risk?"
The threshold should be the point at which the call is no longer useful to the caller, which is the caller's budget for that step, not the dependency's typical latency: if payment has 600 milliseconds in the budget from Q127, a call over 600 milliseconds is a failure from the user's point of view even if it eventually succeeds, so
slowCallDurationThreshold=600msandslowCallRateThreshold=50.The risk is opening the breaker during a dependency's slow-but-working period and turning a degraded state into a full failure for the wait duration; that is correct if a fallback exists and questionable if it does not.
For a required dependency with no fallback, I set the slow threshold at the read timeout instead, so the breaker opens only when calls are actually failing by timeout, and I rely on the bulkhead to contain the slow period.
The metric
resilience4j.circuitbreaker.slow.callsshows whether slow calls are what is opening it.- "How do you test a breaker transition in CI without a real outage?"
With a WireMock stub that fails on demand and the breaker's registry in the test. The test configures the client's base URL to the WireMock instance through a dynamic property, sets a scenario where the endpoint returns 503 or a fixed delay above the slow threshold, makes enough calls to fill the minimum window, and asserts
circuitBreakerRegistry.circuitBreaker("payment").getState()isOPEN; then it asserts the next call fails fast withCallNotPermittedExceptionin under a millisecond, which proves the fast-fail behaviour; then it advances the clock, which Resilience4j allows by configuring the breaker with a testClockor by setting a shortwaitDurationInOpenStatefor the test, switches the stub to success, and asserts the transition throughHALF_OPENtoCLOSED. The whole test takes a second, runs in the container job, and is the only thing that would have caught the breaker that never opened.fault-injection testruns offlinestubFor(get("/charge").willReturn(aResponse().withFixedDelay(3000).withStatus(200))); for (int i = 0; i < 12; i++) { try { client.charge(); } catch (Exception ignored) { } } assertThat(registry.circuitBreaker("payment").getState()).isEqualTo(CircuitBreaker.State.OPEN); assertThatThrownBy(() -> client.charge()).hasRootCauseInstanceOf(CallNotPermittedException.class);- "Why one breaker per operation rather than per host?"
Because a breaker's job is to detect that a specific thing is failing, and different operations on the same host fail independently.
A payment provider's authorise endpoint might be down while its status lookup is fine, or a search endpoint might time out on large queries while a lookup by id is instant; with one breaker per host, failures on one operation open the breaker for all and turn a partial outage into a full one, or, worse, successful cheap calls dilute the failure rate of the expensive one so it never opens.
Per-operation breakers each judge their own signal. The cost is more breakers to configure and observe, which the Resilience4j Boot starter handles through named instances sharing a default configuration, and a dashboard panel per breaker state.
The bulkhead, by contrast, is often per host, because it protects the caller's threads and the host's capacity, which are shared resources.
Q129. "What are the rules for retrying a call safely, and what does Spring Framework 7's core retry support give you compared to Resilience4j?"
Reveal answer
Strong answer Retry rules first. Retry only operations that are idempotent or made idempotent with a key, because a retried non-idempotent write is a duplicate.
Retry only failures that a retry can fix: connection refused, connection reset, timeouts on reads where the operation is idempotent, 503 with Retry-After, and 429; never 400, 401, 403, 404, or 422.
Use exponential backoff with jitter, for example 100 milliseconds doubling to a cap of 2 seconds, to avoid synchronised retry waves.
Bound attempts, three at most, and bound total time, because retries extend latency; a retry budget across the service, such as no more than 10 percent extra calls, stops a dependency outage from being amplified, which is the retry-storm mechanism from Q130.
Retry at one layer only; if the client library, the service, and the gateway all retry three times, one failure becomes 27 calls. And retry outside transactions, as in Q96.
Spring Framework 7 moved the essentials of the old Spring Retry project into the core: RetryTemplate in org.springframework.core.retry with a RetryPolicy built from max attempts, backoff, and included or excluded exception types, and the @Retryable annotation in org.springframework.resilience.annotation, enabled with @EnableResilientMethods, alongside @ConcurrencyLimit as a lightweight bulkhead; it is proxy-based like everything else.
What it does not have is a circuit breaker, a rate limiter, time limiter, or the metrics integration; for those you still add Resilience4j, which also composes the patterns in a defined order, bulkhead then time limiter then breaker then retry.
So: the core annotations for simple retries and concurrency caps with no extra dependency; Resilience4j when you need breakers and observability of the resilience layer.
Picture it The same call retried under the two libraries, with a timeline of attempts and a table of what each gives you.
The setup: one idempotent read, annotated with each library.
@Configuration
@EnableResilientMethods
class ResilienceConfig { }
@Service
class StockClient {
// ✅ FIX: retry only the failure a retry can fix, with backoff
@Retryable(includes = ResourceAccessException.class, delay = 100, multiplier = 2)
Stock stock(String sku) { return restClient.get().uri("/stock/{sku}", sku).retrieve().body(Stock.class); }
}
resilience4j.retry.instances.stock:
max-attempts: 3
wait-duration: 100ms
enable-exponential-backoff: true
exponential-backoff-multiplier: 2
enable-randomized-wait: true
Make the invisible visible: one call against a dependency that fails twice and recovers.
# illustrative output
t=0 ms attempt 1 ResourceAccessException (connection refused) ✗
t=110 ms attempt 2 ResourceAccessException ✗ (100 ms + jitter)
t=330 ms attempt 3 200 OK ✓
if every layer retries 3 times: client lib x service x gateway = 27 calls per failure ✗
| Need | Core retry (Framework 7) | Resilience4j |
|---|---|---|
| Retry with backoff | Works | Works |
| Concurrency cap | Works (@ConcurrencyLimit) | Works (bulkhead) |
| Circuit breaker | Not available | Works |
| Metrics for the resilience layer | Not produced by itself | Works via Actuator |
| Retry a non-idempotent POST with no key | Silently duplicates | Silently duplicates |
Land it Retry idempotent calls, on retryable failures, with jittered backoff and a budget, at exactly one layer, and reach for Resilience4j when you need a breaker beside the retry.
- "Show the Framework 7 annotation form and explain how the retry and the transaction proxies are ordered."
On a bean method:
@Retryable(includes = TransientDataAccessException.class, maxAttempts = 3, delay = 100, multiplier = 2, jitter = 50, maxDelay = 1000), with@EnableResilientMethodson a configuration class; the same package also offers@ConcurrencyLimit(10).The retry is applied by an AOP advisor with a default order that Spring places outside the transaction advisor, so on each attempt the
@Transactionalinterceptor runs afresh and creates a new transaction; that ordering is what makes the annotation on a transactional method work for the retry-on-optimistic-lock case, which the old Spring Retry project also handled by ordering.If a project changes
@EnableTransactionManagement(order = ...), the order can invert and the retry would rerun inside the doomed transaction, so I keep the retry on a separate outer bean anyway when correctness matters, as the Q96 rule says. The reactive form works onMonoandFluxreturn types too.- "How do you implement a retry budget rather than a per-call limit?"
With a token bucket shared across all calls to a dependency. Each first attempt deposits a fraction of a token, say 0.1, and each retry withdraws a whole token; a retry is allowed only if the bucket has one.
Under normal conditions the bucket fills, and occasional retries are free; during an outage, retries drain it faster than first attempts refill it, and once it is empty, calls fail without retrying, so total load on the dependency stays within 10 percent above first attempts.
Resilience4j has no built-in budget, so it is a small class: an
AtomicLongof tokens in milli-units, aRetryPolicypredicate that checks and decrements, and a Micrometer gauge on the balance.gRPC's client has this built in as
retryThrottling, and Envoy has a retry budget per cluster, which is the better place when a mesh exists. The metric to prove it works is outbound rate divided by inbound rate during a fault-injection test.- "When would you still pick Resilience4j over the core support in a new Boot 4 service?"
When I need a breaker, which is almost always for a network dependency, or when I need the observability.
Resilience4j's Boot starter registers metrics for every retry, breaker, bulkhead, and rate limiter with their state and call counts, exposes them through Actuator, and lets the patterns be configured in
application.ymlper named instance with shared defaults, which is what operations teams want to tune without a code change.The core
@Retryableand@ConcurrencyLimitare configured in code, produce no metrics by themselves, and compose only with each other.So for a service with one or two simple retries around a database call, the core annotations avoid a dependency; for a service with several network dependencies, Resilience4j is the right layer, and the core retry is not used.
As of Aug 2026 Resilience4j 2.3 supports Boot 4 and Framework 7 directly.
- "Retrying on a read timeout: safe or not?"
Only for idempotent operations, and only if the retry is bounded by the overall deadline. A read timeout means the request was sent and no response arrived in time; the server may have processed it fully, partially, or not at all.
For a GET or for a PUT with the same body, a retry is harmless. For a POST that creates something, a retry may create it twice unless the request carries an idempotency key the server honours.
The second condition is about time: a call with a 2-second read timeout retried three times can take 6 seconds, so the retry policy must know the remaining budget and skip attempts that cannot finish in it.
The third condition is that a read timeout on a dependency that is overloaded is exactly when retries do the most harm, so the retry runs under the breaker and the budget. If all three hold, retry once; if any fails, do not.
Q130 · Scenario. "A downstream service had a 30-second blip. Our service's traffic to it tripled and stayed tripled for 10 minutes, and the downstream fell over completely. Explain the mechanism and what to change."
Reveal answer
Strong answer In diagnosis order:
- Symptom: a short failure amplified into a sustained overload by the callers. That is a retry storm, made worse by queued work.
- Evidence: our outbound request rate versus our inbound rate during the window, showing 3 outbound per inbound; retry metrics from Resilience4j or the client; the queue depth of any executor or message consumer feeding the calls.
- Mechanism: during the blip, each call failed and was retried up to three times immediately, tripling load on a service that was already struggling. Meanwhile, callers of our service timed out and retried us, multiplying again. When the downstream recovered, it faced three times normal traffic plus the backlog of queued retries and could not catch up, so it stayed failing, which kept the retries flowing. No circuit breaker meant nothing ever stopped sending.
- Fix: a circuit breaker so that after the failure rate crosses the threshold we stop calling for 30 seconds and give the downstream room to recover; retries with exponential backoff and jitter instead of immediate; a retry budget capping retries at 10 percent of first attempts; honouring
Retry-Afteron 503 and 429; and a deadline per request so that retries do not exceed the caller's patience. Also apply the same on our own inbound side, returning 503 withRetry-Afterquickly when we are shedding, so our callers back off rather than pile on. - Prevention: a load test that injects a 30-second outage in a dependency and asserts that our outbound rate never exceeds 1.2 times inbound, and a review rule that every retry has backoff and a budget.
Picture it Request rates at four moments, showing a 30-second blip turning into a 10-minute outage.
The setup: a caller doing 100 requests per second to a service that can handle 150, with three immediate retries per failure and no breaker.
Make the invisible visible: the state of both sides over time.
# illustrative output
moment inbound outbound to downstream downstream capacity downstream state
normal 100/s 100/s 150/s healthy
blip (0-30 s) 100/s 300/s (3 attempts each) 0/s down
recovery (30 s) 100/s 300/s + queued backlog 150/s overloaded, latency > our timeout
10 minutes later 100/s 300/s 150/s still failing; retries feed the overload
The trace: the loop that never exits.
downstream slow ──► our timeout ──► retry x3 ──► more load on downstream ──► slower ✗ metastable
└─► our callers time out and retry us as well
breaker open 30 s ──► outbound drops to ~0 ──► downstream clears its queue ✓
| Symptom | Root cause | Action |
|---|---|---|
| Outbound is 3 times inbound | Immediate retries | Backoff, jitter, retry budget |
| Outbound stays high after recovery | No breaker | Breaker with open wait of 30 seconds |
| Downstream never leaves overload | No load shedding on its side | 503 with Retry-After, quickly |
| Outbound still above 1.2 times inbound | Several layers retry | One retry layer, others set to zero |
What you see now: the same table after breaker, backoff and budget.
# illustrative output
moment inbound outbound downstream state
blip (0-30 s) 100/s 110/s -> 0/s down; breaker opens after the window fills
recovery 100/s probes only healthy; half-open trials succeed
10 minutes later 100/s 100/s healthy
Land it Retries without a breaker and a budget turn a blip into an outage, because they add load at exactly the moment the dependency has the least to spare.
- "You added a breaker and backoff, ran the fault-injection test, and outbound still hit 2.5 times inbound. Where is the rest coming from?"
From layers that retry independently.
The call path may retry at the HTTP client library, which Apache HttpClient does by default for some I/O errors, at the service through Resilience4j, and at the mesh sidecar or ingress in front of the downstream, each with its own policy, and 2 × 2 × 2 is 8 attempts per user request in the worst case.
I list every layer between our code and the downstream socket and check each one's retry setting: the client's
setRetryStrategyor the JDK client's absence of retries, the Resilience4j config, Envoy'sretry_policy, and the downstream's own ingress.Then I pick the one layer that keeps the retry, usually the service, because it knows idempotency, and set the others to zero.
A second source is queued work: an
@Asyncor a Kafka consumer that keeps producing calls at the same rate while the breaker is closed again; those need the same breaker in front of them.attempts per user request, by layerruns offline# illustrative output layer retry setting attempts HTTP client library default strategy x2 Resilience4j max-attempts: 2 x2 mesh sidecar num_retries: 1 x2 = 8 downstream calls per user request ✗ # fix: keep the retry in the service, set the others to 1 attempt- "How do you make your own service tell its callers to back off?"
By shedding early and answering clearly.
When the load-shedding filter from Q143, or a breaker on a required dependency, decides a request cannot be served, the response is a 503 with
Retry-After: 2and a ProblemDetail, sent in microseconds from the filter so the rejection itself is cheap.Well-behaved clients and ingress controllers honour
Retry-After, and even those that do not at least get a fast answer instead of a slow timeout, which stops their own retry from stacking on a still-running request.For clients we own, the platform
RestClientcustomiser readsRetry-Afterand applies it as the backoff floor.The metric on shed requests by reason tells the callers' owners what happened, and an on-call runbook says that a rise in 503-with-Retry-After from a dependency means "do not add capacity by retrying".
Making back-pressure explicit in the protocol is what keeps the storm from propagating upstream.
- "Why did the downstream not recover once the blip ended? It was healthy for 30 seconds and then got the retries."
Because recovery needs headroom and it had none.
When it came back, it faced normal traffic plus every retry that had queued during the blip plus every retry of those retries, three times its capacity, so its queues filled, its latency rose past our timeouts, our timeouts produced more retries, and it was back in the failure state without having done anything wrong.
That is a metastable failure: a system that is stable at normal load but has a second stable state, overloaded, that it cannot leave on its own because the load itself is generated by the failure.
The only exits are for the callers to stop, which the breaker does, or for the downstream to shed load so it serves some fraction correctly and clears its queues, which its own load shedding does.
Both sides need their mechanism, and the test in prevention should be run on both.
- "What would you change in a greenfield design so this class of failure cannot happen?"
Three defaults in the platform starter so no service can opt out by forgetting. Every outbound client is built with a breaker, a bulkhead, timeouts, and a retry that has backoff, jitter, and a budget, configured centrally; a client without them cannot be constructed.
Every inbound path has load shedding with
Retry-After, so a service that is overloaded says so fast.And every asynchronous producer of outbound calls, whether an executor or a message consumer, runs behind the same breaker and pauses consumption while it is open, so a queue cannot keep generating load into a failure.
Add a fault-injection test in the platform's template that runs against every service in CI, asserting outbound rate stays within 1.2 times inbound during a simulated 30-second dependency outage. With those, the retry storm becomes a test failure in a pull request rather than an incident.
Q131 · Design. "Design scheduled jobs for a Boot service that runs as 10 replicas: a nightly reconciliation that must run exactly once, and a 30-second cache refresh that should run everywhere."
Reveal answer
Strong answer Two jobs, two semantics.
The cache refresh should run on every replica, because each has its own local cache, so a plain @Scheduled(fixedDelay = 30000) with fixedDelay rather than fixedRate, so a slow refresh cannot overlap itself, and on its own thread pool sized above one, spring.task.scheduling.pool.size=4, so the reconciliation cannot delay it; add jitter with an initialDelay derived from the pod's hash so 10 replicas do not hit the source at the same second.
The reconciliation must run once across the fleet.
Options:
- ShedLock: wraps
@Scheduledmethods with@SchedulerLock(name, lockAtMostFor = "PT2H", lockAtLeastFor = "PT5M")and takes a row-level lock in a shared table or Redis key, so whichever replica fires first runs it and the others skip. - Kubernetes CronJob: runs the same image with a different entry point,
--spring.main.web-application-type=noneand a runner profile, so the job has its own pod, resources, retries, and history, and the replicas do no scheduling at all. - Quartz in clustered mode: with a JDBC job store, when jobs need persistence, misfire handling, and dynamic schedules.
Decision: CronJob for the reconciliation, because it isolates resource use, gives a visible run history, and cannot be affected by a rolling deploy of the web replicas; ShedLock if the platform cannot run CronJobs or the job must share warm in-process state.
The reconciliation itself is chunked and idempotent, with a run record so a rerun after failure resumes. Trade-offs: a CronJob's pod pays startup each night, which is fine; ShedLock's lockAtMostFor must exceed the longest possible run or two runs overlap.
What I would not do: rely on @Scheduled alone across replicas, or use Quartz for two jobs.
// ❌ TRAP: @Scheduled runs on EVERY replica. Ten pods, ten reconciliations.
// ✅ FIX: a distributed lock. ShedLock is the usual choice because it needs
// only a table in the database you already have.
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30M")
public class SchedulingConfig {
@Bean LockProvider lockProvider(DataSource ds) {
return new JdbcTemplateLockProvider(ds, "shedlock");
}
}
@Component
public class Reconciliation {
@Scheduled(cron = "0 0 2 * * *", zone = "UTC") // ALWAYS set the zone
@SchedulerLock(name = "nightlyReconciliation",
lockAtMostFor = "PT2H", // safety net if the pod dies holding it
lockAtLeastFor = "PT5M") // guards against clock skew re-running it
public void reconcile() {
// Result: one pod runs it; the other nine skip silently
// MUST still be idempotent. lockAtMostFor expiring while this is
// genuinely still running lets a second pod start — which is exactly
// how duplicate invoices get sent.
}
}
Read the comment on lockAtMostFor. The lock has a timeout because a crashed pod must not hold it forever, which means the lock is a strong hint and never a guarantee — so the job must be idempotent regardless, and a lock is not a substitute for that.
Picture it Ten replicas and two jobs, with the lock table shown at three moments so you can see who runs what.
The setup: the code above: the cache refresh is a plain @Scheduled, the reconciliation carries @SchedulerLock.
Make the invisible visible: the shedlock table row for the nightly job.
# illustrative output
moment name lock_until locked_at locked_by
01:59:59 nightlyReconciliation 2026-11-12 00:05 2026-11-12 00:00 pod-4
02:00:00.003 nightlyReconciliation 2026-11-13 04:00 2026-11-13 02:00 pod-7 (lockAtMostFor 2 h)
02:00:00.004 pod-1..6, 8..10: UPDATE ... WHERE lock_until <= now() affects 0 rows -> skip
What you see: the log of ten pods at 02:00 with and without the lock.
# illustrative output
without @SchedulerLock: 10 lines "reconciliation started" on pod-1..pod-10 ✗ ten runs
with @SchedulerLock: 1 line "reconciliation started" on pod-7; the other nine log nothing ✓
cache refresh (no lock): 10 lines every 30 s, one per pod, offset by initialDelay hash ✓ intended
| Need | Choice | Why |
|---|---|---|
| Every replica must run it (local cache) | Plain @Scheduled, fixedDelay, own pool | Each has its own state |
| Exactly once nightly, isolated resources | Kubernetes CronJob | Own pod, history, retries |
| Exactly once, shares warm state | ShedLock | One row update per run |
| Persistence, misfire handling, dynamic schedules | Quartz clustered | JDBC job store |
Land it Run per-instance work with @Scheduled and jitter, and move fleet-wide work into a CronJob or behind a distributed lock, chunked and idempotent either way.
- "How does ShedLock's lock actually work in the database, and what happens if a replica dies mid-run?"
ShedLock keeps one row per job name in a
shedlocktable withlock_until,locked_at, andlocked_by. Acquiring is a single conditional statement:UPDATE shedlock SET lock_until = now() + lockAtMostFor, locked_at = now(), locked_by = host WHERE name = ? AND lock_until <= now(), and the affected-row count decides; a first-time job inserts the row and relies on the primary key to serialise.On normal completion, the lock is released by setting
lock_untiltonow()or tolocked_at + lockAtLeastFor, whichever is later.If the replica dies mid-run, nothing releases the lock, so it stays held until
lock_untilpasses, which is whylockAtMostFormust exceed the longest run: too short and a live job loses its lock, too long and a dead job blocks the next run.The job must therefore be resumable, because the next run after a death starts from the beginning of whatever the job's own progress marker says.
lock row across a crashruns offline# illustrative output moment locked_by lock_until what happens 02:00 pod-7 04:00 run starts (lockAtMostFor 2 h) 02:40 pod-7 04:00 pod-7 dies; nothing releases the lock 03:00 - 04:00 scheduler on pod-2 tries: lock_until > now -> skip ✗ no run 04:01 pod-2 06:01 next trigger finds the lock expired and starts from the progress marker- "The requirement changes: the reconciliation must now run every 5 minutes instead of nightly. Does the CronJob still win?"
Less clearly.
A CronJob every 5 minutes pays a pod start each time, 20 to 40 seconds for a JVM with the AOT cache, so a job that runs for a minute spends a third of its life starting, and Kubernetes' CronJob controller starts to show its quirks at that frequency, such as skipped runs when
startingDeadlineSecondsis missed and concurrency policy decisions.At that cadence, an in-process
@Scheduledunder ShedLock in the existing replicas is better: no startup cost, immediate access to warm caches, and the lock cost is one row update.The trade-off is the one the original design avoided, that the job shares resources with request traffic, so the job runs on its own scheduler pool and its database work uses the batch pool.
Between the two sits a dedicated worker Deployment of one replica that runs only the scheduler, which isolates resources without the startup cost, and that is what I would pick at 5 minutes.
- "How do you keep the 30-second refresh from causing a thundering herd against the source?"
Jitter and staggering, with a fallback for the source being slow.
The
initialDelayis derived from the pod's identity, for instance the hash ofHOSTNAMEmodulo 30 seconds, so ten replicas start their cycles at different offsets and the source sees a request every few seconds instead of ten at once;fixedDelaythen preserves the stagger, because each replica's next run is measured from its own completion.Boot 3.x and later also let you express jitter directly through a
SchedulingConfigurerwith a custom trigger.If the source is a shared database, the refresh reads a single small table and it is fine; if it is an HTTP service, the refresh uses a conditional request with
ETagso an unchanged answer costs a 304.And if the source is slow or down, the refresh has a 5-second timeout and keeps the previous value, with a metric on the age of the cache so staleness is visible.
- "What would you cut under time pressure?"
The CronJob, keeping ShedLock for the reconciliation inside the replicas, because ShedLock is a dependency plus a table plus an annotation, an hour of work, while a CronJob needs a second entry point, a manifest, and a way to run the same image without the web server.
The cost of the cut is resource sharing and the risk that a rolling deploy of the web replicas kills the job mid-run, which the job's idempotency and progress marker handle.
What I would not cut is the idempotency and the run record, because without them a job that dies mid-run either duplicates work or silently skips it, and that is the invoice-duplication incident from Q132.
Also not cut: the separate scheduler pool size, since the default of one thread means the 30-second refresh silently stops while the reconciliation runs, which is a bug that shows up as stale caches at 3 a.m.
Q132 · Scenario. "A nightly invoice job sent duplicate invoices to 1,200 customers. It is a @Scheduled method with ShedLock, and the logs show two replicas both ran it, 90 minutes apart. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom: the lock did not prevent a second run, and the gap is 90 minutes, which is a lock expiry, not a race.
- Evidence: the ShedLock table's
locked_at,lock_until, andlocked_byfor that job; the first run's duration in the logs; thelockAtMostForvalue in the annotation or the default. - Cause:
lockAtMostForwas set to 90 minutes, or the default was used, and the first run took longer than that, so the lock expired while the job was still running, and the second replica, whose scheduler fired late or was catching up after a restart, acquired the expired lock and ran the job again from the start. Possibly the first run was slow because the batch grew, and the invoice send is not idempotent, so the second run re-sent everything the first had already sent. - Fix, two layers. The lock: set
lockAtMostForwell above the worst-case run, and use ShedLock'sKeepAliveLockProvideror extend the lock periodically for long jobs, so a running job cannot lose its lock. The job: make it idempotent, with a per-invoicesent_atmarker set in the same transaction as the send record and a check before sending, so a rerun sends nothing twice; process in chunks and record progress. Then for the 1,200 customers, a corrective communication and a credit note process. - Prevention: a job duration metric with an alert at 50 percent of
lockAtMostFor, and a test that runs the job twice against the same data and asserts one send per invoice.
Picture it The lock row at three moments, showing the lock expiring while the first run is still going.
The setup: a nightly job with lockAtMostFor of 90 minutes and a run that now takes 130 minutes.
Make the invisible visible: the lock row and the job over time.
# illustrative output
moment locked_by lock_until job state
02:00 pod-3 03:30 run 1 starts
03:30 pod-3 03:30 lock expired; run 1 still going ✗
03:31 pod-7 05:01 run 2 acquires the expired lock and starts from the top
04:10 pod-3 - run 1 finishes
The trace: where the duplicates come from.
run 1 (pod-3) ──► sends invoices 1..9000 ✓
run 2 (pod-7) ──► invoice 1: no sent marker ──► sends again ✗ duplicate
invoice 1200 .. : both runs hit the same customers
What you see: the evidence in the logs and the data.
# illustrative output
SELECT customer_id, count(*) FROM invoice_send_log WHERE run_date = '2026-11-13' GROUP BY 1 HAVING count(*) > 1;
customer_id | count
------------+------
c-1018 | 2
... | 2 (1,200 rows)
| Symptom | Root cause | Action |
|---|---|---|
| Two runs 90 minutes apart | Lock expired before run 1 finished | lockAtMostFor above worst case, or keep-alive plus a hard stop |
| Rerun re-sends everything | Job not idempotent | Per-invoice claim before send |
| Nobody noticed the long run | No duration metric | Alert at 50 percent of lockAtMostFor |
What you see now: the same query after the claim-then-act fix.
# illustrative output
SELECT customer_id, count(*) FROM invoice_send_log WHERE run_date = '2026-11-13' GROUP BY 1 HAVING count(*) > 1;
(0 rows)
run 2 log: "claimed 0 invoices (all already claimed)"
Land it A lock with an expiry is a promise about duration, and the job must be idempotent because that promise will eventually be broken.
- "Why did the second replica fire 90 minutes late instead of at the scheduled time?"
It probably did not fire late; it fired at its own scheduled moment, which was the same wall-clock time, tried the lock, failed because the first replica held it, and skipped, which is correct.
The 90-minute-later run is a different trigger: with
fixedDelayorfixedRatethe schedule is relative to each replica's start, so a replica restarted 90 minutes after the others has its own phase and fires 90 minutes later, at which point the lock had expired.With a
cronexpression the phase is shared, so this pattern points atfixedRate, or at a replica that started during the first run and ran itsinitialDelaylater. The logs'locked_byvalue and each replica's start time confirm it.The fix for the phase problem is a cron expression for anything that should happen at a time of day, and the lock fix is separate.
- "How do you make the invoice send idempotent when the email provider has no idempotency key?"
By making the decision to send durable before the send, in a way that a rerun checks. Each invoice row gets
send_claimed_atandsent_at. The job claims a batch withUPDATE invoice SET send_claimed_at = now() WHERE id IN (...) AND send_claimed_at IS NULL RETURNING id, commits, sends those, and setssent_atper invoice as each send is accepted.A rerun selects only rows where
send_claimed_at IS NULL, so it never re-sends anything claimed.The window is a crash between claim and send, which leaves claimed-but-unsent rows; a sweeper after a timeout treats those as "unknown", queries the provider's message log by our reference if it has one, and otherwise routes them to a human list rather than resending automatically.
That converts a mass duplicate into a handful of manual checks. The claim-then-act pattern is the general answer for non-idempotent side effects.
- "How do you extend a lock during a long job, and what is the risk?"
ShedLock's
KeepAliveLockProviderwraps another provider and, on a background thread, extendslock_untilat intervals of half thelockAtMostFor, so a job that runs for hours keeps a lock configured for 30 minutes, and a job that dies loses it within 30 minutes.The risk is a job that is alive but stuck, for instance blocked on a database lock or spinning on a bad record: the keep-alive keeps extending, the lock never expires, and the next scheduled run silently skips forever while the stuck job holds it.
So keep-alive needs a companion: a metric for job duration with an alert at, say, twice the normal run, and a hard cap in the job itself, a deadline after which it stops and releases.
Without keep-alive, the same cap is simply
lockAtMostForand the job must finish inside it. I prefer the explicit cap plus chunked, resumable work over a lock that lives as long as the process does.- "What would the corrective process look like, and how would you prove the fix before the next nightly run?"
Corrective: query the send log for invoices with two sends in the window to get the 1,200 customers and the amounts; issue a credit note or a void for each duplicate through the accounting system in a batch with its own idempotency, and send one apology email through a separate, manually triggered template; notify support with the list before the emails go out.
Proof of the fix: a test that runs the job twice against the same Testcontainers data, the second run starting while the first is still marked running with an expired lock, and asserts exactly one send per invoice, which fails on the old code and passes on the claim-then-act version.
Then a rehearsal in staging with the real schedule, two replicas, and an artificially short
lockAtMostForto force the overlap.And the duration alert is live before the next run, so a slow run is noticed at 50 percent of the lock rather than the morning after.
Q133 · Design. "Design a Spring Kafka consumer for order events: 12 partitions, ordering per order id required, some messages are poison, and the handler writes to PostgreSQL."
Reveal answer
Strong answer Requirements: process events for one order in order, tolerate poison messages without blocking the partition forever, never lose an event, and handle redelivery without double writes.
Design: the producer keys messages by order id, so all events for an order land on one partition and Kafka preserves order within it.
The consumer is a @KafkaListener with concurrency = 12 when running as one instance, or 4 per instance across 3 instances, since more consumers than partitions sit idle; each consumer thread processes its partition sequentially, which is the ordering guarantee.
Acknowledgement mode is RECORD or manual with ack.acknowledge() after the database transaction commits, so an offset is committed only for work that is durable.
Idempotency: the handler inserts the message id into a processed_events table with a primary key and skips on conflict, in the same transaction as the business write, so a redelivery after a crash between commit and ack is a no-op.
Errors: a DefaultErrorHandler with exponential backoff of, say, 3 retries over 10 seconds for transient failures, then a DeadLetterPublishingRecoverer to orders.DLT with the exception recorded in headers; deserialization failures are wrapped by the ErrorHandlingDeserializer so a malformed message goes straight to the DLT rather than crashing the consumer loop.
The retry blocks the partition briefly, which is the ordering trade: non-blocking retries via retry topics would reorder events for the same order, so they are not used here. Poll tuning: max.poll.records=100 and max.poll.interval.ms above the worst-case batch time to avoid rebalances as in Q134.
Monitoring: consumer lag per partition with an alert, DLT message count, and processing time. Shutdown: the container's graceful stop finishes the current batch. Trade-offs: a poison message that keeps failing costs 10 seconds of partition delay before landing in the DLT; that is acceptable for ordering.
What I would not do: enable.auto.commit=true, catch exceptions in the handler and swallow them, or reprocess the DLT automatically without a human look.
Picture it An order's events on one partition, a poison message retried in place, and the crash windows that decide duplicates.
The setup: the error handler and the idempotent handler.
@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
ExponentialBackOffWithMaxRetries backoff = new ExponentialBackOffWithMaxRetries(3);
backoff.setInitialInterval(1000);
backoff.setMultiplier(2.0);
// ✅ FIX: retry in place, then publish to orders.DLT; ordering survives
return new DefaultErrorHandler(new DeadLetterPublishingRecoverer(template), backoff);
}
@Transactional
void handle(OrderEvent e) {
int inserted = jdbc.update("insert into processed_events(id) values (?) on conflict do nothing", e.messageId());
if (inserted == 0) return; // redelivery after a crash: no-op
// business write in the same transaction
}
Make the invisible visible: the partition for order 42, with one poison record.
# illustrative output
orders-7 (key=42): offset 100 OrderCreated ✓ 101 OrderPaid (poison) ✗ 102 OrderShipped (waiting)
attempt 1 fails, wait 1 s; attempt 2 fails, wait 2 s; attempt 3 fails
101 -> orders.DLT (headers: kafka_dlt-exception-fqcn, kafka_dlt-original-topic, ...); 102 then processes
The trace: the crash windows.
commit DB transaction ──► ack offset ✓ normal
commit DB transaction ──► crash ──► redelivery ──► processed_events primary key hit ──► skip ✓ harmless
ack offset first ──► crash before commit ✗ event lost, never allowed
| Symptom | Root cause | Action |
|---|---|---|
| Consumer lag on one partition only | Poison message retrying | Bounded retries, then DLT |
| Duplicate rows after a restart | No idempotency | processed_events insert in same transaction |
| Consumer crash loop on a bad payload | Deserialization failure | ErrorHandlingDeserializer |
| Rebalances | max.poll.interval.ms below worst-case batch | Raise it, lower max.poll.records |
Land it Key by order id, one thread per partition, commit after the transaction, dedupe on message id, and retry in place with a dead-letter exit so ordering survives.
- "How does the offset commit relate to the database transaction, and where is the window for duplicates?"
They are two separate systems, so there is no atomic commit across them; the design chooses which side can be duplicated and makes that side safe.
The handler runs the database transaction first, which inserts the business row and the message id into
processed_eventstogether; only after that commit does the container acknowledge the record, which with manual acknowledgement means the offset is committed on the next poll or immediately withAckMode.MANUAL_IMMEDIATE.The window is a crash after the database commit and before the offset commit: the new consumer for that partition restarts from the old offset and redelivers the record, the handler's insert into
processed_eventshits the primary key, and the handler skips, so the redelivery is harmless.The opposite ordering, committing the offset first, would lose the record on a crash, which is the case the design must never allow. Kafka's own transactions can make consume-transform-produce atomic, but not consume-and-write-to-PostgreSQL.
the two orderings after a crashruns offlineDB commit ──► crash ──► offset not committed ──► redelivery ──► primary key hit ──► skip ✓ duplicate absorbed offset commit ──► crash ──► DB never committed ──► record gone ✗ lost event- "The requirement changes: a poison message must not delay other orders on the same partition for more than a second. What changes?"
The blocking retry goes, and ordering is preserved a different way. The handler makes one attempt in place; on failure, it writes the record to a
parked_eventstable keyed by order id, acknowledges, and moves on, so the partition never stalls.Ordering is then enforced at the order level: before processing any record, the handler checks whether that order id has parked events, and if so parks this one too, so an order with a failed event accumulates its subsequent events in order rather than processing them out of sequence.
A sweeper retries parked events per order in sequence with backoff, and after a bounded number of attempts moves the order's queue to a dead-letter state for a human. Other orders on the partition are unaffected beyond the millisecond it takes to park.
This is more code than the blocking retry, which is why the original design used the simple form; the requirement justifies the complexity.
- "What would you cut with two days, and what is the risk?"
The idempotency table can be cut only if the writes are naturally idempotent, for example an upsert of the order's latest state keyed by order id and version, which many order-event handlers are; then a redelivery just rewrites the same row.
If the writes are inserts, such as appending order history, the table stays, because it is the only thing that makes redelivery safe.
I would cut the
ErrorHandlingDeserializerwrapping and accept that a malformed message stalls the consumer until someone skips it manually, which is a visible failure rather than a silent one, and I would cut the DLT publisher in favour of logging the failed record with its offset, which lets someone replay it by hand.The risk of the second cut is that a poison message blocks a partition until a human intervenes, which is a pager at 3 a.m.; that is the honest cost of two days, and the DLT is the first follow-up.
- "How does ordering survive a rebalance, and what about the cooperative assignor?"
Ordering within a partition survives because a partition has exactly one owner at a time and the new owner starts from the last committed offset; the risk is not reordering but reprocessing of the uncommitted tail, which the idempotency table absorbs.
The subtle case is the old owner still finishing a record while the new owner starts on the same partition after an eager rebalance, which can process two records of one order concurrently for a moment.
Spring Kafka's container waits for the in-flight record to complete before releasing the partition on revocation, bounded by
max.poll.interval.ms, which closes that window as long as the handler respects timeouts.The cooperative sticky assignor,
partition.assignment.strategy=CooperativeStickyAssignor, moves only the partitions that need to move and lets the others keep processing, so a scale-out no longer pauses the whole group, and it has been the sensible default since Kafka 3.x clients.
Q134 · Scenario. "Consumer lag on the orders topic keeps growing and the group rebalances every few minutes. CPU is low. Diagnose."
Reveal answer
Strong answer In diagnosis order:
- Symptom. Periodic rebalances with low CPU.
- A rebalance happens when a member leaves or is deemed dead.
- With low CPU the members are being kicked out for being slow rather than for being overloaded.
- Evidence. Three places to look:
- the broker's coordinator log or the client log shows "member has left the group" with the reason;
kafka.consumermetrics show the time between polls exceedingmax.poll.interval.ms, which defaults to 5 minutes;- the handler's processing time per batch.
- Cause chain.
- The listener processes a batch of
max.poll.records, default 500, and each record does a slow database write or an external call. - The batch takes longer than
max.poll.interval.ms, so the consumer fails to poll in time. - The coordinator evicts it and triggers a rebalance.
- The partitions move, and the new owner reprocesses from the last committed offset, which is the start of the same slow batch. The cycle repeats.
- Lag grows because nobody completes a batch. CPU is low because the time is spent waiting.
- The listener processes a batch of
- Fix.
- Reduce
max.poll.recordsto a size the handler completes in well under the interval, for example 50. - Raise
max.poll.interval.msmodestly if processing is legitimately slow. - Make the per-record work fast: batch the database writes and add timeouts on external calls.
- Use the cooperative sticky assignor so a rebalance moves fewer partitions.
- Consider running the handler on virtual threads with
spring.threads.virtual.enabledso blocking waits do not hold the consumer thread, though the poll interval still bounds batch time.
- Reduce
- Prevention. A metric for time between polls with an alert at 50 percent of the interval, and a load test that replays a day's events at 5x speed.
Picture it one poll batch that outlives max.poll.interval.ms, the loop it starves, and the metrics at three moments.
The setup: a plain record listener. The container calls it once per record, for up to 500 records returned by one poll().
@Component
public class OrderListener {
@KafkaListener(topics = "orders", groupId = "orders-svc")
public void onOrder(String payload) {
// ❌ TRAP: ~700 ms per record once the database slows down.
// The next poll() happens only after ALL records of this batch are done.
orderRepository.save(parse(payload));
}
}
Make the invisible visible: the consumer thread is one loop, and only poll() tells the group it is alive in the processing sense. The heartbeat is a separate thread, so it stays healthy while the loop is stuck.
consumer thread (…KafkaListenerEndpointContainer#0-0-C-1)
loop:
records = poll() # resets the max.poll.interval.ms clock (300 000 ms)
for r in records: onOrder(r) # 500 records x 700 ms = 350 s, no poll() in between
commit offsets
heartbeat thread (separate)
every 3 s: heartbeat -> coordinator # healthy, so session.timeout.ms (45 s) is never the problem
The trace: one hop per line, with the clock on the left.
t=0 s poll() -> 500 records, offsets 41000..41499
t=0..300 s onOrder() works through ~430 of them (700 ms each)
t=300 s ✗ no poll() for max.poll.interval.ms: client leaves the group
t=300 s ✗ rebalance: partition 3 moves to consumer B; offsets 41000..41499 were never committed
t=300 s consumer B poll() resumes at committed offset 41000
✗ same 500 records, same 350 s batch -> evicted again at t=600 s
What you see: client log, then the numbers at three moments.
# illustrative output
WARN consumer poll timeout has expired: the time between subsequent calls to poll()
was longer than max.poll.interval.ms (wording varies by client version)
ERROR CommitFailedException: the group has already rebalanced, so the commit cannot complete
INFO partitions revoked: [orders-3] ... partitions assigned: [orders-3]
| Moment | Time per record | Time per batch | Time between polls | Rebalances per 10 min | CPU | Lag | Offsets committed |
|---|---|---|---|---|---|---|---|
| A. before the database slowed | 20 ms | 10 s | about 10 s | 0 | 6% | 0 to 200 | advancing |
| B. incident | 700 ms | 350 s | 350 s, above the 300 s limit | 2 | 5% | 12 000, then 90 000 | stuck at 41000 |
| C. after: 50 records, one multi-row insert | about 25 ms | about 1.2 s | about 1.2 s | 0 | 12% | falling to 0 | advancing |
Why: the broker judges liveness of the poll loop by the gap between polls, not by CPU, so a loop that waits on a database for 350 seconds looks dead even though the process is idle.
The fix: smaller batches, faster records, and a cooperative assignor.
# ✅ FIX: a batch the handler finishes in seconds, not minutes
spring.kafka.consumer.max-poll-records=50
spring.kafka.consumer.properties.max.poll.interval.ms=300000
spring.kafka.consumer.properties.partition.assignment.strategy=org.apache.kafka.clients.consumer.CooperativeStickyAssignor
# Result: time between polls stays far below 300 s, no eviction, offsets keep committing
What you see now: row C in the table above, and a quiet group log.
# illustrative output
INFO partitions assigned: [orders-3] # once, at startup
# no "poll timeout" lines, no CommitFailedException, lag draining
| Symptom | Root cause | Action |
|---|---|---|
| Rebalance about every 5 min, CPU low, time between polls near 300 s | batch slower than max.poll.interval.ms | shrink max.poll.records, speed up each record, add timeouts |
| Rebalance, time between polls small, broker reason "session timed out" | heartbeat thread missed the session timeout (CPU throttling, long GC pause, network) | check throttling, GC pauses and network before touching poll settings |
| Rebalance coinciding with pod restarts | membership churn | look at restart count and the restart reason, fix that instead |
| Lag grows, no rebalances, every partition busy | throughput below arrival rate | faster records first, more partitions only deliberately |
Land it Rebalances with idle CPU mean the poll loop is starved by slow handlers, and the cure is smaller batches and faster records, not more consumers.
- "You reduced max.poll.records to 50 and rebalances still happen. What next?"
Then the eviction is not about batch time, or the batch time is far worse than expected.
First I check the metric for time between polls,
kafka.consumer.fetch.manager...or Spring Kafka'sspring.kafka.listenertimer, to see whether the handler still exceeds 5 minutes for 50 records, which would mean 6 seconds per record and points at a hanging external call with no timeout.If polls are fine, the other eviction path is the heartbeat: the consumer's background heartbeat thread must reach the coordinator within
session.timeout.ms, default 45 seconds, and a pod that is CPU-throttled, garbage-collecting for long pauses, or losing network to the broker misses it;kubectl top, GC pause metrics, and the broker's log reason, "session timed out" versus "rebalance timeout", separate these.Third, membership churn from pods restarting, which the restart count shows. Each has a different fix, and the broker log names which it is.
telling the three evictions apartruns offline# illustrative output $ kubectl get pods -l app=orders-svc NAME READY STATUS RESTARTS AGE orders-svc-6d9f-x2k 1/1 Running 4 38m # restarts: membership churn # broker / coordinator log reason (wording varies): # poll path: the member exceeded the rebalance timeout (max.poll.interval.ms) # heartbeat path: the member's session timed out (session.timeout.ms) $ kubectl top pod orders-svc-6d9f-x2k NAME CPU(cores) MEMORY(bytes) orders-svc-6d9f-x2k 1000m 812Mi # pinned at the limit: suspect throttling- "Can you fix this with more consumer instances?"
No, and it can make it worse. Twelve partitions means at most twelve active consumers; adding a thirteenth leaves it idle, and each new member joining triggers a rebalance, which is more of the symptom.
The lag is caused by each consumer taking too long per batch, so with the same per-record cost, more consumers only helps up to the partition count and then stops.
The fix is per-record time: batch the database writes so 50 records become one multi-row insert, add timeouts on external calls, and move slow enrichment out of the consumer path into a separate step.
If the per-record cost is intrinsic and the partition count is the ceiling, the answer is more partitions, which is a topic change with its own consequences for ordering and key distribution, and it should be done deliberately rather than as an incident response.
Concurrency inside a partition is also possible with Spring Kafka's batch listeners, at the cost of ordering.
- "How do virtual threads help or not help here?"
They do not change the poll-interval constraint, which is the root cause: the consumer thread must call
pollwithinmax.poll.interval.ms, and if the handler for a batch takes longer than that, it makes no difference whether the handler's thread is virtual.What they change is the cost of concurrency within a batch: with a batch listener that fans out records to virtual threads and waits for all of them, 50 records with 200-millisecond external calls complete in 200 milliseconds instead of 10 seconds, so the batch fits the interval comfortably, at the cost of per-partition ordering within the batch unless the fan-out is grouped by key.
Spring Kafka runs listener containers on virtual threads when
spring.threads.virtual.enabled=true, which removes a thread-pool sizing question but not the timing one. The honest fix remains making each record cheap, and virtual threads make parallel I/O cheap to write.- "How do you set the alert so it fires before lag becomes visible to users?"
On time between polls and on lag growth rate, not on lag level. The poll-interval metric compared against
max.poll.interval.msgives the earliest signal: an alert at 50 percent of the interval, sustained for a minute, fires before any eviction occurs.Lag level alone is noisy, because a burst of producer traffic creates lag that the consumers clear in seconds; what indicates trouble is lag that grows for several minutes while the consumer's processed-record rate is flat, which in Prometheus is
deriv(kafka_consumer_lag[5m]) > 0combined with a low processing rate.A third alert on the rebalance count, more than two per ten minutes, catches the churn itself.
The user-facing SLO from Q126, freshness of processed events, is the backstop that says whether anyone was affected, and the three cause alerts are supposed to fire before it does.
Q135 · Design. "Design the transactional outbox for a Boot service so that an order written to PostgreSQL always produces exactly one Kafka event, and compare doing it in-process against Debezium."
Reveal answer
Strong answer Requirements: an event is published if and only if the order commits, no event is lost on a crash, duplicates are tolerated by consumers, and the order path stays fast.
- The write path. The order service writes the order row and an
outboxrow in one transaction.- The outbox row holds id, aggregate id, type, payload as JSON, created at, and published at (null until sent).
- That is the whole atomicity trick: one database, one commit.
- The relay. A separate relay reads unpublished rows in id order.
- It publishes them to Kafka with the aggregate id as the key and the outbox id as a header for consumer deduplication.
- It marks them published after Kafka acknowledges.
- In-process relay. A
@Scheduledpoller every 500 milliseconds.- It selects the oldest 100 unpublished rows with
FOR UPDATE SKIP LOCKEDso multiple replicas can share the work. - It publishes with
KafkaTemplateandacks=all, and updates in the same transaction. - Spring Modulith's event publication registry implements this pattern for in-process listeners, and its externalisation support publishes registered events to Kafka with the same guarantee.
- It selects the oldest 100 unpublished rows with
- Debezium relay. The connector tails PostgreSQL's write-ahead log, sees the outbox insert, and publishes it with the outbox event router.
- No polling and no application code.
- The outbox rows can be deleted immediately after insert, since the log already captured them.
- Comparison.
- In-process: simpler to operate and debug, latency of the poll interval, poll load on the database.
- Debezium: sub-second latency and no polling, but Kafka Connect as extra infrastructure and logical replication to enable.
- Choice. In-process for a few services and moderate volume, Debezium when many services need it or latency matters. Either way consumers must be idempotent because the relay is at-least-once, and the outbox table needs a retention job.
- What I would not do. Publish to Kafka inside the transaction before commit, or after commit without a stored record, since both lose the guarantee. Chapter E7 treats the wider pattern.
// The problem: writing to the database and publishing to Kafka are two systems.
// There is no transaction across both, so any order between them can lose or
// duplicate a message if the process dies in the gap.
// SOLUTION: write the event to the SAME database, in the SAME transaction.
@Service
public class OrderService {
@Transactional
public Order place(OrderRequest r) {
Order order = orders.save(toOrder(r));
// Same transaction: either both rows commit, or neither does.
// ✅ FIX: the event is written in the SAME transaction as the order.
outbox.save(new OutboxEvent(
UUID.randomUUID(), "OrderPlaced", order.id(),
json.writeValueAsString(order), Instant.now()));
// Result: both rows commit together, or neither does.
return order;
}
}
// A separate poller publishes and marks sent. Crash anywhere and it retries,
// which is why the consumer must be idempotent: this is AT-LEAST-ONCE.
@Component
public class OutboxPublisher {
@Scheduled(fixedDelay = 500)
@SchedulerLock(name = "outboxPublisher", lockAtMostFor = "PT1M")
@Transactional
public void publish() {
// SKIP LOCKED lets several instances drain the table concurrently
// without blocking each other or double-sending the same row.
for (OutboxEvent e : outbox.findUnpublishedForUpdateSkipLocked(100)) {
// ❌ TRAP: a crash after send() and before the commit below
// leaves the row unpublished, so it is sent again on restart.
kafka.send("orders", e.aggregateId(), e.payload());
// Result: AT-LEAST-ONCE delivery, never lost, sometimes duplicated.
e.markPublished(); // committed with this transaction
}
}
}
Read the phrase “at-least-once”. The outbox guarantees the event is never lost, not that it is sent exactly once — a crash after the send and before the mark produces a duplicate, so the consumer must deduplicate on the event id.
Picture it the order and its outbox row committing together, the relay moving the row out, and what each crash point leaves behind. The code in the transactional outbox block above is the setup.
The setup: the OrderService.place and OutboxPublisher.publish code in the block above: two inserts in one transaction, then a relay that sends and marks.
Make the invisible visible: the two tables, at three moments.
# illustrative output
t0 before place() orders: (empty) outbox: (empty)
t1 place() committed orders: id=7 total=40.00
outbox: id=1 | OrderPlaced | aggregate 7 | published_at = NULL
t2 relay sent + committed outbox: id=1 | OrderPlaced | aggregate 7 | published_at = 12:00:00.4
Kafka topic orders, key=7: 1 event
The trace: the relay transaction with the crash points marked.
place() BEGIN
├─ INSERT orders ✓
├─ INSERT outbox ✓
└─ COMMIT ✓ both rows exist, or neither does
relay (every 500 ms) BEGIN
├─ SELECT ... WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED
├─ kafka.send(key=7) ✓ acknowledged (acks=all)
├─ crash here ✗ event is in Kafka, row still unpublished
├─ UPDATE outbox SET published_at = now()
└─ COMMIT ✓ row marked
What you see: the outcome of a crash at each point.
| Crash point | Orders row | Event in Kafka | After restart |
|---|---|---|---|
before COMMIT in place() | absent | none | nothing to repair, the client sees an error and retries |
| after COMMIT, before the relay runs | present | none yet | the relay finds the unpublished row and sends it |
after kafka.send, before the mark commits | present | 1 event | the relay sends it again: a duplicate, so the consumer deduplicates on the outbox id |
| Kafka down for an hour | present | none | rows wait unpublished, the backlog drains in order afterwards |
Why: the order and the event are one database commit, so no crash can separate them. Only the move to Kafka can repeat, which is why the guarantee is at-least-once.
The fix for the Debezium side: the same outbox row is picked up from the log instead of by a poller.
order service INSERT orders + INSERT outbox, COMMIT
PostgreSQL WAL records both inserts (wal_level=logical)
Debezium connector reads the outbox insert from a replication slot
└─ outbox event router -> topic orders, key = aggregate id
Kafka Connect stores its offset in Kafka; resumes from the last confirmed WAL position
| Symptom | Root cause | Action |
|---|---|---|
| Order exists, no event ever appears | event published outside the order transaction, or after commit with no stored record | write the outbox row in the same transaction |
| Same event arrives twice | crash between send and mark (at-least-once) | consumer deduplicates on the outbox id |
| Events for one order arrive out of order with several relays | batches of different replicas interleave rows of one aggregate | single relay under ShedLock, or claim work per aggregate |
| Database disk fills while Kafka Connect is down | replication slot retains WAL until consumed | alert on slot lag in bytes |
Land it Write the event in the same transaction as the fact, and let a relay, polling or log-based, move it to Kafka at least once for idempotent consumers.
- "How does the polling relay preserve order when multiple replicas share the work with SKIP LOCKED?"
It does not preserve global order, and it must preserve per-aggregate order, which needs one more rule. Two replicas each take a batch of 100 unpublished rows, and rows for the same order can land in different batches and be published out of order.
The fix is to claim by aggregate: the relay selects distinct aggregate ids with unpublished rows, locks per aggregate with an advisory lock or a row lock on a small
outbox_leasetable keyed by aggregate id, and publishes that aggregate's rows in id order before releasing.Simpler, and what I usually do: run a single relay instance under ShedLock, since a relay publishing 100 rows per 500 milliseconds handles 200 events per second, which is enough for most services, and scale by partitioning the outbox by aggregate hash across a small fixed number of relay workers when it is not. Kafka then preserves order within the partition keyed by aggregate id.
- "What happens when Kafka is down for an hour, in both designs?"
In the polling design, the relay's
sendfails or times out, the transaction that would mark rows published rolls back, and the rows stay unpublished; the relay keeps polling with backoff, and when Kafka returns it publishes the backlog in order, which for an hour at 50 events per second is 180,000 rows, cleared in a few minutes.The order path never noticed, since it only wrote to the database. The metric for the age of the oldest unpublished row alerts within minutes.
In the Debezium design, the connector's producer fails, Kafka Connect retries the task and, with its offset stored in Kafka, resumes from the last confirmed WAL position when the broker returns, so nothing is lost either; the risk is on the database side, because the replication slot retains WAL until the connector consumes it, and an hour of WAL on a busy primary can fill the disk.
That is the operational cost of log-based capture, and the alert is on replication slot lag in bytes.
what Kafka down for an hour looks likeruns offline# illustrative output polling relay: unpublished rows = 180000, oldest age = 3600 s -> alert fires within minutes after Kafka returns: backlog drains in a few minutes, in id order Debezium: SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) FROM pg_replication_slots; debezium_orders | f | 41 GB # WAL retained for the stalled connector- "The requirement changes: consumers cannot be made idempotent. Can you give exactly-once?"
Not across PostgreSQL and Kafka, honestly, and I would push back on the requirement.
The relay can be made to publish each row at most once by marking before sending, but then a crash after marking and before Kafka acknowledged loses the event, which is worse than a duplicate.
Kafka's idempotent producer with
enable.idempotence=trueremoves duplicates caused by producer retries within a session, and Kafka transactions make consume-transform-produce atomic within Kafka, but neither spans the database commit. So the choices are at-least-once with idempotent consumers, or at-most-once with possible loss.The practical answer for a consumer that "cannot" be idempotent is usually that it can, cheaply: a processed-id table as in Q133, or an upsert keyed by the event id, which the consuming team adds in an afternoon.
If a third-party consumer truly cannot, a small deduplicating proxy service in front of it does it for them.
- "What would you cut with two days, and what would you never cut?"
With two days I would ship the in-process polling relay as a single ShedLock-guarded scheduled method, without
SKIP LOCKEDsharding, without the retention job, and with a plainKafkaTemplatesend usingacks=all.That is the outbox table, one
@Scheduledmethod, and one metric, and it gives the full guarantee for moderate volume. The retention job comes in week two; until then the table grows, which at 50 events per second is a few gigabytes a month and harmless.What I would never cut is writing the outbox row in the same transaction as the order, because that single line is the guarantee, and publishing "after commit" without it is the design that loses events on a crash.
I would also never cut
acks=alland marking rows only after the broker acknowledged, because withacks=1a broker failover can lose an acknowledged event and the row is already marked published.
The final group tests whether you can move a fleet forward safely, harden a service before it faces the internet, and make the calls that have no single right answer.
Q136 · Design. "Design the migration of 40 services from Spring Boot 2.7 to a supported line in 2026, with limited team time and no feature freeze."
Reveal answer
Strong answer Assumptions, as of August 2026:
- Boot 2.7 has been out of open-source support since late 2023.
- Boot 3.5 ended open-source support on 30 June 2026, so the only supported open-source destinations are 4.x.
- Two majors must be crossed, and the first, 2.7 to 3.x, is the bigger one because of Jakarta EE.
Design: staged, mechanical, measured.
- Stage zero, inventory. A script reads every service's Boot version, Java version, and the dependencies that matter (Spring Security, Hibernate, Spring Cloud, Jackson customisations), producing a risk ranking.
- Stage one, prerequisites on 2.7. Everyone does these now:
- Java 17 or 21, and every deprecation warning fixed.
- Replace
WebSecurityConfigurerAdapterwith aSecurityFilterChainbean. - Replace the Spring Retry and RestTemplate patterns that will change.
- Get the test suite green with Testcontainers so the migration has a safety net.
- Stage two, 2.7 to 3.5. Run OpenRewrite's
UpgradeSpringBoot_3_5recipe, which rewritesjavaxtojakarta, property renames, and known API changes. Then fix the rest by hand: Hibernate 6 query and id-generation changes, the Spring Security 6 authorisation DSL, trailing-slash matching, and library versions. - Stage three, 3.5 to 4.x. Run the corresponding recipe:
@MockitoBean, Jackson 3, module split, removed deprecations. Each stage lands as an ordinary pull request per service with the migration checklist as its template, so no freeze is needed. - Sequencing. A pilot on two low-risk services to write the checklist, then a wave of the 10 simplest to build confidence and tooling, then the rest. The platform starter from Q5 is bumped once per wave so shared code is migrated once.
- Budget and guardrails. About a day per simple service and a week per complex one, spread over a quarter. A CI check fails builds on unsupported Boot versions after a date, and a dashboard shows the fleet's versions.
- Trade-offs. Going straight from 2.7 to 4.x in one jump saves a stage but doubles the change set per pull request, so I would do it only for trivially small services.
- What I would not do. A big-bang branch per service that lives for weeks, or staying on 3.5 with commercial support as a plan rather than a bridge.
Picture it what one recipe run changes and leaves alone, and the fleet dashboard at four moments.
The setup: one service, one recipe run.
# run on the service's own branch, one pull request per stage
mvn -U org.openrewrite.maven:rewrite-maven-plugin:run \
-Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-spring:RELEASE \
-Drewrite.activeRecipes=org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_5
Make the invisible visible: the recipe is a mechanical diff. Syntax moves, behaviour does not.
- import javax.persistence.Entity;
+ import jakarta.persistence.Entity;
- http.authorizeRequests().antMatchers("/orders/**").authenticated();
+ http.authorizeHttpRequests(a -> a.requestMatchers("/orders/**").authenticated());
# property renames in application.properties are rewritten the same way
| Change | Recipe | Who finds it |
|---|---|---|
javax.* to jakarta.* imports | rewrites | compiler |
| Hibernate 6 query parsing, id generation, type mappings | nothing: code compiles, behaviour changed | integration suite on a real PostgreSQL |
| Security matchers and trailing-slash handling | converts the syntax only | route-by-route authorisation test |
Library still importing javax.servlet | nothing | runtime NoClassDefFoundError, or the stage-zero inventory |
The trace: one service across the stages, one pull request each.
service on 2.7 ──► PR 1 prerequisites on 2.7 (Java 17, SecurityFilterChain, Testcontainers) ✓ suite green
──► PR 2 recipe to 3.5 + manual Hibernate 6 / Security 6 fixes ✓ suite green
──► PR 3 recipe to 4.x (Jackson 3, @MockitoBean) ✓ suite green
└─► deploy; each PR merges to main, no long-lived branch ✗ a branch alive for weeks is the anti-pattern
What you see: the fleet dashboard at four moments.
| Week | On 2.7 | On 3.5 | On 4.x | Open migration PRs |
|---|---|---|---|---|
| 0, inventory done | 40 | 0 | 0 | 0 |
| 4, pilot and wave 1 landed | 30 | 10 | 0 | 6 |
| 8, wave 2 under way | 12 | 20 | 8 | 9 |
| 12, deadline | 0 | 6 | 34 | 4 |
Why: the recipes do the mechanical part, the pilot writes the checklist for the manual part, and the dashboard turns a project into a visible rate.
| Symptom | Root cause | Action |
|---|---|---|
Build fails on javax.* imports after the bump | recipe not run or partly applied | run the recipe, fix the leftovers by hand |
| Starts, but queries return different results or id errors | Hibernate 6 behaviour change | real-database integration suite, SQL diff (see Q137) |
| A path that was protected is now open, or one that was open now returns 403 | matcher and trailing-slash semantics | authorisation test per route |
NoClassDefFoundError: javax/servlet/... at runtime | old third-party library | upgrade or replace it, found early by the inventory |
Land it Prepare on the old version, use the rewrite recipes for the mechanical work, cross one major at a time in ordinary pull requests, and let the fleet dashboard drive the pace.
- "What are the top three things that break in the 2.7 to 3.x step that a rewrite recipe does not fix?"
Hibernate 6 semantics, Spring Security's authorisation model, and third-party libraries that never moved to Jakarta.
Hibernate 6 changes query parsing, id generation defaults, and type mappings, as Q137 details; the recipe rewrites nothing there, since the code compiles and only the behaviour changed, and only the integration suite against PostgreSQL finds it.
Spring Security 6 removes
WebSecurityConfigurerAdapterand changes the default matcher toPathPatternRequestMatcherwith strict trailing-slash handling, so/orders/no longer matches/ordersand a rule written forantMatcherscan silently protect fewer paths; recipes convert the syntax, not the semantics, and a route-by-route authorisation test is the guard.Old libraries with
javax.servletorjavax.persistenceimports fail at runtime withNoClassDefFoundError; the fix is an upgrade if one exists, a replacement if not, and the inventory in stage zero is what finds them early.- "What actually changes for a service going from 3.5 to 4.0?"
As of Aug 2026, here is the list from Boot 4.0's release notes that affects most services.
- Jackson 3 replaces Jackson 2, with a new package root
tools.jackson. Every custom serialiser,ObjectMappercustomisation and annotation import moves — thoughcom.fasterxml.jackson.annotationstays for the annotations. @MockBeanand@SpyBeanare removed, becoming@MockitoBeanand@MockitoSpyBean.- The starters were reorganised into finer modules, so some auto-configuration imports and test annotations changed packages.
- Deprecated APIs from 3.x are gone, and Undertow support is removed.
- Java 17 remains the minimum, but Java 21 is where virtual threads and the AOT cache pay off.
- Spring Framework 7 brings JSpecify null annotations — which turn some
warnings into errors under strict tooling — plus API versioning and
RestTestClient. - Hibernate 7 with Jakarta Persistence 3.2 is underneath.
The OpenRewrite recipe handles the imports and the annotations. What it cannot handle is Jackson 3's behaviour changes in defaults, such as date handling — those need the JSON contract tests.
- Jackson 3 replaces Jackson 2, with a new package root
- "The team says 40 services in a quarter is impossible. How do you respond?"
With the arithmetic and the pilot's numbers.
A quarter is about 60 working days; the estimate is a day for a simple service and a week for a complex one, and the inventory typically shows two-thirds simple, so 27 days plus 13 weeks of engineer time, roughly 90 engineer-days, which across a platform pair and the owning teams contributing one engineer-week each is feasible without a freeze.
If the pilot proves the estimate wrong, the plan changes, which is why the pilot goes first. The other lever is scope: services that are scheduled for retirement do not migrate, and services that are trivially small can jump straight to 4.x.
And the alternative to "impossible" is not "do nothing": it is running unsupported software with known CVEs, which the security team will eventually force at a worse time.
Framing the migration as a fixed weekly cadence, three services a week, makes it a routine rather than a project.
- "What would you cut under time pressure, and what would you refuse to cut?"
Cut the fleet dashboard, replacing it with a spreadsheet, and cut the stage of upgrading to 3.5 as a distinct release; a service can go from 2.7 to 3.5 and then to 4.x in one branch with two commits, with only the 4.x version deployed, as long as the integration suite runs at both points.
Cut the CI version gate for the first month, since the dashboard shows the laggards anyway.
What I refuse to cut is the Testcontainers-based integration suite as a precondition, because a migration across Hibernate 6 without a real database suite is a migration into production incidents, and the pilot, because the checklist it produces is what lets the remaining 38 services go fast.
I would also refuse a freeze, since the pull-request-per-service approach was chosen exactly so features keep shipping; the cost of that is that some services migrate on a branch that needs a rebase, which is a normal cost.
Q137 · Scenario. "Right after a 2.7 to 3.x migration, a service compiles and starts, but a search endpoint returns wrong results and a batch job's inserts fail with a sequence error. Diagnose both."
Reveal answer
Strong answer In diagnosis order, both are Hibernate 6 behaviour changes, not Spring ones:
- The search. Evidence is a JPQL or Criteria query whose semantics changed. Likely causes, ranked:
- Hibernate 6 became strict about JPQL, so implicit joins, positional parameters, and functions that the lenient Hibernate 5 parser accepted now parse differently or throw.
- A
DISTINCTwith pagination that Hibernate 5 handled in memory is now pushed to SQL. - Enum and boolean mapping defaults changed (ordinal versus name, and the SQL type for enums).
@Typeand custom types were replaced by the new type system.
- The sequence error. Evidence is an id generation exception or a duplicate key after the migration.
- Cause: Hibernate 6 changed the default for
@GeneratedValue(strategy = AUTO)and for sequence generators. - It now uses a single sequence per entity named
<table>_seqwith a defaultallocationSizeof 50. - Hibernate 5 with the legacy generator mapping used
hibernate_sequenceand an increment of 1. - The database has the old sequence with the old increment, so ids collide or the new sequence does not exist.
- Set
hibernate.id.db_structure_naming_strategy=legacyand keep the old sequence as a bridge. - Or migrate properly with a Flyway script that creates the per-entity sequences, sets their current values above the existing maximum ids, and aligns the increment with the allocation size. Then declare
@SequenceGeneratorexplicitly on each entity so the mapping never depends on a default again.
- Cause: Hibernate 6 changed the default for
- Prevention. Run the migration against a production-like database snapshot in staging with the full integration suite, and treat every Hibernate major as its own migration item with the Chapter E5 checklist.
Picture it the database objects before and after the upgrade, the rolling-deploy collision, and the queries that changed meaning.
The setup: one entity with the default generator, and one query.
@Entity
public class Order {
@Id
@GeneratedValue // strategy = AUTO: Hibernate 5 and 6 pick different sequences
private Long id;
// ...
}
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("select o from Order o where o.status = ?1") // positional parameter needs its index in Hibernate 6
List<Order> byStatus(String status);
}
Make the invisible visible: the sequence each version asks the database for.
# illustrative output
Hibernate 5 (legacy mapping) Hibernate 6 (default)
sequence asked for hibernate_sequence orders_seq
INCREMENT BY 1 50 (allocationSize)
exists in database yes, last_value = 120431 no
result ✓ nextval = 120432 ✗ ERROR: relation "orders_seq" does not exist
The trace: a rolling deploy with the legacy sequence and a new per-entity sequence that starts too low.
old pod (2.7) nextval(hibernate_sequence) -> 120432 INSERT orders id=120432 ✓
new pod (3.x) nextval(orders_seq) -> 1..50 pool of ids 1..50 allocated
INSERT orders id=1 ... id=120432 never reached, no clash yet
...ids climb to 120432 months later
INSERT orders id=120432 ✗ duplicate key value violates unique constraint "orders_pkey"
(surfaces as DataIntegrityViolationException)
What you see: the queries whose meaning changed, as concrete lines.
| JPQL or mapping | Hibernate 5 | Hibernate 6 |
|---|---|---|
where o.status = ? (no index) | accepted as legacy syntax | rejected: write ?1 |
| enum column compared with a string literal | coerced | rejected with a type mismatch |
select distinct with collection fetch and pagination | needed passDistinctThrough=false to keep DISTINCT out of the SQL | handled differently, so a projection that relied on SQL distinct can return duplicates: wrong results, no exception |
@GeneratedValue AUTO | hibernate_sequence, increment 1 | orders_seq, increment 50 |
Why: the build only proves the code compiles. Parsing rules and id-generation defaults are runtime behaviour that nothing in the compile step checks.
The fix: a Flyway migration that creates the per-entity sequence above the existing maximum, and an explicit generator.
// V20__orders_seq.sql (Flyway):
// CREATE SEQUENCE orders_seq INCREMENT BY 50 START WITH 220500; -- max(id) + margin
@Entity
public class Order {
@Id
// ✅ FIX: explicit generator, never a default
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "orders_seq")
@SequenceGenerator(name = "orders_seq", sequenceName = "orders_seq", allocationSize = 50)
private Long id;
}
// Result: ids come from orders_seq in blocks of 50, above every existing id
What you see now: the same table after the migration.
# illustrative output
Hibernate 6 with the migration
sequence asked for orders_seq
INCREMENT BY 50 (= allocationSize)
START WITH 220500 (above max(id) = 120431 plus margin)
result ✓ first id 220500, no collision with existing rows
| Symptom | Root cause | Action |
|---|---|---|
| Search returns wrong or duplicated rows, no exception | JPQL semantics changed (distinct, pagination, enum) | diff SQL old versus new, rewrite the query, test on real PostgreSQL |
| Startup or insert fails: sequence does not exist | Hibernate 6 asks for <table>_seq | Flyway creates it, or legacy naming strategy as a bridge |
| Duplicate key some weeks after deploy | new sequence started below the existing maximum id | set START WITH above max(id) plus margin |
| Works in dev, fails in staging only | dev database has a few rows | staging with a copy of production data |
Land it A Boot major migration is also a Hibernate major migration, and the query parser and id generator are where it bites after the build is green.
- "Give me a concrete query that Hibernate 5 accepted and Hibernate 6 interprets differently."
SELECT o FROM Order o WHERE o.customer.country = :cis fine in both; the ones that differ are subtler. A JPQL query with a positional parameter written as?without an index, which Hibernate 5 accepted as legacy syntax and 6 rejects: it must be?1.A
DISTINCTwith a collection fetch and pagination: Hibernate 5 neededpassDistinctThrough=falseto avoid sendingDISTINCTto SQL, 6 never sends it for entity queries and de-duplicates in memory, so a query that relied on SQL-level distinct for a projection now returns duplicates.A comparison of an enum mapped by ordinal against a string literal, which 5 coerced and 6 rejects with a type mismatch. And
@Formulaor native fragments using{alias}replacements, whose handling changed.The search endpoint in the scenario is likely the distinct-plus-pagination case, since "wrong results" rather than "an exception" is its signature.
the signature of the distinct caseruns offline# illustrative output query: select distinct o from Order o join fetch o.items (page size 10) rows in database: order 7 has 2 items, order 8 has 1 item Hibernate 5 result: [order 7, order 8] # 2 orders changed behaviour: [order 7, order 7, order 8] # a duplicate, no exception, wrong page contents- "The legacy naming strategy is a bridge. What is the migration to the proper per-entity sequences, step by step?"
Four steps, each deployable. First, keep
hibernate.id.db_structure_naming_strategy=legacyso the migrated service starts and behaves as before withhibernate_sequence.Second, a Flyway migration creates one sequence per entity table,
orders_seqand so on, eachINCREMENT BY 50, and sets each one's start value above the table's current maximum id plus a generous margin, saymax(id) + 100000, so ids from the old and new generators cannot overlap even during a rolling deploy where both versions run.Third, each entity declares
@SequenceGenerator(name = "orders_seq", sequenceName = "orders_seq", allocationSize = 50)explicitly, and the legacy property is removed; deploy. Fourth, once no old version runs, a migration dropshibernate_sequence. The pooled-lo optimizer setting makes it safer if any other application writes to those tables.Each step has a test that inserts from two contexts and asserts no collision.
- "How would you catch these before the deploy, given the build was green?"
With the suite that runs SQL against the real engine and compares behaviour, not just success.
For the query parser changes, a test per repository method that asserts on results against a fixture data set, run on PostgreSQL through Testcontainers, catches wrong results; an approval test that records each query's generated SQL under Hibernate 5 and diffs it under 6 finds every changed query in one run, and reviewing the diff is an afternoon.
For the id generator,
spring.jpa.hibernate.ddl-auto=validatefails startup when the expected sequence does not exist, and a smoke test that inserts one row per entity type catches the collision when it does exist with the wrong increment.In staging, running the migrated service against a copy of production data with production ids is what catches the "max id above the new sequence" case, because a test database with a hundred rows never will.
- "What else in Hibernate 6 or 7 tends to surface weeks later?"
Timezone handling: Hibernate 6 changed the default for
OffsetDateTimeandZonedDateTimestorage throughhibernate.timezone.default_storage, so timestamps written by the old and new versions can differ by the JVM's offset, which appears as off-by-hours bugs in reports at month end.Boolean and enum mapping defaults, so an enum column stored as ordinal by one version and name by the other after a mapping change. Batch fetching and
@BatchSizesemantics changed enough that a list endpoint's query count doubles.Hibernate 7, in Boot 4, drops some deprecated annotations such as the old
@Typeforms, makes@ManyToOnefetch defaults stricter in a few edge cases, and aligns with Jakarta Persistence 3.2, which adds features but also tightens validation of mappings at startup.The mitigation for the whole category is the query-count and SQL-diff tests from the previous answer, kept in the suite permanently.
Q138 · Design. "The billing module of a Spring Modulith monolith has to become its own service for compliance reasons. Design the extraction so that nothing breaks during the months it takes."
Reveal answer
Strong answer Assumptions: the monolith already enforces module boundaries with Modulith, billing communicates with other modules only through its public API and events, and its tables are its own. Design in phases with the monolith running throughout.
- Phase one, seal the boundary.
- Run Modulith's verification to prove no other module touches billing internals.
- Replace any remaining synchronous calls into billing with an interface in billing's API package.
- Switch other modules' calls to billing's events where they only need to react.
- Phase two, externalise events. Enable Modulith's event externalisation so the events billing consumes and publishes go through Kafka via the event publication registry, still inside the monolith, and add consumer-side idempotency. Now the interaction is already the shape it will have across processes.
- Phase three, the strangler.
- Deploy the new billing service from the same code: the billing module plus a thin Boot application around it, pointing at the billing tables in the same database initially.
- Route billing HTTP endpoints to the new service at the gateway with a percentage rollout.
- The monolith's billing module stays deployed but receives no traffic.
- Phase four, data. Move the billing tables to their own database with a dual-write or a change-data-capture cutover, then remove the monolith's access.
- Phase five, delete. Remove the module from the monolith and update the Modulith verification.
- Throughout. The same contract tests run against both the module and the service. A shared database during phases three and four is a deliberate temporary coupling, accepted to make each step reversible.
- What I would not do. Rewrite billing while extracting it, or extract the data first, because a data move with a moving codebase is where extractions die. The broader decomposition trade-offs are the subject of Chapter E7.
Picture it where the traffic, the code and the data live in each phase, and the one transaction that has to be broken first.
The setup: the shared transaction that couples orders and billing today, and its replacement.
// BEFORE: one transaction spans two modules
@Transactional
public void placeOrder(OrderRequest r) {
Order o = orders.save(toOrder(r));
billing.createInvoice(o.id()); // ❌ TRAP: billing is inside the order commit
}
// AFTER: an event, then billing reacts in its own transaction
@Transactional
public void placeOrder(OrderRequest r) {
Order o = orders.save(toOrder(r)); // o.status = AWAITING_INVOICE
events.publishEvent(new OrderPlaced(o.id())); // ✅ FIX: stored in the event publication registry
}
// in the billing module
@ApplicationModuleListener
void on(OrderPlaced e) {
invoices.createIfAbsent(e.orderId()); // idempotent on the order id
}
// Result: the order commits first; the invoice follows, so the order briefly has no invoice
Make the invisible visible: where each piece lives at three moments.
| Moment | HTTP traffic for billing | Billing code | Billing tables |
|---|---|---|---|
| After phase two | monolith, 100% | module in the monolith, events through Kafka | shared database |
| After phase three | new service 100% (gateway rollout), monolith module idle | new service and idle module | shared database |
| After phase five | new service | only in the new service | own database |
The trace: the order flow once the boundary is an event.
placeOrder() BEGIN
├─ INSERT orders (status AWAITING_INVOICE) ✓
├─ INSERT event_publication (OrderPlaced) ✓ same transaction
└─ COMMIT ✓
billing listener BEGIN (its own transaction)
├─ createIfAbsent(order 7) ✓ idempotent
└─ COMMIT ✓ order status moves on
crash before the listener finishes ✗ registry still holds the event: replayed on restart
What you see: what the verification test reports when the boundary is not sealed.
# illustrative output: ApplicationModules.of(Application.class).verify()
Violations exception:
Module 'orders' depends on non-exposed type com.example.billing.internal.InvoiceRepository
within module 'billing' (the real message names the module, the class and the type)
Why: the process split then adds only latency and a network failure mode, because every debuggable failure of the new shape was already found while everything was one process.
| Symptom | Root cause | Action |
|---|---|---|
| Verification fails naming a billing internal type | another module reaches into billing | move the call behind billing's API package or an event |
| Order exists without an invoice | invoice is now created after commit | represent AWAITING_INVOICE, fix the tests that assumed otherwise |
| Cutover goes wrong | data and code moved in one step | roll back by routing flip, change one thing per phase |
| Cross-module join found late | not a Java dependency, so verify() misses it | second datasource step and SQL review |
Land it Make the module behave like a service while it is still in-process, then move the traffic, then the data, then delete, with every step reversible.
- "The billing module shares a database transaction with orders today: an order commit and its billing record commit together. How do you break that?"
By replacing the shared transaction with an event and a state, before the process split. Today,
placeOrderwrites the order and callsbilling.createInvoicein one transaction.Phase one changes that to: the order transaction writes the order and publishes
OrderPlacedthrough Modulith's event publication registry; billing's@ApplicationModuleListenercreates the invoice in its own transaction after the order commits, idempotently on the order id.The order now exists briefly without an invoice, which is a new state the order module has to represent, for instance
AWAITING_INVOICE, and any code that assumed the invoice existed immediately after placing an order is found by the tests that now fail.That is the hard part of the extraction, and doing it while everything is still one process means the failures are debuggable locally. Once this holds, the process boundary adds only latency and a network failure mode, which the registry's replay already covers.
- "Compliance says billing data must be in a separate database from day one of the new service. Does that force a different order?"
It forces the data move earlier but not first.
The order becomes: seal the boundary, externalise events, and then move the data while the code is still in the monolith, using the monolith's billing module pointed at a second datasource with its own transaction manager, which Modulith supports and which proves that no cross-module query or join exists, because any such query fails immediately.
Only after the module runs against its own database inside the monolith do I deploy it as a separate service, which is then a pure process split with no data change.
The dual-write or CDC cutover for the tables happens during the "second datasource" step, with the module reading from the new database and a reconciliation job comparing both for a week.
The principle stays: change one thing per phase, and never move code and data in the same step.
- "What would you cut under time pressure?"
The percentage rollout at the gateway, and the strangler period.
If the module is already sealed and its events are externalised, the new service can be cut over in one switch during a maintenance window with the monolith's module left deployed but idle as the rollback, and that saves the gateway routing work and the weeks of dual operation.
The cost is a bigger blast radius on cutover day, which is acceptable if the contract tests pass against both and the rollback is a routing flip.
I would not cut the contract tests or the event externalisation, because those are what make the cutover reversible; and I would not cut the shared database phase in favour of moving the data at the same time, because that is the step where a failed cutover cannot be undone cleanly.
The month I would save is the dual-running month; the month I would not save is the boundary-sealing month.
- "How does Modulith's verification actually check the boundary, and what does it miss?"
ApplicationModules.of(Application.class).verify()builds a model where each direct sub-package of the application package is a module, its top-level package is its API, and nested packages are internal; then it uses ArchUnit to assert that no class in one module depends on an internal package of another, that dependencies declared with@ApplicationModule(allowedDependencies = ...)are respected, and that there are no cycles.It runs as a unit test and fails naming the offending class and dependency.
What it misses is anything not expressed as a Java dependency: a JPQL query in orders joining a billing entity by name, a native SQL query touching billing's tables, a shared database sequence, a Spring bean looked up by name from the context, and reflection.
Those are found by the second-datasource step, by a SQL-level review of native queries, and by grepping for billing table names outside the billing module.
Q139. "How is logging wired in Boot, what does structured logging add, and what do you change for production?"
Reveal answer
Strong answer How logging is wired:
- Facade and implementation. SLF4J is the facade, Logback the default implementation, and Log4j2 a swap-in through its starter.
- Bridges. Boot routes JUL and Log4j 1 calls into SLF4J so libraries end up in the same pipeline.
- Configuration. Properties for the common case:
logging.level.<logger>,logging.pattern.console,logging.file.name.logback-spring.xmlwhen you need appenders and profiles, with Boot's<springProfile>and<springProperty>tags. - Runtime levels. The Actuator
loggersendpoint changes levels without a restart, which is the tool for turning on DEBUG for one package during an incident.
Structured logging, since Boot 3.4:
- One property:
logging.structured.format.console=ecs(Elastic Common Schema),logstash, orgelf. - It emits one JSON object per line with timestamp, level, logger, message, thread, and the MDC including
traceIdandspanId. - Key-value pairs added through SLF4J's fluent API appear as fields too:
log.atInfo().addKeyValue("orderId", id).log("placed"). - Log pipelines then index fields instead of parsing patterns.
For production:
- JSON to stdout only, no files, since the platform collects stdout.
- INFO by default with WARN for chatty libraries.
- An
AsyncAppenderonly if the console appender is measured to block, and withneverBlock=trueif so. - A hard rule against logging request bodies, tokens, or personal data, enforced with a masking converter.
- A per-request log line rather than per-step lines, with everything else at DEBUG.
- Set
logging.exception-conversion-word=%wEx{short}or a truncation so a stack trace is not 200 lines per error under load.
# Boot 3.4+ ships structured logging with no extra dependency.
# Human-readable locally:
# logging.structured.format.console = (unset)
# ❌ TRAP: in production this leaves free-text lines that must be regex-parsed.
# One JSON object per line in production, so the log platform can index fields
# instead of regex-parsing a message.
# ✅ FIX: structured JSON on stdout.
logging.structured.format.console = ecs # or logstash / gelf
# Result: one JSON object per line, traceId and spanId included.
logging.structured.json.customizer = com.example.LogCustomizer
# Correlation: Boot puts traceId and spanId in the MDC automatically when
# Micrometer Tracing is present, so every line joins to a trace.
logging.pattern.correlation = "[${spring.application.name:},%X{traceId:-},%X{spanId:-}] "
logging.level.root = INFO
logging.level.org.springframework.web = INFO
logging.level.com.example.orders = DEBUG
<!-- ❌ TRAP: synchronous appenders block the request thread on every log line.
Under load, Tomcat threads pile up inside Logback rather than in your code. -->
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
</appender>
<!-- Hand off to a background thread with a bounded queue. -->
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="CONSOLE"/>
<queueSize>8192</queueSize>
<!-- 0 = never block the application thread; drop instead.
The default (20) DISCARDS INFO/DEBUG when the queue is 20% full,
which is usually what you want under load. -->
<discardingThreshold>20</discardingThreshold>
<!-- ✅ FIX: neverBlock=true. Result: a slow destination drops lines instead of adding latency. -->
<neverBlock>true</neverBlock>
</appender>
<root level="INFO"><appender-ref ref="ASYNC"/></root>
</configuration>
neverBlock is the decision that matters. With it false, a slow log destination applies backpressure straight into your request threads; with it true you lose log lines under extreme load and keep serving traffic — and for most services that is the right trade.
Picture it one log call written as a pattern line and as a JSON line, plus the runtime level change.
The setup: one call in the order service, using the fluent API, running inside a traced request.
log.atInfo()
.addKeyValue("orderId", id)
.log("placed");
Make the invisible visible: the path a call takes before it reaches stdout.
log.atInfo()... SLF4J (facade)
└─► Logback default implementation
├─ MDC traceId, spanId (put there by Micrometer Tracing)
├─ key-value pairs orderId=42
└─ encoder pattern text, or JSON when logging.structured.format.console is set
└─► stdout the platform collects it
What you see: the same event, unstructured and structured.
# illustrative output
2026-08-03T12:00:00.412Z INFO 1 --- [orders] [nio-8080-exec-3] c.example.orders.OrderService : placed
# illustrative output: logging.structured.format.console=logstash
{"@timestamp":"2026-08-03T12:00:00.412Z","message":"placed","logger_name":"com.example.orders.OrderService",
"thread_name":"http-nio-8080-exec-3","level":"INFO","traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"00f067aa0ba902b7","orderId":"42"}
# the ecs format renames and nests these keys (log.level, and so on)
Why: a pipeline can filter on orderId or join on traceId without a regex that breaks when someone edits the message.
The runtime change: DEBUG for one package, then back, with no restart.
curl -X POST localhost:9090/actuator/loggers/com.example.orders \
-H 'Content-Type: application/json' -d '{"configuredLevel":"DEBUG"}' # 204 No Content
curl -X POST localhost:9090/actuator/loggers/com.example.orders \
-H 'Content-Type: application/json' -d '{"configuredLevel":null}' # back to the configured level
| Change | Effect |
|---|---|
logging.structured.format.console=ecs | one JSON object per line, fields indexed by the pipeline |
neverBlock=true on the async appender | a slow log destination cannot stall request threads, some lines may be dropped |
%wEx{short} | shorter stack trace per error |
| no bodies, tokens or personal data in any line | nothing sensitive reaches the log platform |
Land it SLF4J over Logback, JSON to stdout with the trace id inside, levels changeable at runtime, and a firm rule about what never gets logged.
- "How does the traceId reach the MDC, and why does it sometimes go missing on async work?"
Micrometer Tracing installs a
Slf4JEventListeneror the equivalent bridge that, whenever a span becomes current on a thread, putstraceIdandspanIdinto SLF4J's MDC, and removes them when the span scope closes; Boot's default log pattern and the structured formats then include those keys.The MDC is a
ThreadLocal, so work on another thread starts with an empty MDC unless something copies it.Boot's task executors do so when the context-propagation library is present and the executor is built with the propagating decorator; a raw
ExecutorService, a parallel stream, or aCompletableFutureon the common pool loses it.The fix is the same as for observations in Q124: use the configured executors or wrap with
ContextSnapshot. A quick check in any service is to log inside an@Asyncmethod and see whether the trace id appears; if not, the executor is not propagating.- "What goes into the one line per request, and how do you keep it from becoming a privacy problem?"
The line is written by a filter or by the observation's completion: method, route template rather than raw path, status, duration in milliseconds, outcome, the authenticated principal's id rather than name, the client's request id if it sent one, and the trace id from the MDC, plus one or two business identifiers that are not personal data, such as an order id.
It excludes query strings, which may carry tokens, headers, bodies, and anything free-text. As structured JSON, each of those is a field, so the log pipeline can index and aggregate without regex.
The privacy control is an allow list: the fields are enumerated in code, and a test asserts the line contains only those keys.
For the error path, the same line carries the error reference from Q76 and the exception class, and the stack trace goes to a separate ERROR line with the same trace id, throttled so a repeating error does not produce a thousand traces a second.
- "Why not Log4j2 with its async loggers, which are faster?"
Log4j2's async loggers on the LMAX Disruptor are faster at high volume, and if logging throughput is a measured bottleneck they are a valid choice, with Boot's
spring-boot-starter-log4j2after excluding Logback.The reasons Logback stays the default and my default: it is what Boot configures and tests first, most teams know it, its structured logging support in Boot is first-class, and for a service logging one line per request the throughput difference is not measurable, since the bottleneck is the stdout consumer, not the framework.
Log4j2 also carries the memory of the 2021 remote-code-execution vulnerability, which is not a technical argument against the current version but is a reason some organisations restrict it.
If I switch, it is for a proven reason such as a logging-heavy batch service, and I keep the same structured format so the pipeline does not care.
- "How do you add custom fields to structured log output, and how would a team standardise them?"
Three mechanisms, in order of reach. Per line, SLF4J 2's fluent API:
log.atInfo().addKeyValue("orderId", id).log("order placed"), which Boot's structured formats render as top-level JSON fields.Per request or per thread, the MDC: a filter puts
tenantandprincipalIdinto the MDC at the start and clears it at the end, and every line in between carries them.Globally, a
StructuredLogFormattercustomisation or, in Boot 3.4 and later, aStructuredLoggingJsonMembersCustomizerbean that adds fields such as service name, version, and region to every line from the build info and the environment.Standardisation is a small platform library that provides the filter, the customiser, and a set of constants for field names, so
orderIdis spelled the same in forty services and the log pipeline's dashboards work across all of them.
Q140 · Scenario. "Under load, request latency rises in lockstep with log volume, and a thread dump shows most Tomcat threads inside Logback's console appender. Diagnose and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom. Request threads blocked in logging.
- Logback's
ConsoleAppenderis synchronous and takes a lock per event while writing to stdout. - So 200 threads each logging several lines per request serialise on that lock and on the speed of whatever reads the pipe.
- Logback's
- Evidence.
- The thread dump, with threads in
OutputStreamAppender.writeBytes. - The log line rate per second.
- The container runtime's log driver: Docker's json-file driver and Kubernetes' log rotation can make stdout writes slow when the reader falls behind.
- The thread dump, with threads in
- Likely causes, ranked.
- Excessive per-request logging, for example DEBUG left on for a package or a log line per SQL statement.
- Large stack traces on every expected error such as validation failures.
- A slow stdout consumer, such as a log agent that is CPU-throttled.
- A synchronous appender with an expensive layout, like a pattern with caller data (
%C,%L), which forces a stack walk per line.
- Fix, in order.
- Cut the volume: raise levels and remove per-step lines so a request logs once.
- Stop logging stack traces for client errors, and remove caller-data patterns.
- If still blocking, wrap the console appender in an
AsyncAppenderwith a bounded queue,neverBlock=true, and a discarding threshold, accepting that under extreme pressure DEBUG lines are dropped rather than latency added. - Give the log agent enough CPU, and measure with a counter of dropped events.
- Prevention. A log volume budget per service on the dashboard, and a load test that includes error paths so the logging cost of failures is known.
Picture it the thread dump with every request thread queued on one lock, the metrics at three moments, and the same service after the fix.
Make the invisible visible: one thread holds the appender lock and writes to a slow pipe, and the other threads park behind it.
# illustrative output
"http-nio-8080-exec-17" BLOCKED / WAITING (queued for the appender lock)
at ch.qos.logback.core.OutputStreamAppender.subAppend
at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend
at com.example.orders.OrderController.place
"http-nio-8080-exec-3" RUNNABLE (holds the lock, writing to stdout)
at java.io.FileOutputStream.writeBytes
at ch.qos.logback.core.OutputStreamAppender.writeBytes
(... 187 more request threads in the first state, 12 in the second)
The trace: one request.
request thread ──► controller.place()
├─ log.info("received") ✗ waits for the appender lock
├─ service work (3 ms) ✓
└─ log.info("done") ✗ waits again; latency = work + queueing for the pipe
What you see: the numbers at three moments.
| Moment | Log lines per second | Tomcat busy threads | Hikari active / pending | CPU | p99 latency | Error rate |
|---|---|---|---|---|---|---|
| A. normal | 800 | 24 / 200 | 3 / 0 | 35% | 80 ms | 0.1% |
| B. incident, DEBUG on a package | 9 000 | 200 / 200 | 3 / 0 (not the database) | 40% | 2.4 s | 4% |
| C. after: volume cut, async appender | 1 200 | 28 / 200 | 3 / 0 | 36% | 85 ms | 0.1% |
Why: logging is a blocking write on the request thread, and the rate of lines had outrun what the pipe behind stdout could absorb.
The fix: the async appender with neverBlock is the one in the XML block under Q139, after the volume has been cut.
What you see now: row C above, plus the dropped-event counter.
# illustrative output
logback dropped events (counter): 0 at normal load
non-zero only during a real storm, and visible on the dashboard
| Symptom | Root cause | Action |
|---|---|---|
Threads in OutputStreamAppender in the dump, latency tracks line rate | synchronous console appender, too many lines | cut volume first, then async appender with neverBlock |
| Hikari pending stays 0 while threads are all busy | the wait is not the database | look at logging, not the pool |
| Stack traces for validation errors in the log | expected errors logged as failures | log client errors as one line, no trace |
| Log agent CPU at its limit, node log file lagging | slow reader | more CPU for the agent, rotation settings, lower volume |
Land it Logging is I/O on the request thread, so first log less, then make what remains asynchronous and droppable rather than blocking.
- "How do you measure how much time requests actually spend in logging?"
With a profiler rather than a guess.
Async-profiler in wall-clock mode for 30 seconds on one pod, or JFR with the
jdk.JavaMonitorEnterand thread-park events, shows the fraction of request-thread time insideOutputStreamAppender.doAppendand the lock contention on the appender; if it is more than a few percent, logging is a latency contributor.A cheaper ongoing number is a Micrometer timer around the request-logging filter, which captures the cost of the per-request line specifically.
And a system-level view: the log rate in lines per second from the log agent versus latency p99 on the same graph, which in the scenario move together.
After the fix, the same profile should show logging under one percent, and the dropped-event counter from the async appender should be zero at normal load and non-zero only during a real storm.
profile before and afterruns offline# illustrative output: share of request-thread time by frame before: 31% ch.qos.logback.core.OutputStreamAppender.subAppend (lock wait + write) 52% application code after: <1% ch.qos.logback.classic.AsyncAppender.append (queue offer) 88% application code- "What are the exact AsyncAppender settings you would use, and what does each protect against?"
In
logback-spring.xml:<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">withqueueSizeof 8192, which bounds memory to a few megabytes of events;discardingThresholdof 0, so nothing is discarded until the queue is actually full, or the default of 20 percent remaining, which starts dropping TRACE through INFO early to keep room for WARN and ERROR;neverBlocktrue, so when the queue is full the calling thread drops the event instead of waiting, which is the property that protects request latency;includeCallerDatafalse, because caller data is the expensive stack walk; andmaxFlushTimeof 1000 milliseconds, so shutdown waits at most a second to drain.It wraps the console appender. Logback's LoggingEventVsLogEvent asynchronous path in Logback 1.5 also allows a virtual-thread writer. The trade-off is explicit: under overload, some INFO lines are lost, and the dropped count is a metric.
- "The container's log driver is the slow reader. What can you do about that side?"
First confirm it: on the node, the container runtime's log file for the pod grows, and the log agent's own metrics show its read lag or its CPU throttling.
Fixes on that side: give the log agent, whether Fluent Bit or Vector, enough CPU and a request that is not throttled; enable the runtime's log rotation with a size that does not force frequent rotation, since rotation stalls the writer; and reduce the volume at the source, which is still the biggest lever.
An alternative that removes the pipe entirely is having the application ship logs itself, for example through an OTLP log exporter from Micrometer's or OpenTelemetry's SDK to the collector over the network, which has its own bounded queue and drop policy and does not block on stdout; Boot 3.4 and later support OTLP log export.
That moves the back-pressure into a place the application controls, at the cost of a second path to operate.
- "How do you keep DEBUG from being left on in production again?"
Two guards.
First, make the runtime change temporary: DEBUG is enabled through the Actuator
loggersendpoint on one pod, which reverts on restart, and a small scheduled task or an operator runbook resets any non-default logger level after 30 minutes; a metric exposing the count of loggers at DEBUG or TRACE is on the dashboard and alerts if it stays non-zero.Second, make the configuration change visible: the production overlay's
logging.level.*keys are in the reviewed manifest, and a policy check in the pipeline fails a change that sets any package below INFO in production without an approval label.A log-volume budget alert, lines per second per pod above a threshold, catches whatever both miss. The organisational part is a runbook that says how to get DEBUG for one package on one pod for one incident, so people do not reach for the global setting.
Q141 · Design. "Design what has to be true of a Boot service before it can run active-active in two regions behind a global load balancer."
Reveal answer
Strong answer Assumptions: the database question is answered separately, either a multi-region database with defined consistency or region-local databases with replication. This design covers the service's obligations.
- Statelessness. No HTTP sessions, or Spring Session on a store that is itself replicated. No local caches used as a source of truth, only as accelerators with TTLs. No in-memory rate limiters or locks.
- Idempotency. Every write endpoint accepts an idempotency key as in Q48, because a client failing over between regions will retry across them.
- Identity. Ids generated without coordination, UUIDv7 or a region-prefixed sequence, never database auto-increment shared across regions.
- Configuration. Region as a property,
app.region, injected from the environment and stamped on every metric, log, and span so cross-region comparison is possible. Feature flags evaluated identically in both. - Data access.
- Reads tolerate replication lag, with read-your-writes handled by routing a user's requests to the region that wrote for a short window, or by version checks.
- Writes go to the region-local primary or to the global primary with the latency accepted, chosen per aggregate.
- Messaging. Kafka topics with cross-region mirroring and consumer groups per region, with consumers idempotent on message id so mirrored duplicates are harmless.
- Scheduling. Fleet-wide jobs elected in one region via a distributed lock in a global store, or partitioned by region.
- Health and failover. Readiness reflects region-local dependencies only, so a failure of the other region does not take this one down. A regional kill switch exists to drain a region deliberately.
- Testing. Chaos runs that fail one region and verify the other serves.
- Trade-offs. Everything above adds a little latency and a lot of discipline. Active-passive is cheaper if the availability target allows a few minutes of failover.
- What I would not do. Run active-active with sticky sessions and hope, or let two regions both run the reconciliation. The consistency models behind these choices are the Distributed Systems primer.
Picture it what each region carries at three moments, one write that fails over, and a service property per row of the decision table.
The setup: region as a property, stamped on every metric, and the idempotency key on a write.
// application.properties
// app.region=${REGION} # eu-west or us-east, from the environment
// management.metrics.tags.region=${app.region} # every metric carries the region
@PostMapping("/payments")
public ResponseEntity<Payment> pay(@RequestHeader("Idempotency-Key") String key,
@RequestBody PaymentRequest r) {
// ✅ FIX: a client that fails over and retries in the other region hits the same key
return ResponseEntity.ok(payments.payOnce(key, r));
}
Make the invisible visible: what each region carries at three moments.
| Moment | Region A | Region B | Replication lag A to B | What the user sees |
|---|---|---|---|---|
| 1. normal | 1 200 req/s, 40% of capacity | 1 200 req/s, 40% | 60 ms | normal |
| 2. region A lost | 0 req/s | 2 400 req/s, 80% of capacity | n/a | a few retries, no data loss for idempotent writes |
| 3. A back, resyncing | 600 req/s, ramping | 1 800 req/s | lag 4 s, falling to 60 ms | reads may be briefly stale: read-your-writes covers the writer |
The trace: one write that fails over mid-flight.
client ──► region A POST /payments key=abc ✓ committed in A
✗ region A fails before the response arrives
client ──► region B POST /payments key=abc (retry)
payOnce(abc): key not seen in B yet? replication lag decides
✓ seen: returns the stored result
✗ not yet: second payment, unless the key table is global or checked in A
What you see: metrics tagged by region make the comparison possible.
# illustrative output
http_server_requests_seconds_count{region="eu-west", uri="/payments"} 1200
http_server_requests_seconds_count{region="us-east", uri="/payments"} 1198
replication_lag_seconds{from="eu-west", to="us-east"} 0.06
Why: a region that fails over to the other one is the same as a pod that fails over to another pod: anything held in the first and not in the second is lost.
| Symptom | Root cause | Action |
|---|---|---|
| Customer sees logged out after failover | HTTP session in local memory | stateless tokens, or Spring Session on a replicated store |
| Duplicate payment after retry in the other region | idempotency key stored region-locally | global key store, or key checked on the home region |
| Id collision between regions | shared auto-increment | UUIDv7 or region-prefixed sequence |
| Two settlement files at midnight | job runs in both regions | ShedLock on a global store, or partition by region |
| Region B goes unready when region A is down | readiness includes a cross-region dependency | region-local checks only |
Land it Active-active is a property of the service's statelessness, idempotency, id generation, and region-aware routing, and each of those has to be built in before the balancer is switched.
- "The requirement changes: writes must be strongly consistent for accounts but eventually consistent for everything else. What changes in your design?"
I would split the service's data by aggregate and route writes differently for each.
Account writes go to a single global primary, or to the region that owns that account by a deterministic home-region rule, and the other region forwards account writes across the link, accepting the extra 60 to 100 milliseconds per call.
Everything else stays region-local with asynchronous replication. In code that means two
DataSourcebeans, or one routing data source keyed by aggregate, and a clear package boundary so nobody accidentally joins an account row with a region-local row in one transaction.The home-region rule is stored with the account and stamped on the JWT so the global balancer can route the user to the right region most of the time, making the forwarded path the exception.
I would put a metric on forwarded writes so a routing bug shows up as a rising counter.
routing by aggregateruns offlinewrite to account 77 home region = eu-west from eu-west ──► global primary (or local home) ✓ local, a few ms from us-east ──► forward to eu-west ✓ +60 to 100 ms write to cart 12 region-local, async replication ✓ no forwarding # metric: app.writes.forwarded{from="us-east"} rising means a routing bug- "How would you verify in production that the service really is stateless before you switch the balancer?"
I would prove it with traffic, not by reading code.
In a single region, I would set the load balancer to no affinity and a short DNS TTL, then run a synthetic user journey that spans several requests, login, add to cart, checkout, while killing pods mid-journey and rotating requests between pods.
Any failure that depends on which pod served the previous request is state.
I would also grep the codebase and the classpath for
HttpSession,spring-session,ConcurrentHashMapandCaffeineused as a source of truth, and forsynchronizedorReentrantLockguarding cross-request invariants, because those are the usual leaks.Finally I would inspect the heap of a pod after an hour of traffic with a histogram from
jcmd GC.class_histogram; a growing map keyed by user or session id is state hiding as a cache.- "Both regions run the nightly reconciliation job. What actually goes wrong, and how do you stop it?"
Two runs of the same job produce double side effects: two emails, two settlement files, or a counter incremented twice, and if they write the same rows they can deadlock or overwrite each other's results.
I would elect one runner with a lease in a store both regions see.
ShedLock with a JDBC or Redis provider is the usual choice:
@SchedulerLock(name = "reconcile", lockAtMostFor = "PT30M")so a crashed runner's lock expires, andlockAtLeastForso clock skew cannot let the other region start early.The lock table must live in the global database, not a region-local one, or you have two locks.
As a second defence the job itself is idempotent: it writes a run record keyed by date and skips work already marked done, so a duplicate run costs a query rather than a double payment.
- "What does active-active cost compared to active-passive, and when is it not worth it?"
Roughly double the compute since each region must carry full load alone during a failover, a cross-region data path that adds latency and a replication bill, and engineering time for idempotency, coordination-free ids and region-aware routing that active-passive never needs.
The biggest hidden cost is testing: every release needs a chaos check that one region can serve alone.
It is not worth it when the availability target allows a few minutes of failover, which is most internal and many customer-facing services; an active-passive setup with a warm standby and a rehearsed failover runbook reaches four nines in practice.
Active-active is earned by a requirement to survive a region loss with no visible blip, or by latency needs where users on two continents must each hit a nearby region for writes.
- "A user writes in region A, fails over, and reads stale data in region B. Walk me through your read-your-writes mechanism concretely."
The write response returns a version token, either the row version or the replication position such as the Postgres LSN after commit, and the client sends it back as a header on subsequent reads.
A filter in region B compares the token with the replica's applied position; if the replica is behind, it either waits up to a bounded time, say 200 milliseconds, or forwards the read to region A, or returns the write response's copy of the entity from a short-lived cache.
The cheap version is a cookie set on write that pins the user to region A for 30 seconds through the global balancer's routing rule.
I would measure how often the wait or forward path triggers, because if replication lag is normally 50 milliseconds the mechanism fires rarely and its cost is negligible, and if it fires constantly the replication link is the problem.
Q142 · Scenario. "New pods serve their first two minutes of traffic at 3x the latency of old pods, which trips the SLO alert on every scale-out. Diagnose and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom. Latency correlated with pod age, recovering on its own. That is warm-up:
- the JIT has not compiled hot paths;
- caches are empty and connection pools are cold;
- class loading is still happening on first use.
- Evidence.
jvm.compilation.timerising during the window, andjvm.classes.loadedclimbing.- Cache hit rate near zero, and Hikari creating connections.
- If CPU limits are tight, throttling metrics spiking, because JIT compilation competes with request handling for the CPU quota.
- Causes, ranked.
- Interpretation and tier-1 compilation for the first thousands of invocations.
- CPU throttling extending the compile phase.
- Cold local caches.
- Lazy first-use initialisation of Hibernate metamodel pieces, Jackson serialisers, and validators.
- Readiness flipping before any of this has happened.
- Fix.
- A warm-up phase before readiness: an
ApplicationRunnerthat exercises the top endpoints a few hundred times throughMockMvcor a loopbackRestClientwith representative payloads, so serialisers, queries, and hot paths compile before the first real request. - The JDK AOT cache or CDS archive to cut class loading and let the JVM start with pre-linked classes. On Java 25 the AOT cache also stores profiling data so compilation starts warmer.
minimum-idleequal to the pool size so connections exist at start.- A higher CPU limit, or no limit with a request set, since throttling during warm-up is a false economy.
- A slow-start setting at the load balancer that ramps traffic to a new pod over 60 seconds.
- Exclude pods younger than two minutes from the SLO alert only if warm-up cannot be fixed, which it can.
- A warm-up phase before readiness: an
- Prevention. Latency by pod age as a dashboard panel, and a startup budget that includes warm-up.
Picture it a new pod's first two minutes in numbers, with and without a warm-up runner.
The setup: a warm-up runner that calls the service through its own port before readiness can flip.
@Component
class WarmUpRunner implements ApplicationRunner {
private final RestClient client;
WarmUpRunner(RestClient.Builder builder, @Value("${local.server.port}") int port) {
this.client = builder.baseUrl("http://localhost:" + port).build();
}
@Override
public void run(ApplicationArguments args) {
// ✅ FIX: hot paths compile before the first real request.
for (int i = 0; i < 300; i++) {
client.get().uri("/orders/search?q=sample-" + (i % 20)).retrieve().toBodilessEntity();
}
// Result: serialisers, queries and validators are loaded and compiled when readiness flips.
}
}
Make the invisible visible: what is cold in a fresh JVM.
JIT interpreted code and tier-1 (C1) code; hot paths not yet C2-compiled
class loading classes loaded lazily on first use (Jackson, Hibernate, validators)
caches empty, hit rate near 0
Hikari connections created on demand
CPU quota shared between request threads and the compiler threads
The trace: a request on a young pod.
readiness flips ──► load balancer sends traffic at full weight
request 1 ──► Jackson serialiser built on first use ✗ slow
──► Hibernate metamodel pieces initialised ✗ slow
──► query runs, cache miss ✗ slow
request 2000──► same code, compiled and cached ✓ fast
What you see: the same service at three pod ages.
| Pod age | p99 latency | JIT compile time rate | Cache hit rate | CPU throttled | Hikari active |
|---|---|---|---|---|---|
| 0 to 30 s | 900 ms | high | 2% | 45% of periods | 2 of 10 |
| 60 to 120 s | 420 ms | falling | 40% | 20% | 6 of 10 |
| over 5 min | 140 ms | low | 88% | 1% | 6 of 10 |
Why: the JVM optimises what it has seen, so the first real requests pay for compilation, class loading and empty caches while competing for a limited CPU quota.
What you see now: the same table after the warm-up runner, a higher CPU limit and a short slow-start window.
| Pod age | p99 latency | JIT compile time rate | Cache hit rate | CPU throttled | Hikari active |
|---|---|---|---|---|---|
| 0 to 30 s | 190 ms | low | 60% | 2% | 10 of 10 (minimum-idle) |
| 60 to 120 s | 150 ms | low | 80% | 1% | 6 of 10 |
| over 5 min | 140 ms | low | 88% | 1% | 6 of 10 |
| Symptom | Root cause | Action |
|---|---|---|
| Slow only in the first minutes of a pod's life | JIT, class loading and cold caches | warm-up runner before readiness, AOT cache |
| Throttled seconds spike at startup | CPU quota shared with compiler threads | raise the limit or drop it and keep a request |
| Alert still fires after the warm-up runner | warm-up too small a payload, or readiness earlier than the runner | check the order, warm up realistic payloads |
| Old pods saturated during a scale-out | slow start ramp too long or scaling too late | short ramp, scale earlier |
Land it A JVM is slow until it has seen traffic, so give it synthetic traffic before readiness and pre-linked classes at start, and ramp real traffic in.
- "You added the warm-up runner and the alert still fires on scale-out. What next?"
First I check that the warm-up actually ran before readiness, because an
ApplicationRunnerruns after the context is refreshed and readiness flips at about the same moment unless the runner completes first; Boot setsReadinessState.ACCEPTING_TRAFFIConly after runners finish, so if readiness is served by a separate endpoint or the probe hits before the runner ends, traffic arrives early.Then I check what the warm-up exercised: if it hit an endpoint through MockMvc with a tiny payload, the JIT compiled the small-payload path and the real serialiser branches are still cold.
Then CPU throttling, with
container_cpu_cfs_throttled_seconds_total, because a throttled pod compiles slowly no matter how much warm-up you send. Finally the dependency side: a new pod's first calls to a downstream service establish TLS sessions and DNS lookups, so I would pre-open the HTTP client's connections too.checking the orderruns offline# illustrative output 12:00:03.1 context refreshed 12:00:03.4 WarmUpRunner started # ApplicationRunner phase 12:00:09.8 WarmUpRunner finished: 300 requests 12:00:09.9 readiness state: ACCEPTING_TRAFFIC # must come AFTER the runner line # if the readiness line comes first, the probe or a separate endpoint is racing the runner- "Why does CPU throttling make warm-up so much worse than it makes steady state?"
Kubernetes CPU limits use CFS quota, which gives the container a fixed slice of CPU time per 100-millisecond period.
During warm-up the JVM is running C1 and C2 compiler threads, class loading, and GC alongside request threads, so demand is far above the limit and the container spends much of each period throttled, which shows up as request latency in bursts.
In steady state the compiler threads are idle and demand fits the quota. The practical numbers: a pod limited to one CPU with two compiler threads can take three to five times longer to finish compiling its hot paths than the same pod unlimited.
I would set a request without a limit for JVM services where the node allows it, or a limit at least twice the request, and I would confirm the change by watching the throttled-seconds metric drop to near zero after startup.
- "What does the AOT cache actually store, and how do you produce it in a container build?"
The AOT cache, as of Aug 2026 on Java 24 and 25 via JEP 483 and 515, is a file that stores pre-parsed and pre-linked classes plus, on 25, method profiling data from a training run, so the JVM starts with classes loaded and the JIT knows which methods are hot.
Boot supports it through the buildpack or a two-stage Dockerfile: run the application once with
-XX:AOTMode=record -XX:AOTConfiguration=app.aotconfunder representative traffic, then-XX:AOTMode=create -XX:AOTCache=app.aot, then start production with-XX:AOTCache=app.aot.The cache must match the exact JDK build and classpath, so it is produced in the image build, not copied between versions. The older CDS route is
-XX:ArchiveClassesAtExitand works on Java 17.Typical gains are 30 to 50 percent on startup and a warmer first minute, which I would verify by comparing p99 by pod age before and after.
- "How does slow start work at the load balancer, and what is the risk?"
Slow start ramps the weight of a new backend linearly from a small fraction to full over a window.
In Envoy and Istio it is
slowStartWindowon the destination rule; in NGINX ingress it is theslow_startparameter on the upstream; Kubernetes Services alone do not support it because kube-proxy balances at connection level.The risk is during a rapid scale-out: if half the fleet is new and all of it is ramping, the old pods take most of the load during the window and can themselves become saturated, so the ramp should be short, 30 to 60 seconds, and the autoscaler should scale earlier rather than in one large step.
With a warm-up runner in place slow start becomes a belt-and-braces measure, and I would keep it only if the latency-by-age panel still shows a bump.
- "How would you build the latency-by-pod-age panel?"
The metric needs a tag it does not have by default. I would register a
MeterFilterthat adds apod_age_buckettag tohttp.server.requests, computed from the pod's start time into buckets like under one minute, one to five, over five. The start time isManagementFactory.getRuntimeMXBean().getStartTime().With the tag in place, the panel is a p99 of the request timer grouped by the bucket.
An alternative that needs no code is joining in PromQL on
kube_pod_start_timefrom kube-state-metrics with the per-pod latency series, but that only works if the request metric carries the pod label, which it does under the Prometheus operator's default relabelling.The panel exists so warm-up regressions show up as a change in the young-bucket line rather than as a mystery in the aggregate.
Q143 · Design. "Design load shedding for a Boot API so that when it is overloaded it stays fast for the requests it accepts and rejects the rest cheaply."
Reveal answer
Strong answer Requirements: detect overload from the service's own signals, reject before doing expensive work, prefer important traffic, and tell clients how to back off. Design: an early servlet filter, ordered before Security, that decides admit or reject in microseconds.
- The signal. In-flight concurrency: an
AtomicIntegerincremented on entry and decremented in afinally, compared with a limit.- A static limit derived from Q45's arithmetic is the simple version.
- An adaptive limit using a gradient or Vegas-style algorithm, as in Netflix's concurrency-limits library, adjusts the limit from measured latency so it tracks the real capacity as dependencies slow down.
- Priority. The filter reads a cheap classifier, a header set by the gateway or a path prefix, and applies tiered limits. Checkout has a higher limit than product search, and health checks are never shed.
- Rejection. An immediate 503 with
Retry-After: 1and a ProblemDetail, written by the filter without touching the thread pool beyond the filter itself. Because rejection is cheap, the service can refuse thousands per second while serving its full capacity. - Queueing. A short bounded wait, 50 milliseconds, before rejecting smooths micro-bursts, but never a long queue, since a queued request is one the client has probably abandoned.
- Below the filter. The same principle at each resource: Hikari with a 2-second checkout timeout, bulkheads per dependency, and Tomcat's
accept-countkept small so overload is visible as fast 503s rather than slow timeouts. - Scaling and observability. Kubernetes autoscaling on in-flight count or on a latency metric adds capacity while shedding protects the existing pods. A counter of shed requests by tier is also the autoscaler's early signal.
- Trade-offs. Adaptive limits can oscillate and need tuning. A static limit is wrong when dependencies change speed.
- What I would not do. Shed at the controller after parsing and authentication, or use the thread pool's rejection as the shedding mechanism, because by then the cost has been paid.
Picture it the filter at the front door, the service at three load levels, and the numbers a load test must show.
The setup: a static in-flight limit in a filter ordered before Spring Security.
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 10) // before the Security filter chain
class ShedFilter extends OncePerRequestFilter {
private final AtomicInteger inFlight = new AtomicInteger();
private final int limit;
ShedFilter(@Value("${app.shed.limit:200}") int limit) { this.limit = limit; }
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
if (req.getRequestURI().startsWith("/actuator")) { chain.doFilter(req, res); return; } // never shed health
if (inFlight.incrementAndGet() > limit) {
inFlight.decrementAndGet();
// ✅ FIX: reject in microseconds, tell the client to back off
res.setStatus(503);
res.setHeader("Retry-After", "1");
res.setContentType("application/problem+json");
res.getWriter().write("{\"title\":\"Overloaded\",\"status\":503}");
return; // Result: no auth, no parsing, no controller
}
try { chain.doFilter(req, res); } finally { inFlight.decrementAndGet(); }
}
}
The trace: a request at the front door.
request ──► ShedFilter (order before Security)
inFlight = 200, limit = 200
├─ over the limit ──► 503 + Retry-After: 1 ✓ about 0.3 ms, cost paid: none
└─ under the limit ──► Security ──► controller ──► service ✓ admitted
shed at the controller instead: ✗ authentication, parsing and a thread already spent
What you see: the service at three load levels, offered load against a limit of 200 in flight.
| Moment | Offered load | In flight | Tomcat busy threads | Hikari pending | 2xx p99 | 503 p99 | Throughput 2xx / 503 |
|---|---|---|---|---|---|---|---|
| A. normal | 400 req/s | 60 | 60 / 200 | 0 | 90 ms | none | 400 / 0 |
| B. 2x overload, no shedding | 1 600 req/s | 800 and growing | 200 / 200 | 45 | 6.5 s then timeouts | none | 300 / 0 (the rest time out) |
| C. 2x overload, with shedding | 1 600 req/s | 200 | 190 / 200 | 0 | 105 ms | 0.4 ms | 800 / 800 |
Why: without a limit, the queue in front of the slow resource grows without bound, so every request waits. A hard cap keeps admitted requests fast and makes the excess cheap.
| Symptom | Root cause | Action |
|---|---|---|
| Latency of all requests rises with load, no errors | unbounded in-flight work | in-flight limit in an early filter |
| Clients retry instantly after connection resets | Tomcat rejected at TCP level, no status | 503 with Retry-After from a filter, small accept-count |
| Checkout starved by product search | one queue, no priority | tiered limits by path prefix or header |
| Limit oscillates every few seconds | adaptive window shorter than the dependency's reaction time | longer window, smaller step, floor limit |
Land it Count in-flight requests at the front door, reject the excess in microseconds with a 503 and a Retry-After, and keep the important tier admitted.
- "The requirement changes: shedding must be fair per tenant, not per priority tier. How does the filter change?"
The single in-flight counter becomes a map of counters keyed by tenant, and each tenant gets a share of the total limit, for example total divided by active tenants with a floor and a ceiling.
The filter reads the tenant from the validated token or an API key header, which means it must run after authentication rather than before, so it moves to just after the resource server filter, still before the controller.
To keep the cost low I would use a
ConcurrentHashMapofLongAdderand sweep idle tenants every minute.The fairness rule I would pick is max-min: a tenant can exceed its share only while there is unused capacity, and when the total limit is reached only tenants over their share are shed.
The metric becomes shed count by tenant, which is also the signal for a sales conversation about a tenant that needs a bigger plan.
- "How does the adaptive limit algorithm actually decide, and what makes it oscillate?"
A gradient limiter keeps a long-window minimum round-trip time as the no-queue baseline and compares it with the recent sample.
The gradient is baseline divided by current latency; if latency has doubled, the gradient is 0.5 and the limit shrinks toward half; if latency is at baseline, the limit grows by a small additive step.
Netflix's library implements this in
GradientLimitwith a smoothing factor and a minimum limit. Oscillation happens when the sampling window is shorter than the time it takes the dependency to react, so the limiter cuts, sees latency improve, grows, overloads again, and repeats every few seconds.The fixes are a longer window, a smaller growth step, and a floor limit derived from the known safe concurrency. I would verify by plotting limit and p99 together and expecting the limit to move slowly and settle, not to saw-tooth.
- "Why not just use Tomcat's max-threads and accept-count as the shedding mechanism?"
Because Tomcat rejects at the TCP level, after the connection is accepted into the backlog and only when the backlog is full, which means requests sit in the accept queue and in the kernel backlog for seconds before failing, and the client sees a connection reset or a timeout rather than a fast 503.
The client cannot tell overload from a network fault and retries immediately, which adds load. Also the backlog is a single queue with no notion of priority, so a health check or a checkout request waits behind a thousand product searches.
A filter-level shed happens after the request line is parsed, which costs microseconds, and can write a proper status code and
Retry-Afterso a well-behaved client backs off.I still keep
server.tomcat.accept-countsmall, around 100, as the last line, but it is the floor, not the mechanism.what the client seesruns offline# illustrative output Tomcat backlog full: curl: (56) Recv failure: Connection reset by peer # or a timeout after seconds filter shed: HTTP/1.1 503 Service Unavailable Retry-After: 1 {"title":"Overloaded","status":503} # in about a millisecond- "What would you cut under time pressure if you had to ship shedding by Friday?"
I would ship a static in-flight limit with two tiers and nothing adaptive.
That is one filter of about forty lines: an
AtomicInteger, a limit from configuration such asapp.shed.limit=200, a tier decided by path prefix, an immediate 503 withRetry-After: 1, and a counterapp.shed.rejectedtagged by tier.The limit comes from the thread and pool arithmetic already known, set at about 80 percent of measured capacity. I would cut the bounded wait, the gateway header classification, and the adaptive limiter, and I would note them as follow-ups.
What I would not cut is the metric and a load test that proves rejected requests return in under a millisecond, because a shedder that has never been seen shedding is a guess.
- "How do you test that the service really stays fast for admitted requests when it is overloaded?"
With a load test that separates admitted from rejected latencies. I would drive the service with k6 or Gatling at twice the configured limit and record two histograms, one for 2xx responses and one for 503s.
The pass criteria are that 2xx p99 stays within 20 percent of its unloaded value, 503 p99 is under a few milliseconds, and the sum of throughputs equals the offered load, meaning nothing queued silently.
I would also watch
tomcat.threads.busyto confirm it stays below max andhikaricp.connections.pendingstays at zero, since the point of shedding is to keep those resources unsaturated.Then I would repeat with a slow dependency injected by Toxiproxy to confirm the limit, static or adaptive, still protects the service when the bottleneck moves downstream.
Q144. "Which executors does Boot manage for you, how are they configured, and what changes when virtual threads are on?"
Reveal answer
Strong answer Boot auto-configures three families.
- The embedded server's request executor. Tomcat's own pool, configured through
server.tomcat.threads.*. - The application task executor. A
ThreadPoolTaskExecutorbean namedapplicationTaskExecutorand aliasedtaskExecutor.- Configured by
spring.task.execution.pool.core-size(default 8),max-size(default unbounded),queue-capacity(default unbounded), andthread-name-prefix. - It backs
@Async, Spring MVC's async request processing, and anything that injects anAsyncTaskExecutor. - The defaults deserve attention: with an unbounded queue, the pool never grows past the core size. That is eight threads and an infinite queue, so
@Asyncwork silently backs up under load. Set a queue capacity, a max size, and a rejection policy.
- Configured by
- The task scheduler. A
ThreadPoolTaskScheduler, configured byspring.task.scheduling.pool.size, default one thread, which makes all@Scheduledjobs serialise.
Kafka listener containers have their own consumer threads, and Boot 3.2 and later can run the listener's record processing on a configured executor.
With spring.threads.virtual.enabled=true on Java 21 and later:
- Boot replaces the Tomcat executor with a virtual-thread-per-task executor.
- It swaps the application task executor for a
SimpleAsyncTaskExecutorthat starts a virtual thread per task. - It makes the scheduler use virtual threads, and does the same for Kafka and RabbitMQ listeners.
- The pool-size properties then stop meaning "threads" and the queue disappears, since there is nothing to queue for. You regain concurrency limits only by adding them explicitly, such as
@ConcurrencyLimitor a bulkhead. - A
TaskDecoratorbean, for context propagation, still applies to both.
# ❌ TRAP (defaults): core-size 8, queue-capacity unbounded, so the pool never grows past 8.
# 1. The web server's request pool.
server.tomcat.threads.max = 200
server.tomcat.threads.min-spare = 10
server.tomcat.accept-count = 100 # queue depth once all threads are busy
# 2. The @Async / general task executor.
# ✅ FIX: bounded queue and a max size.
# Result: 8 threads, then 100 queued, then up to 32 threads, then TaskRejectedException.
spring.task.execution.pool.core-size = 8
spring.task.execution.pool.max-size = 32
spring.task.execution.pool.queue-capacity = 100 # NOTE: fills BEFORE max-size grows
spring.task.execution.shutdown.await-termination = true
spring.task.execution.shutdown.await-termination-period = 30s
# 3. The @Scheduled executor. Defaults to ONE thread: a long job blocks
# every other scheduled job in the service.
spring.task.scheduling.pool.size = 4
# 4. Virtual threads (JDK 21+, Boot 3.2+). One line.
spring.threads.virtual.enabled = true
// With spring.threads.virtual.enabled=true:
// - Tomcat runs each request on a NEW virtual thread instead of a pooled
// platform thread. server.tomcat.threads.max stops being the concurrency limit.
// - @Async and @Scheduled use virtual threads too.
//
// What it does NOT change, and what still bites:
//
// 1. The connection pool is still the real limit. 10,000 concurrent virtual
// threads all waiting on a 10-connection Hikari pool is 10,000 threads
// queueing. Virtual threads remove the thread cost, not the resource cost.
//
// 2. PINNING. A virtual thread inside a synchronized block that blocks cannot
// unmount from its carrier thread, so it holds a platform thread anyway.
// JDK 24 fixed this for synchronized (JEP 491); on earlier versions,
// replace with ReentrantLock:
//
// // ❌ TRAP:
// synchronized (this) { jdbc.query(...); } // pins before JDK 24
// // ✅ FIX:
// lock.lock(); try { jdbc.query(...); } finally { lock.unlock(); } // never pins
// // Result: the virtual thread unmounts while it waits on the database
//
// 3. Diagnose pinning with: -Djdk.tracePinnedThreads=full
Point 1 is the one that disappoints teams. Enabling virtual threads on a service whose bottleneck is the database changes nothing measurable, because the constraint was never the number of threads.
Picture it the bean names, how a thread pool decides, and the pool state at three moments, before and after enabling virtual threads.
The setup: the properties in the first block above.
Make the invisible visible: the executors Boot registers and what backs each.
# illustrative output
bean name class threads
applicationTaskExecutor ThreadPoolTaskExecutor core 8, max unbounded, queue unbounded
taskExecutor (alias) same bean
taskScheduler ThreadPoolTaskScheduler 1 thread
Tomcat request pool http-nio-8080-exec-1 .. 200 200 max
# with spring.threads.virtual.enabled=true:
applicationTaskExecutor SimpleAsyncTaskExecutor one virtual thread per task, no pool, no queue
The trace: how a ThreadPoolExecutor decides, with the default queue.
submit(task)
├─ threads < core (8)? ──► start a thread ✓
├─ else queue.offer(task)? ──► unbounded queue always accepts ✗ task waits, pool never grows
└─ else threads < max? ──► start a thread (never reached with an unbounded queue)
──► else reject (TaskRejectedException with the default AbortPolicy)
What you see: the executor metrics at three moments.
| Moment | Config | executor.active | executor.queued | Wait of a new @Async task |
|---|---|---|---|---|
| A. normal load | core 8, unbounded queue | 3 | 0 | milliseconds |
| B. burst of 20 000 @Async calls | core 8, unbounded queue | 8 (the maximum) | 19 992 and memory growing | minutes |
| C. same burst after the fix | core 8, max 32, queue 100 | 32 | 100, then TaskRejectedException at the caller | bounded, rejections visible |
Why: a ThreadPoolExecutor adds threads beyond the core only when the queue refuses a task, and an unbounded queue never refuses.
The fix: a bounded queue and a max size, as in the properties block above. The code under "what that one line actually changes" shows the virtual-thread side.
What you see now: row C above, and an explicit failure instead of a silent backlog.
| Action | Platform threads | Virtual threads on |
|---|---|---|
| 2 000 concurrent requests, each calls the database through a 10-connection pool | 200 threads busy, the rest wait in accept-count | 2 000 virtual threads, 10 run, 1 990 wait for a connection: the pool is the limit |
@Async fan-out to a dependency with no limit | bounded by max-size | one virtual thread per task, dependency crushed unless concurrency-limit or a bulkhead is set |
synchronized block that does JDBC, JDK 21 | n/a | pins the carrier thread (fixed in JDK 24) |
server.tomcat.threads.max=200 | limits concurrency | no longer the concurrency limit |
| Symptom | Root cause | Action |
|---|---|---|
@Async work starts minutes late, memory grows | unbounded queue, pool stuck at core size | queue-capacity, max-size, rejection policy |
A long @Scheduled job delays all others | scheduler pool size 1 | spring.task.scheduling.pool.size, or hand work to the task executor |
| Virtual threads on, no latency gain | database pool is the bottleneck | size the pool, bound the work |
Dependency crushed by @Async fan-out with virtual threads | no cap left | spring.task.execution.simple.concurrency-limit or a bulkhead |
Land it Know the three executors and their default sizes, bound the async queue, and remember that virtual threads remove the limits you were relying on without noticing.
- "Why does the default application task executor never grow past eight threads?"
Because of how
ThreadPoolExecutormakes decisions. When a task arrives it first fills the pool up to the core size, then it offers the task to the queue, and only if the queue refuses does it create a thread up to the max size.Boot's default queue is a
LinkedBlockingQueuewith capacityInteger.MAX_VALUE, which never refuses, so the max size is never consulted. The result is eight threads working through an unbounded backlog, and memory grows with the queue while callers of@Asyncsee their work start minutes later.The fix is
spring.task.execution.pool.queue-capacity=100together withmax-size=32and a rejection policy, so under load the pool grows first and then fails fast with aTaskRejectedExceptionyou can see. I would verify with theexecutor.queuedandexecutor.activemetrics that Boot registers for the executor.pool state under a burstruns offline# illustrative output unbounded queue: pool size 8 active 8 queued 19992 -> max-size never consulted queue-capacity=100, max-size=32: pool size 32 active 32 queued 100 -> next submit: TaskRejectedException- "What is the rejection policy default, and which would you choose?"
The default is
AbortPolicy, which throwsTaskRejectedExceptionat the caller. For@Asyncmethods returning void, that exception surfaces in the calling thread at the point of submission, which is the honest behaviour.The alternative many teams reach for is
CallerRunsPolicy, which executes the task on the submitting thread, in practice the Tomcat request thread, so it acts as back-pressure but turns a fire-and-forget into a blocking call and can stall the request pool.I choose abort for user-facing paths with a clear error, and caller-runs only for internal batch producers where slowing the producer is the desired effect. In Boot you set it with a
ThreadPoolTaskExecutorCustomizerbean callingsetRejectedExecutionHandler, because there is no property for it.- "With virtual threads enabled, an @Async method fans out to a dependency and the dependency gets crushed. What replaced the limit you lost?"
Nothing did, which is the trap. The
SimpleAsyncTaskExecutorstarts one virtual thread per task with no cap unless you setspring.task.execution.simple.concurrency-limit, which as of Boot 3.4 and later exists exactly for this, and I would set it to whatever the dependency tolerates, say 100.For a specific call site I would add a Resilience4j bulkhead,
@Bulkhead(name = "pricing", type = SEMAPHORE)withmaxConcurrentCallsconfigured, or Spring's@ConcurrencyLimitfrom Framework 7.The point to say aloud is that platform-thread pools were an accidental rate limiter, and virtual threads remove the accident, so every fan-out needs an explicit bound.
I would verify by watching the dependency's connection count or its own in-flight metric while running the fan-out under load.
- "Two @Scheduled jobs overlap and one starves the other. Which setting, and what else do you check?"
The scheduler pool defaults to one thread, so the second job waits for the first, and a job that runs longer than its interval blocks everything.
spring.task.scheduling.pool.size=4gives independent threads.But I would also check the trigger type:
fixedRateschedules the next run on the clock regardless of duration, so a slow job piles up its own invocations once the pool has spare threads, whereasfixedDelaywaits for completion, which is usually what people mean.And I would check for a job doing blocking I/O that belongs on the task executor rather than the scheduler: the pattern is a tiny scheduled method that submits work to
applicationTaskExecutorand returns.Boot exposes
executor.*metrics for the scheduler too, tagged by name, so a saturated scheduler is visible asexecutor.activepinned at the pool size.- "How does context propagation work across these executors, and what breaks when it does not?"
A task on another thread loses the MDC, the security context, the tracing span, and the request-scoped beans of the submitting thread unless something copies them.
The mechanism is a
TaskDecoratorbean: Boot applies it to the task executor and scheduler, and it wraps each runnable to capture the MDC map and theSecurityContextbefore submission and restore them inside the task.Micrometer's
ContextSnapshotfrom context-propagation does the same for observation and trace ids, and Spring Security 6.3 and later can propagate the context automatically throughDelegatingSecurityContextAsyncTaskExecutor.What breaks without it is subtle: logs from async work lack the trace id so they cannot be correlated, and a method-secured call inside
@Asyncfails with an authentication exception because the context is empty.Virtual threads do not change any of this, since a new thread is still a new thread.
Q145 · Scenario. "A service is at 100 percent CPU with only 50 requests per second, which used to need 5 percent. Nothing was deployed. Walk through it."
Reveal answer
Strong answer In diagnosis order:
- Symptom. CPU per request rose twenty-fold without a code change. Either the work per request changed because the data or the input changed, or the JVM is spending CPU on something other than requests.
- Evidence first, since guessing is slow.
- A CPU profile with async-profiler or JFR for 30 seconds, which names the hot frames in a minute.
jvm.gc.pauseandjvm.gc.overhead, to see whether the collector is the consumer.- The thread dump, to see whether the busy threads are request threads or something else.
- Likely causes, ranked.
- Garbage collection thrash: the heap is nearly full and the collector runs continuously, caused by a leak that finally reached the limit or by a traffic pattern with larger payloads.
- A regular expression on an input that now triggers catastrophic backtracking, which one malformed request per second can turn into full CPU.
- A query whose result set grew because a table crossed a size threshold, so the service now deserialises and sorts a hundred times more rows.
- A cache whose TTL expired for an entry that is expensive to rebuild and is being rebuilt concurrently, the stampede from Q114.
- A runaway
@Scheduledjob, or an@Asyncqueue draining a backlog. - A logging storm from an error that repeats on every request with a stack trace.
- A dependency's changed response that puts every request on an error path with exception construction and logging.
- Fix per cause. Restart to clear the GC state and then find the leak. Bound and precompile regexes and reject oversized inputs. Paginate and bound queries.
sync=trueon the cache. Bound the async queue. Drop the log level on the repeating error. - Prevention. A continuous low-overhead profiler in production, CPU per request as a dashboard line so a slow drift is seen before it becomes 100 percent, and input size limits at the edge.
Picture it the same service at three moments, what a 30-second profile reads for each likely cause, and a decision table from the first minute of evidence to the action.
The setup: the service is a plain Boot API at 50 requests per second. The only thing that changed is the data and the input, so the code below is a typical culprit, a regex that backtracks.
private static final Pattern CODE = Pattern.compile("(a+)+b"); // ❌ TRAP: nested quantifiers backtrack exponentially
boolean valid(String s) {
return CODE.matcher(s).matches(); // "aaaaaaaaaaaaaaaaaaaaaaaaaaaa!" never matches, and takes exponential time
}
// ✅ FIX: bound the input and avoid nested quantifiers
// if (s.length() > 64) return false; Pattern.compile("a++b");
// Result: the same hostile input fails in microseconds
Make the invisible visible: CPU per request, which is what the dashboard should have shown.
| Moment | Requests per second | CPU | CPU per request | GC overhead | Heap after GC | Busy threads |
|---|---|---|---|---|---|---|
| 04:00 normal | 50 | 5% | 1 ms | 0.5% | 410 MB | 6 |
| 09:10 incident begins | 50 | 100% | 20 ms | 0.5% | 410 MB | 46 (regex frames) |
| 09:40 other incident shape: GC thrash | 50 | 100% | 20 ms | 55% | 1.9 GB of 2 GB, climbing | 4 |
The trace: what the thread dump shows for the regex case.
"http-nio-8080-exec-21" RUNNABLE
at java.util.regex.Pattern$Loop.match
at java.util.regex.Pattern$GroupTail.match
at java.util.regex.Matcher.matches
at com.example.Validator.valid ✗ same frame on 46 threads, same request path
What you see: a 30-second profile for each cause.
# illustrative output: top frames by CPU share
regex case: 61% java.util.regex.Pattern$Loop.match
GC thrash: 58% G1 concurrent mark / G1 young collection (not in your code)
big result set: 40% org.hibernate.loader... / jackson serialization of 100 000 rows
log storm: 35% ch.qos.logback... / Throwable.fillInStackTrace
Why: CPU per request is the product of what each request does and what the JVM does around it, so the first minute of evidence splits the causes cleanly.
The fix: one fix per cause, listed in the decision table, with the profile re-run after each.
What you see now: after the regex fix, the same profile.
# illustrative output
regex case, after: Pattern$Loop no longer in the top frames; CPU 5%, 1 ms per request, busy threads 6
| Symptom | Root cause | Action |
|---|---|---|
Pattern$Loop frames across many threads | regex backtracking on hostile input | possessive quantifiers, bound the input length, unit test with a time limit |
jvm.gc.overhead high, live set after GC climbing | leak, heap near the ceiling | histogram then heap dump, find the retainer, restart to buy time |
| Rows fetched per call grew a hundredfold | data crossed a threshold or the plan changed | bound and paginate every list query, alert on rows per call |
| Many threads rebuilding one cache entry | stampede after TTL expiry | sync=true |
| Logging frames and stack traces dominate | error repeating on every request | drop the level on that error, fix the cause |
Land it CPU without traffic is GC, a pathological input, or a background task, and a thirty-second profile beats an hour of theories.
- "The profile shows the time inside G1 concurrent marking, not in your code. What does that tell you, and what next?"
It tells me the heap is near its ceiling and G1 is running its concurrent cycle back to back, which is the collector working continuously to free space that is immediately reused.
The next step is to find out whether the live set has grown, meaning something is retaining objects, or whether allocation rate has exploded, meaning something creates garbage faster than before.
jvm.memory.usedafter each GC is the live set line; if it climbs monotonically it is a leak. I would take a heap histogram withjcmd <pid> GC.class_histogram, which is cheap, then a full heap dump only if the histogram does not name the culprit.The usual retainers are an unbounded cache, a growing list held by a singleton, or a Hibernate session that lives too long. Restarting buys time, but the next occurrence is scheduled the moment the leak refills the heap.
heap histogram of a leakruns offline# illustrative output: jcmd <pid> GC.class_histogram num #instances #bytes class name (module) 1: 4812033 385762640 [B (java.base@21) 2: 4650112 111602688 java.lang.String (java.base@21) 3: 1203441 38510112 com.example.cache.PricingEntry # millions of one app class: the retainer- "How do you confirm the regex theory without guessing, and what is the fix pattern?"
A thread dump under load shows the busy threads with
java.util.regex.Matcher.matchorPattern$Loopframes deep in the stack, and the same request path repeated across many threads.Then I look at what input those requests carried, usually a long string with repeated characters that hits a pattern like
(a+)+or nested optional groups, which backtracks exponentially.The fix pattern is to rewrite the expression with possessive quantifiers or atomic groups so it cannot backtrack, to bound the input length before matching, and to compile the pattern once as a static final rather than per call.
Java has no built-in match timeout, so an input length check at the controller is the real protection. I would keep a unit test with the pathological input and a time limit so the regex cannot regress silently.
- "Nothing was deployed, but the profile points at a query result grown a hundredfold. How can that happen with no code change?"
The data changed shape.
A query with a
WHEREon a status column returns a small set until a batch job or a stuck consumer leaves a hundred thousand rows in that status, and a query with noLIMITnow loads all of them, maps them to entities, and sorts or filters in Java.Alternatively the database's planner changed strategy after statistics crossed a threshold, so a query that used an index now scans, and the service spends CPU deserialising a large result set that it then discards.
I would confirm with
hibernate.generate_statisticsor a JDBC interceptor counting rows fetched per query, or with the database's slow log showing rows examined.The fix is a hard bound on every list query, pagination in the API, and an alert on rows per call so the drift is visible before it becomes 100 percent CPU.
- "What does a continuous profiler in production cost, and how would you set one up?"
Around one to two percent CPU with async-profiler in wall or CPU mode at a 10 to 20 millisecond sampling interval, and with JFR at its default profile similar overhead.
The setup I have used is JFR always on, started with
-XX:StartFlightRecording=disk=true,maxage=1h,settings=profile, which writes a rolling recording to disk so an incident's last hour is available withjcmd <pid> JFR.dump.For a fleet-wide view a continuous profiler agent such as Pyroscope or Datadog's uploads sampled stacks and lets you compare a slow hour to a normal one as a flame graph diff, which is exactly the tool for a question like this one.
The cost that matters is not CPU but disk and the storage bill for profiles, so I would sample at a lower rate on the fleet and raise it on a pod under investigation.
- "How would you build the CPU-per-request line so this is caught early?"
Divide process CPU by request rate. Micrometer exposes
process.cpu.usage, and the request counter ishttp_server_requests_seconds_count. In PromQL the panel israte(process_cpu_seconds_total[5m]) / rate(http_server_requests_seconds_count[5m]), which gives CPU seconds per request.I would alert on it doubling against a seven-day baseline rather than on an absolute number, because a legitimate feature can raise it.
For finer attribution, a per-route version uses thread CPU time: a filter reads
ThreadMXBean.getCurrentThreadCpuTime()before and after the handler and records the delta in a timer tagged by route, which costs a couple of microseconds per request and tells you exactly which endpoint got expensive.Either form would have shown this incident as a slow ramp days earlier if the cause was a leak, or a step change if it was a data shape.
Q146 · Design. "Design a Boot service that adds an LLM-powered 'summarise this ticket' feature to a support product: provider calls, streaming, cost control, and failure handling."
Reveal answer
Strong answer Requirements: summaries appear within a few seconds and stream as they are generated, the monthly provider bill is bounded and attributable per tenant, provider outages degrade rather than break the product, and no ticket text leaves the system without the controls the privacy team requires.
- Shape. A dedicated
summariesmodule or service in Boot 4 on Java 25 with virtual threads, so thousands of slow provider calls do not need a thread pool budget. - Provider client. A
RestClientor the Spring AIChatClientwith a 30-second read timeout, a bulkhead of 50 concurrent calls, a circuit breaker, and a single retry on connection failures only, never on a completed generation. - Streaming. The SSE design from Q59, relaying provider tokens to the browser and persisting the finished summary.
- Cost control.
- A per-tenant token budget stored in the database and decremented in the same transaction that records the summary, with a pre-check that refuses when the budget is exhausted.
- A Micrometer counter of input and output tokens tagged by tenant and model, which is the bill forecast.
- A cache keyed by a hash of the ticket content and the prompt version, so an unchanged ticket is never summarised twice.
- A smaller, cheaper model for tickets under a size threshold.
- Failure. An open breaker or a timeout returns the last stored summary if one exists, otherwise a clear "summary unavailable" state rather than an error page. A queue handles asynchronous retry so the summary appears later.
- Safety. A redaction step strips emails and card numbers before the call. The prompt is versioned in configuration. Every call is logged with the prompt version and token counts but never the ticket text.
- Trade-offs. Caching by content hash misses tickets that change slightly. The budget check adds a database round trip.
- What I would not do. Call the provider inside a request transaction, retry a generation that may have completed, or let the provider's latency define the service's thread pool. The prompting, evaluation, and RAG questions behind this feature are modules 06 through 08 of this course.
Picture it one request through the guards, the budget row at three moments, and what the user sees when each guard trips.
The setup: the budget reservation, one atomic statement.
-- reserve an estimate; zero rows updated means refuse
UPDATE tenant_budget
SET used_tokens = used_tokens + 1200
WHERE tenant_id = 'acme' AND used_tokens + 1200 <= limit_tokens;
The trace: one request.
POST /tickets/7/summary
├─ cache lookup (hash of ticket + prompt version) hit ✓ return stored summary, 0 tokens
├─ budget reservation 0 rows ✗ refuse: budget exhausted
├─ redaction (emails, card numbers) ✓
├─ bulkhead (50 concurrent), breaker closed ✓
├─ provider call, stream tokens to the browser ✓
│ connect failure or 429 before any body ✓ one retry
│ read timeout after first token ✗ no retry: persist partial, queue regeneration
└─ reconcile budget with real token counts, store summary
What you see: the budget row at three moments, then the response bodies.
| Moment | used_tokens | limit_tokens | Event |
|---|---|---|---|
| start of the month | 0 | 2 000 000 | nothing used |
| mid-month | 1 340 000 | 2 000 000 | reservations and reconciliations netted |
| end of month | 1 999 100 | 2 000 000 | next reservation of 1 200: 0 rows updated, request refused |
// 200 normal
{ "summary": "Customer reports duplicate charge ...", "stale": false }
// 200 provider down, last stored summary, ticket edited since
{ "summary": "Customer reports duplicate charge ...", "stale": true, "summaryAt": "2026-08-01T09:12:00Z" }
// 200 provider down, nothing stored
{ "state": "unavailable", "retryLater": true }
Why: the provider is slow, billed per token and sometimes absent, so each guard turns one of those facts into a bounded cost or a visible state.
| Symptom | Root cause | Action |
|---|---|---|
| Bill climbs faster than ticket volume | no cache, or prompt version changes invalidate it constantly | cache by content hash and prompt version, watch the token counter by tenant |
| Request threads all waiting on the provider | no bulkhead or timeout | 50-call bulkhead, 30 s read timeout, breaker |
| Summary text changes on reload | retry of a generation that completed | no retry after the first token, regenerate through the queue |
| Redaction counter drops to zero with normal volume | step bypassed or broken | alert, hourly canary with fake emails and card numbers |
Land it Treat the provider as a slow, expensive, occasionally absent dependency: stream through it, bulkhead and break around it, meter every token, and degrade to the last good answer.
- "The requirement changes: summaries must never be served stale after a ticket is edited. What changes?"
The content-hash cache already handles the common case, because an edited ticket has a new hash and misses. The gap is the fallback path, where a provider outage returns the last stored summary.
I would store the source hash alongside each summary, and on fallback compare it with the current ticket hash; if they differ, the response carries a
stale: truefield with the summary's timestamp so the product can show it as "summary from before the last edit", or, if the requirement is strict, the service returns the unavailable state instead.I would also invalidate on write: the ticket service publishes a ticket-updated event, and the summaries module deletes or marks its cached entry, so a freshly edited ticket triggers a new generation on next view.
The cost is one more event consumer and a small race between edit and view, bounded by the event's delivery time.
- "Why never retry a completed generation, and how do you tell a completed one from a failed one?"
A generation that completed on the provider's side has already been billed, and a retry bills it again and may produce a different summary, so the user sees the text change on reload. The distinguishing signal is where the failure happened.
A connect timeout, a DNS failure, or a 429 before any body arrives means the provider did no work, so a retry is safe.
A read timeout after the first streamed token, or a broken connection mid-stream, means work was done and money was spent, so I do not retry automatically; I persist the partial text with a flag and let the asynchronous queue schedule a regeneration with a back-off.
In code that means the retry policy is on the
RestClientrequest only forConnectExceptionand 429 withRetry-After, and the streaming path is wrapped separately with no retry.- "Show me how the per-tenant budget check avoids two concurrent requests both passing the check."
The check and the decrement must be one atomic statement, not a read followed by a write.
The pattern is
UPDATE tenant_budget SET used_tokens = used_tokens + :estimate WHERE tenant_id = :id AND used_tokens + :estimate <= limit_tokens, and if the update affects zero rows the request is refused.Two concurrent requests serialise on the row lock and the second sees the first's increment.
Because the real token count is only known after the call, I reserve an estimate up front, based on ticket length times a factor, and reconcile after the response by adjusting the row by the difference.
If the provider call fails, the reservation is released in the same failure handler. That keeps the budget honest under concurrency and makes the database the single source of truth for the bill forecast.
- "What would you cut under time pressure to ship in a sprint?"
I would ship without streaming and without the asynchronous retry queue. The summary is generated on demand with a 30-second timeout and shown when complete, which is acceptable for a first release if the product shows a spinner.
I would keep the bulkhead, the circuit breaker, the content-hash cache, the token metering by tenant, and the redaction step, because those are the pieces that protect the bill and the privacy review, and they are each a few lines.
The budget check can start as a soft alert on the token counter rather than a hard refusal.
Streaming and the retry queue go on the next sprint's list, and I would say clearly that without streaming the perceived latency is the full generation time, so the feature will feel slower than the final design.
- "How do you verify the redaction step is actually working in production without logging the ticket text?"
With counters and sampled synthetic tickets. The redaction step increments a metric per pattern class it replaced,
app.summaries.redacted{type=email}, so a drop to zero over a day while ticket volume is normal means the step is bypassed or broken.Then a scheduled canary submits a synthetic ticket that contains known fake emails and a test card number every hour, and a check asserts that the outbound request body, captured by a test-only interceptor on the canary tenant, contains none of them.
The canary runs through the real path including the cache, so it also tells me the pipeline is alive.
For audit, I log the count and the positions of redactions, never the values, which satisfies the privacy team's need to prove the control without creating a copy of the data it protects.
Q147 · Design. "Design the liveness and readiness semantics for a Boot service with a database, Redis, and a Kafka consumer, so that probes help during incidents instead of making them worse."
Reveal answer
Strong answer Requirements: restart a pod only when a restart would help, stop routing to a pod only when it cannot serve, and never let a shared dependency's outage restart the whole fleet.
- Liveness. It answers "is this process wedged in a way only a restart fixes".
- The liveness group contains only Boot's
livenessState, which reflects the context being alive, and possibly a custom indicator for a known deadlock condition, such as the Kafka consumer thread not having polled in 10 minutes. - It never includes the database, Redis, or Kafka. If the database is down, restarting 50 pods creates a reconnect storm against a database that is trying to recover, and a restart loop that hides the real problem.
- The liveness group contains only Boot's
- Readiness. It answers "can this pod serve requests right now".
- The readiness group contains
readinessStateplus the database indicator, since the service cannot serve without it. - Not Redis, because the cache has a fallback path. Not Kafka, because HTTP serving does not depend on consuming.
- The readiness group contains
- Kafka consumer. It gets its own signal: a metric and an alert on lag and on time since last poll, not a probe.
- Probe tuning.
- Liveness with a 30-second period and a failure threshold of 3, so a 90-second problem triggers a restart.
- A startup probe with a long budget so slow starts do not count.
- Readiness with a 5-second period and a threshold of 2, so a pod is pulled within 10 seconds and returned as soon as it recovers.
- Health checks cached for 5 seconds with a 1-second timeout, so a slow database does not make the probe itself time out.
- Trade-offs. Excluding Redis from readiness means a pod with a broken cache client serves slowly, so the fallback path's latency must be acceptable.
- What I would not do. Put every dependency in liveness, which is the most common cause of self-inflicted outages, or make readiness so strict that a partial dependency failure removes all capacity at once.
Picture it the group configuration, the two JSON answers, and 50 pods through a ten-minute database outage under a bad and a good setup.
The setup: the groups and the probes.
# ✅ FIX: liveness only looks at the process; readiness adds the database
management.endpoint.health.probes.enabled=true
management.endpoint.health.group.liveness.include=livenessState
management.endpoint.health.group.readiness.include=readinessState,db
management.endpoint.health.group.readiness.show-details=always
management.endpoint.health.cache.time-to-live=5s
# ❌ TRAP: pointing a probe at /actuator/health instead aggregates db, redis and everything else
startupProbe: { httpGet: { path: /actuator/health/liveness, port: 9090 }, periodSeconds: 10, failureThreshold: 30 }
livenessProbe: { httpGet: { path: /actuator/health/liveness, port: 9090 }, periodSeconds: 30, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 9090 }, periodSeconds: 5, failureThreshold: 2 }
Make the invisible visible: what each endpoint answers with the database down.
# illustrative output
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:9090/actuator/health/liveness
200 # {"status":"UP","components":{"livenessState":{"status":"UP"}}} no db inside
$ curl -s -w "\n%{http_code}\n" localhost:9090/actuator/health/readiness
{"status":"DOWN","components":{"db":{"status":"DOWN"},"readinessState":{"status":"UP"}}}
503 # pod leaves the Service, container keeps running
The trace: a database outage, the two setups side by side.
database down
bad: /actuator/health in the liveness probe ──► DOWN ──► kubelet restarts the pod ✗ 50 pods restart
good: liveness probe ──► UP; readiness ──► 503 ──► pod removed from the Service only ✓ no restart
What you see: 50 pods through a ten-minute outage, at three moments.
| Moment | Setup | Ready pods | Restarts so far | DB connection attempts |
|---|---|---|---|---|
| t = 0, outage starts | bad | 50 | 0 | steady |
| t = 2 min | bad | 0 | 50 and cycling | reconnect storm against a recovering database |
| t = 10 min, database back | bad | 0 to few, still restarting | 200+ | still saturated |
| t = 2 min | good | 0 (readiness 503) | 0 | pools retry quietly |
| t = 10 min, database back | good | 50 within seconds | 0 | pools refill at once |
Why: a restart cannot fix a dependency that belongs to someone else, and it makes the recovery harder by adding load.
| Symptom | Root cause | Action |
|---|---|---|
| Whole fleet restarts during a database incident | database in the liveness group, or probe on /actuator/health | liveness group = livenessState only |
| Pods killed during a slow start | no startup probe | startup probe with a long budget |
| Probe fails because the database is slow, not down | health check slower than the probe timeout | cache TTL 5 s, validation timeout about 1 s |
| Redis blip pulls every pod out of the Service | Redis in readiness | keep it out, rely on the fallback |
| Consumer silently stuck, probes green | no signal for consumer progress | time-since-poll alert, or a custom liveness indicator for it |
Land it Liveness is about the process, readiness is about serving, and a shared dependency belongs in neither unless a restart would fix it or serving is impossible without it.
- "Which exact properties put the database in readiness and keep it out of liveness?"
Boot's probe support is enabled in Kubernetes automatically, or with
management.endpoint.health.probes.enabled=trueelsewhere. The groups are configured withmanagement.endpoint.health.group.readiness.include=readinessState,dbandmanagement.endpoint.health.group.liveness.include=livenessState. The probes then point at/actuator/health/readinessand/actuator/health/liveness, never at/actuator/health, which aggregates every indicator.I would also set
management.endpoint.health.group.readiness.show-details=alwayson the management port so an operator can see which component is down, and I would verify with a curl to each endpoint in a pod that the readiness JSON lists only db and the liveness JSON lists nothing but the state.A test in CI that asserts the group configuration prevents someone adding
redisback in a year later.the guard testruns offline@Test void probeGroupsContainOnlyWhatWeIntend() { // ❌ TRAP: someone adds redis to liveness; Result: this assertion fails in CI assertThat(body("/actuator/health/liveness")).containsOnlyKeys("status", "components"); assertThat(components("/actuator/health/liveness")).containsOnlyKeys("livenessState"); assertThat(components("/actuator/health/readiness")).containsOnlyKeys("readinessState", "db"); }- "The requirement changes: the Kafka consumer is the service's main job and HTTP is only for health. Does Kafka go into readiness now?"
Readiness still controls only HTTP routing, so putting Kafka in it would just remove the pod from a Service that carries no real traffic; it changes nothing about consumption.
What matters for a consumer is whether it is making progress, and the right control is the consumer itself. Spring Kafka's listener container can be paused and resumed, and the Kafka broker's group coordinator already rebalances partitions away from a dead consumer.
So I would keep readiness as is, and add a custom liveness indicator that fails when the consumer thread has not polled in more than
max.poll.interval.msplus a margin, because a stuck consumer is exactly the wedged process a restart fixes.Lag and time-since-poll remain the alerting signals, and the restart path is a last resort behind them.
- "Why cache the health check for 5 seconds, and what goes wrong if the check itself is slow?"
Several probes and monitors call health, and each database indicator call takes a connection from the pool and runs a validation query.
Without caching, a busy pod with the kubelet, a mesh, and a monitor all polling can spend a measurable share of its pool on health.
If the database is slow, the indicator's query is slow, the probe hits its own timeout, which defaults to one second in Kubernetes, and the probe fails for the wrong reason.
The fix is
management.endpoint.health.cache.time-to-live=5sand a validation timeout on the data source health check, which uses the pool'svalidationTimeout, set around one second. Then the probe returns fast with a slightly old answer, which for readiness is what you want.I would verify by timing the readiness endpoint under a Toxiproxy latency injection on the database and expecting it to stay under 100 milliseconds.
- "What would you cut under time pressure if you could change only one thing before a launch?"
I would remove every external dependency from liveness and point the liveness probe at
/actuator/health/liveness. That single change removes the fleet restart loop, which is the failure mode that turns a dependency incident into an outage, and it is a one-line manifest change plus one property.Readiness can stay pointing at the aggregate health endpoint for a while, because the worst case there is that a Redis blip pulls pods from the Service temporarily, which is a degradation rather than a restart storm.
The startup probe, the cache TTL, and the custom consumer indicator can follow. If pressed for one verification, I would run a game day in staging that blocks the database port for five minutes and confirm the restart count stays at zero.
- "How do you keep the probe configuration honest as the service evolves?"
With a test and a policy.
The test is an integration test that starts the context, hits both group endpoints, and asserts the exact component sets, so a new starter that registers a health indicator, which Boot does automatically for Redis, RabbitMQ, Elasticsearch and others, cannot slip into a probe group unnoticed.
The policy is an admission rule in the cluster, with Kyverno or OPA Gatekeeper, that rejects a deployment whose liveness probe path is
/actuator/healthand requires a startup probe on JVM workloads.I would also keep a dashboard panel of restart count per deployment with an alert on any restart that coincides with a dependency alert, because that correlation is the fingerprint of a bad liveness group returning.
Q148 · Scenario. "During a 10-minute database failover, every pod of an unrelated-looking service restarted repeatedly and the outage lasted 40 minutes instead of 10. Explain and fix."
Reveal answer
Strong answer In diagnosis order:
- Symptom. Restarts correlated with a dependency outage, and a recovery much longer than the dependency's. That is a liveness probe including the database, plus the reconnect storm the restarts caused.
- Evidence.
- Pod events showing liveness failures and restarts.
- The liveness endpoint's configuration, including
dbinmanagement.endpoint.health.group.liveness.include, or the probe pointing at/actuator/healthwhich aggregates everything. - Database connection counts spiking as pods restarted and rebuilt pools simultaneously.
- The 30 extra minutes explained by the failover target being hammered by reconnections while pods cycled every 90 seconds.
- Cause chain.
- The database failed over and the health indicator went DOWN.
- Liveness failed, and Kubernetes restarted the pods.
- Each restart created a full pool of connections and ran migration checks against the recovering database.
- Startup took longer than the liveness threshold because the database was slow, so liveness failed again before readiness ever came up.
- The loop continued long after the database was actually healthy, because the pods never got a full startup window.
- Fix.
- Remove the database from liveness as in Q147.
- Add a startup probe with a budget of several minutes so liveness is not evaluated during startup.
- Make the pool's startup non-fatal with
spring.datasource.hikari.initialization-fail-timeout=-1, so a pod can start and become ready later when the database returns. - Keep the database in readiness so traffic stops without restarts, and add jitter to reconnection.
- Prevention. A fleet-wide check that no liveness group includes an external dependency, and a game day that fails over the database in staging while watching restart counts.
Picture it the 40-minute outage as a timeline of one pod and of the fleet, with the pod events and the connection counts at three moments.
The setup: the probe configuration that caused it.
# ❌ TRAP: the probe asks the aggregate endpoint, which includes the database
livenessProbe:
httpGet: { path: /actuator/health, port: 9090 }
periodSeconds: 30
failureThreshold: 3 # a 90-second problem kills the pod
# application.properties: spring.datasource.hikari.connection-timeout=30000 (default 30 s per startup wait)
The trace: one pod during the incident, then the fleet.
00:00 database failover begins db indicator DOWN
00:01.5 liveness fails 3 times ✗ kubelet kills the pod (restart #1)
00:02 pod starts: Hikari init, Flyway validate against a slow database, each waiting up to 30 s
00:03.5 startup not finished at 90 s ✗ liveness still checked, fails again (restart #2)
00:10 database is healthy again
00:10..00:40 pods still cycle: each start needs more than 90 s while 50 pods reconnect at once
00:40 restarts finally align with a quiet window ✓ recovered
What you see: pod events and the numbers at three moments.
# illustrative output
$ kubectl describe pod orders-svc-6d9f-x2k
Events:
Warning Unhealthy Liveness probe failed: HTTP probe failed with statuscode: 503
Normal Killing Container orders-svc failed liveness probe, will be restarted
$ kubectl get pods
NAME READY STATUS RESTARTS
orders-svc-6d9f-x2k 0/1 Running 7
| Moment | Ready pods | Total restarts | DB connections | DB state |
|---|---|---|---|---|
| 00:05 failover running | 50 to 0 | 50 | dropping | failing over, 10 min planned |
| 00:15 database healthy | 0 | 160 | 2 400 attempts per minute | healthy but saturated by reconnects |
| 00:38 | 46 | 410 | settling | healthy |
Why: the restarts added load to the thing that was recovering, and no pod ever got a startup window long enough to finish.
The fix: the database leaves liveness, a startup probe protects slow starts, and the pool tolerates an absent database.
# ✅ FIX
startupProbe: { httpGet: { path: /actuator/health/liveness, port: 9090 }, periodSeconds: 10, failureThreshold: 30 } # 5 minutes
livenessProbe: { httpGet: { path: /actuator/health/liveness, port: 9090 }, periodSeconds: 30, failureThreshold: 3 }
readinessProbe: { httpGet: { path: /actuator/health/readiness, port: 9090 }, periodSeconds: 5, failureThreshold: 2 }
# application.properties: spring.datasource.hikari.initialization-fail-timeout=-1
# spring.datasource.hikari.connection-timeout=3000
What you see now: the same failover, one line per moment.
| Moment | Ready pods | Total restarts | DB connections | What happened |
|---|---|---|---|---|
| 00:05 failover running | 0 (readiness 503) | 0 | retrying quietly | traffic stopped, pods kept running |
| 00:10 database healthy | 50 within seconds | 0 | refill once | recovered with the database |
| 00:40 | 50 | 0 | steady | nothing left to recover |
| Symptom | Root cause | Action |
|---|---|---|
| Restarts start with a database incident | liveness includes the database | liveness group = livenessState only |
| Pods restart before ever becoming ready | startup slower than liveness budget | startup probe, shorter connection timeout |
| Pod exits at startup when the database is unreachable | Hikari fails fast at init | initialization-fail-timeout=-1, with a not-ready alert |
| Database stays saturated after it is healthy | all pods reconnect at once | lower minimum-idle, rolling-update limits, a pooler such as PgBouncer |
Land it A liveness probe that watches the database turns every database incident into a fleet restart loop, and the extra 30 minutes were that loop, not the failover.
- "You removed the database from liveness and pods still restarted during the next failover. What next?"
I would read the pod events again, because the restart reason may have changed.
If the events show OOMKilled rather than liveness failure, the reconnect storm is now exhausting memory: each failed connection attempt allocates buffers and stack traces, and a logging burst can push the heap over its limit.
If the events show the startup probe failing, its budget is too short for a start against a slow database.
If the liveness probe is still failing, something in the liveness group still touches the database, such as a custom indicator that runs a query, or a filter on the management port that opens a transaction.
I would confirm with
kubectl describe podand with the liveness endpoint's JSON during the incident. The fix follows the reason, and the general lesson is to re-verify probe behaviour with a game day rather than assuming one change was enough.reading the restart reasonruns offline# illustrative output $ kubectl describe pod orders-svc-6d9f-x2k Last State: Terminated Reason: OOMKilled # reconnect storm exhausted memory (not a liveness failure) Exit Code: 137 # other reasons seen in Events: # "Startup probe failed" -> startup budget too short for a slow database # "Liveness probe failed" -> something in the liveness group still touches the database- "What does initialization-fail-timeout=-1 actually change, and what is the downside?"
By default Hikari's
initializationFailTimeoutis 1, which means the pool tries to open one connection at startup and throws if it cannot, so the context fails and the pod exits.With -1 the pool starts empty and does not validate, so the application starts, becomes live, and readiness reports down until the database returns, at which point connections are created on demand.
startup with the database unreachableruns offline# illustrative output initializationFailTimeout = 1 (default): context fails at startup, pod exits, restart loop initializationFailTimeout = -1: pool starts empty, pod is live, readiness 503 until the database returnsThe downside is that a misconfigured URL or wrong credentials no longer fail fast at startup; the pod starts, sits not-ready, and someone has to notice.
I would pair the setting with an alert on pods not-ready for more than a few minutes and with a startup log line that reports the first successful connection. The value zero is a middle ground: it validates configuration but tolerates the database being unreachable.
- "Why did startup take longer than the liveness threshold in the first place?"
Several startup steps talk to the database and each waited on a slow or unreachable target. Hikari's pool initialisation waited up to
connectionTimeout, 30 seconds by default. Flyway's validation ran a query and waited similarly. Hibernate's schema validation or metadata bootstrap may have queried the catalog.With the failover target overloaded by reconnections, each of these took tens of seconds, so the context did not finish within the liveness probe's initial delay plus its failure threshold, roughly 90 seconds, and the kubelet killed the pod before readiness ever succeeded.
A startup probe with
failureThreshold: 30andperiodSeconds: 10gives five minutes during which liveness is not evaluated. I would also dropconnection-timeoutto 3 seconds so a slow database fails each step quickly instead of stacking waits.- "How would you add jitter to reconnection, given Hikari does the reconnecting?"
Hikari retries connection creation internally with a fixed back-off, so the jitter has to come from outside it. The practical levers are three.
First, a randomised initial delay on the startup probe and a randomised pre-start sleep in the entrypoint script of a few seconds, so restarted pods do not all begin at once.
Second,
minimum-idleset lower thanmaximum-pool-sizefor the recovery period, so a pod does not open a full pool the moment the database answers; Hikari's housekeeper then grows the pool gradually.Third, the deployment's rolling update parameters,
maxSurgeandmaxUnavailable, which bound how many pods restart together. On the database side, a connection pooler such as PgBouncer or ProxySQL absorbs the reconnect storm by holding client connections while it reopens a bounded number to the server.- "How do you prove the fix during a game day without risking production?"
In staging with production-like pod counts, I would trigger a real failover on the managed database, or block the database port with a network policy for ten minutes, and watch three lines: restart count per deployment, database connection count, and readiness state per pod.
The pass criteria are zero restarts, connections rising once and flattening rather than sawing, and every pod returning to ready within a minute of the database coming back.
I would run the same drill before and after the change so the improvement is a measured delta, and I would keep the drill as a quarterly exercise.
If staging cannot match production scale, I would run the drill against a single production canary pod during a maintenance window, since a single pod's behaviour under a blocked port reveals the probe configuration just as well.
Q149 · Design. "A Boot service is about to be exposed to the public internet for the first time. Design the hardening checklist you would sign off, ordered by risk."
Reveal answer
Strong answer Ordered by what an attacker reaches first:
- Surface. Actuator on a separate management port not routed from the ingress, with only
health,info, andprometheusexposed, as in Q33 and Q70. No H2 console, and no Swagger UI in production unless authenticated.server.error.include-*atneverand the whitelabel page off. - Authentication and authorisation.
- A declared
SecurityFilterChainwithanyRequest().authenticated()as the last rule, so every new endpoint is protected by default. - A JWT resource server with audience validation.
- Method security on service methods for the sensitive operations, and CSRF deliberately decided per chain.
- A declared
- Input. Request size limits on body and multipart, header size at 8 kilobytes, validation on every request body, strict JSON with unknown properties rejected where the API is internal, a bound on collection sizes in payloads, and a regex review.
- Rate limiting and shedding from Q44 and Q143 at the filter layer.
- Transport and headers. TLS at the ingress with HSTS, Security's default headers restored, a CSP if HTML is served, and CORS explicit.
- Dependencies. A software bill of materials generated by the CycloneDX plugin, a CVE scan in CI that fails on critical findings, the Boot line on a supported version, and no
SNAPSHOTor unpinned dependencies. - Secrets. None in the image or git, mounted as files, rotated, and masked in Actuator and logs.
- Logging. No bodies, tokens, or personal data, and an audit trail for authentication events via Spring Security's event publisher.
- Runtime. A non-root user, a read-only root filesystem, dropped Linux capabilities, resource limits, and
ExitOnOutOfMemoryError. - Verification. An authenticated and an unauthenticated dynamic scan against staging, and a test that every route in the
mappingsendpoint returns 401 without a token except an allow list. - Trade-offs and what I would not do. Strict JSON and size limits may break careless clients, which is the point. I would not ship with
permitAllon a catch-all to "fix it later", or rely on the ingress alone for authentication.
Picture it what an outsider can reach before and after the checklist, the route test, and the first three groups as a table of probes and expected answers.
The setup: the default-deny chain.
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(a -> a
.requestMatchers("/login", "/health-public").permitAll()
// ❌ TRAP: .anyRequest().permitAll() "to fix later" opens every new endpoint
// ✅ FIX: deny by default
.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
return http.build();
// Result: a new endpoint with no rule returns 401 until someone decides otherwise
}
Make the invisible visible: what an outsider tries from the internet, before and after.
| Probe | Before the checklist | After |
|---|---|---|
GET /actuator/env | 200, property names and masked values | 404 or connection failure at the ingress, management port not routed |
GET /h2-console | 200, login page | 404 |
GET /orders/7 with no token | 200 (catch-all permitAll) | 401 |
POST /orders with a 50 MB body | accepted and parsed | 413 before deserialisation |
GET /missing | whitelabel page with trace | generic error body, no stack trace |
The trace: how the route test reaches every endpoint.
RequestMappingHandlerMapping.getHandlerMethods() every route the app serves
└─ for each (method, pattern): call with no credentials
├─ in allow list ──► expect 200 ✓
└─ not in allow list ──► expect 401 or 403 ✗ any 200 here fails the build
What you see: the test output.
# illustrative output
GET /orders/{id} 401 ✓
POST /orders 401 ✓
GET /reports/export 200 ✗ not in the allow list: a permit-all matcher is broader than intended
allow list entry /legacy/ping matches no route ✗ stale entry, fails the test
Why: an application is exposed by its routes, and the route table is the only complete list of them.
| Symptom | Root cause | Action |
|---|---|---|
/actuator/env reachable from the internet | management endpoints on the public port or routed by the ingress | separate management port, not routed, network policy |
| New endpoint answered 200 with no login | catch-all permitAll | anyRequest().authenticated() last, route test |
| One request exhausts the heap | no size limits before deserialisation | multipart limits, header size, Jackson read constraints |
| Critical CVE in a network-facing library | unscanned dependencies | CycloneDX bill of materials, CI scan, supported Boot line |
Land it Close the management surface, deny by default, bound every input, scan every dependency, and verify from the outside before the switch is flipped.
- "The requirement changes: the service also serves a browser front end with cookies. What moves on the list?"
CSRF and the header set move to the top. With cookie sessions, a cross-site request carries the cookie automatically, so CSRF protection must be on for the browser chain, with Spring Security's
CookieCsrfTokenRepository.withHttpOnlyFalse()for single-page apps and the token sent on every mutating request.The cookie itself needs
SameSite=Laxor Strict,Secure, andHttpOnly, set throughserver.servlet.session.cookie.*. A content security policy becomes mandatory rather than optional, and I would start it in report-only mode to find violations.I would run two
SecurityFilterChainbeans, one matched on the browser paths with sessions and CSRF, one on the API paths stateless with bearer tokens, so the two models never mix.Session fixation protection is on by default, and I would verify it by checking the session id changes at login.
- "How do you write the test that every route returns 401 without a token?"
I would read the route table from the running application rather than from a hand-written list, so new endpoints are covered automatically.
In a Spring Boot test with a random port, inject
RequestMappingHandlerMappingand iterate its handler methods to get every path pattern and method, substitute placeholder values for path variables, then call each with the testRestClientand no credentials and assert 401 or 403.An allow list holds the handful of public paths, such as the login and the health endpoint, and the test fails if the allow list contains a path that no longer exists, so it cannot grow stale. Actuator routes are tested separately against the management port.
This test takes a few seconds and has caught a permit-all matcher that was broader than intended, which is exactly the class of bug a public exposure turns into an incident.
- "Which request size limits, exactly, and what happens when a client exceeds them?"
For multipart,
spring.servlet.multipart.max-file-size=10MBandmax-request-size=12MB, which throwMaxUploadSizeExceededExceptionthat I map to a 413 in the exception handler. For plain bodies, Tomcat'sserver.tomcat.max-swallow-sizecontrols how much of an oversized body it reads before closing, andserver.tomcat.max-http-form-post-sizebounds form posts, both around 2 megabytes.Header size is
server.max-http-request-header-size=8KB, and exceeding it produces a 400 from Tomcat before the application sees it. JSON depth and array size are bounded through Jackson'sStreamReadConstraints, withmaxNestingDepthandmaxStringLength, which Boot exposes through aJackson2ObjectMapperBuilderCustomizer.The important behaviour is that all of these fail before deserialisation allocates memory, so a hostile client cannot exhaust the heap with one request.
- "What would you cut under time pressure if the launch is tomorrow?"
I would keep the first three groups untouched: the management surface closed, deny by default with authenticated as the last rule, and the input size limits, because each is an hour of work and each closes a class of attack.
I would keep the CVE scan as a report rather than a blocking gate, since fixing findings may take days, and I would ship if there are no critical ones on network-facing libraries.
I would defer the read-only filesystem and dropped capabilities, the full CSP, and the dynamic scan, and book them for the first week after launch.
I would not defer the route test, because it is the only mechanical proof that nothing is exposed by accident, and it takes an afternoon. I would write down exactly which items were deferred and who owns them.
- "How do you verify the management port really is unreachable from the internet?"
From outside, not from inside. A pipeline step runs after deployment and curls
https://public-host/actuator/healthand/actuator/envfrom a runner outside the cluster, expecting connection failures or 404 from the ingress, and it fails the pipeline on a 200.Inside the cluster, a network policy restricts the management port to the monitoring namespace, and I check it with a pod in a different namespace trying to connect.
I would also confirm that the ingress does not route the management port by reading the Service definition, since a Service exposing both ports is the usual mistake.
Finally I would search the ingress access logs for any request path beginning with
/actuatorover a week, because a zero count is evidence and a non-zero count is either a scanner or a misconfiguration worth knowing about.the pipeline checkruns offline# illustrative output, run from a runner outside the cluster $ curl -s -o /dev/null -w "%{http_code}\n" https://public-host/actuator/env 404 # expected: 404 or a connection failure; a 200 fails the pipeline $ curl -s -o /dev/null -w "%{http_code}\n" https://public-host/actuator/health 404
Q150 · Design. "You have one day with a legacy Boot 2.x monolith that cannot be migrated this quarter. Design what you would change in that day to make it materially safer to run."
Reveal answer
Strong answer Assumptions: I can change configuration and small code, deploy once, and I want the highest reduction in incident risk per hour, without touching the migration.
- Morning, configuration only. Each a one-line change with a large effect:
- Hikari
connection-timeoutfrom 30 seconds to 3,max-lifetimebelow the database's idle timeout,leak-detection-thresholdat 30 seconds, and a fixed pool size from the arithmetic in Q88. spring.jpa.open-in-view=falseif the endpoints survive a quick test, otherwise scheduled for the next day.server.shutdown=gracefulwith a drain timeout and apreStopsleep in the manifest.- A startup probe so liveness cannot kill slow starts, and the database removed from the liveness group.
- Actuator exposure reduced to
health,info,prometheuson a management port, andserver.error.include-stacktrace=never. MaxRAMPercentagein place of any hard-Xmx, plusExitOnOutOfMemoryError.
- Hikari
- Midday, outbound calls. Find every
RestTemplateand HTTP client and set connect and read timeouts, which is a small code change with the largest outage-prevention value on the list. Wrap the two or three most important dependencies in a Resilience4j breaker and bulkhead. - Afternoon, visibility. Enable percentile histograms on
http.server.requestsfor the top routes, and add the Hikari pending and Tomcat busy-thread panels to the dashboard. Write three alerts: pool pending above zero for a minute, busy threads above 80 percent, and error rate above the SLO burn. - Then. A dependency CVE scan to know what the migration must fix first, and a written note of what I changed and why, so the next person is not surprised by fast failures that used to be slow.
- Trade-offs. Fast timeouts make previously slow-but-successful requests fail, which is a visible change the team must expect. That is the intended trade.
- What I would not do. Start the Java or Boot upgrade in that day, or refactor transaction boundaries, because both take longer than a day to make safe.
Picture it one partner stalling for ten minutes, with the service before and after the day, and the three alerts that would have named it.
The setup: the morning configuration and the midday client timeouts.
# ✅ FIX (morning): fail fast, drain cleanly, stop leaking
spring.datasource.hikari.connection-timeout=3000
spring.datasource.hikari.leak-detection-threshold=30000
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s
management.server.port=9090
management.endpoints.web.exposure.include=health,info,prometheus
server.error.include-stacktrace=never
# JVM flags: -XX:MaxRAMPercentage=70 -XX:+ExitOnOutOfMemoryError
// ❌ TRAP: new RestTemplate() has no read timeout: one slow partner holds a request thread for ever
@Bean
RestTemplate partnerClient(RestTemplateBuilder b) {
// ✅ FIX: bounded waits
return b.setConnectTimeout(Duration.ofSeconds(2))
.setReadTimeout(Duration.ofSeconds(5))
.build();
// Result: a stalled partner fails requests in 5 s instead of holding threads
}
The trace: a stalled partner, before and after.
request ──► controller ──► partnerClient.get()
before: no read timeout ✗ thread blocked on the socket; 200 threads gone in about a minute
after: read timeout 5 s ✓ ResourceAccessException after 5 s; thread returns; breaker opens after repeated failures
What you see: the service at three moments of a ten-minute partner stall.
| Moment | Tomcat busy threads | Hikari pending | p99 latency | Error rate |
|---|---|---|---|---|
| t = 0, partner stalls | 30 / 200 | 0 | 120 ms | 0.2% |
| t = 60 s | 200 / 200 | 0 | 60 s and climbing | 35% |
| t = 10 min | 200 / 200 | 0 | timeouts | 100%, healthy service fully unavailable |
| Moment | Tomcat busy threads | Hikari pending | p99 latency | Error rate |
|---|---|---|---|---|
| t = 0, partner stalls | 30 / 200 | 0 | 120 ms | 0.2% |
| t = 60 s | 55 / 200 | 0 | 5.2 s on partner routes only | 3% (partner routes) |
| t = 10 min, breaker open | 35 / 200 | 0 | 150 ms | 3%, fast failures |
# illustrative output
java.sql.SQLTransientConnectionException: HikariPool-1 - Connection is not available, request timed out after 3000ms.
WARN Connection leak detection triggered for org.postgresql.jdbc.PgConnection on thread http-nio-8080-exec-5, stack trace follows
Why: a missing timeout lets one dependency convert its own slowness into the service's thread exhaustion, and every other setting in the day shortens or names that same failure.
| Symptom | Root cause | Action |
|---|---|---|
| Busy threads at maximum, partner slow, pool pending 0 | no read timeout on the HTTP client | connect 2 s, read 5 s, breaker and bulkhead |
| Hikari pending above zero for a minute | pool exhausted or leaked connection | 3 s connection timeout, leak detection at 30 s, alert |
| Restarts during a database incident | database in liveness, no startup probe | liveness without the database, startup probe |
| Errors on every deploy | no graceful drain | server.shutdown=graceful, preStop sleep, grace period larger than the drain |
Land it In one day you can make the service fail fast, drain cleanly, stop leaking, and tell you when it hurts, and that buys the quarter the migration needs.
- "Setting open-in-view to false breaks half the endpoints with LazyInitializationException. What do you do with your remaining hours?"
I would put the property back and move it to tomorrow's list, because fixing lazy loading means touching queries and transaction boundaries, which is exactly the work that takes longer than a day to make safe.
What I can do in an hour is limit the damage the setting causes: keep the pool checkout timeout at 3 seconds so an open-in-view transaction that waits on a connection fails fast rather than tying up a request thread for 30 seconds, and add the
hikaricp.connections.pendingpanel so the cost of the pattern is visible.Then I would write down the three worst endpoints, found by
http.server.requestsduration, as the first candidates for a fetch join or a DTO projection. The day's goal is safer, not cleaner.what the setting breaksruns offline# illustrative output spring.jpa.open-in-view=false GET /orders/7 -> 500 org.hibernate.LazyInitializationException (the lazy collection is read after the transaction closed) action: put open-in-view back, list the 3 slowest endpoints for a fetch join or DTO projection tomorrow- "Why is setting HTTP client timeouts the most valuable item, and what are the actual values?"
Because a missing read timeout is the mechanism by which one slow dependency consumes every request thread: each request blocks forever on a socket, Tomcat's 200 threads fill within a minute, and a healthy service becomes fully unavailable because of a partner's problem.
The values are a connect timeout of 1 to 2 seconds, since a connection that has not completed in that time is not going to, and a read timeout just above the dependency's p99, typically 2 to 5 seconds for internal services and up to 30 for known slow ones.
In Boot 2.x with
RestTemplatethat isRestTemplateBuilder.setConnectTimeout(Duration.ofSeconds(2)).setReadTimeout(Duration.ofSeconds(5)), and for a rawHttpClientit isconnectTimeouton the builder andtimeouton each request.I would verify by grepping for every client construction and by a Toxiproxy test that stalls a dependency and confirms requests fail within the timeout.
- "The team says fast timeouts will cause errors that slow-but-successful requests never had. How do you handle that?"
I would agree that it is true and show that it is the intended trade.
A request that takes 25 seconds to succeed has usually already been abandoned by the user or retried by the client, so its success is mostly wasted work that held a thread.
I would look at the
http.server.requestshistogram to pick a read timeout that covers the real p99 rather than a guessed number, so the rate of newly failing requests is small and known.Then I would announce the change with the expected error rate, ship it early in the day, watch the error rate and the busy-thread panel for an hour, and be ready to raise the timeout by a few seconds if a specific dependency is legitimately slow.
The conversation to have is that a visible fast error is better than an invisible slow outage.
- "Which of these changes could make things worse, and how do you guard against that?"
Three of them carry risk. Graceful shutdown with a drain timeout longer than the pod's termination grace period means Kubernetes kills the pod mid-drain, so
terminationGracePeriodSecondsmust exceedspring.lifecycle.timeout-per-shutdown-phaseplus the preStop sleep.MaxRAMPercentagein place of-Xmxchanges the heap size and can either cause OOM kills if set too high against the container limit or GC pressure if too low, so I would set 70 percent and comparejvm.memory.maxbefore and after.Reducing Actuator exposure can break a dashboard or a deploy script that scraped an endpoint I did not know about, so I would check the ingress and management access logs for endpoint usage first.
Every change goes in as a separate commit with its own revert, and the deploy is a rolling one where I watch the first pod before the rest.
- "What would you cut if you had only a morning instead of a day?"
I would keep four things. The outbound HTTP timeouts, because they prevent the worst outage class. The Hikari connection timeout and leak detection, because they make pool exhaustion fail fast and name the leak.
The database removed from liveness with a startup probe added, because that prevents the restart loop during a database incident. And the busy-threads and pool-pending alerts, because without them nobody learns the service is hurting until users do.
I would drop the Resilience4j breakers, the histogram percentiles, the memory flags, and the CVE scan to the next day, and I would leave the Actuator exposure change for a time when I can check who depends on it.
A morning that ends with fast failure and two alerts is a good morning.
11 · RecapWhat You Can Do Now
- You can explain what happens between
main()and "ready": bean definitions from three sources, the lifecycle, the post-processor that swaps in a proxy, and the auto-configuration conditions that decide what exists - You can read the condition evaluation report and the startup timeline instead of guessing why a bean is missing or why startup takes 90 seconds
- You can trace one request through Tomcat, the filter chain, the DispatcherServlet, interceptors, and the controller, and say which layer owns each failure, including the 401 that never reaches your advice
- You can do the thread-pool and connection-pool arithmetic aloud, explain why the pool and not the thread count is usually the ceiling, and say what virtual threads change
- You can name the exact reasons
@Transactionaldid not roll back, and restructure a method that makes an HTTP call inside a transaction - You can design a test strategy that keeps contexts to a handful and uses the real database, and explain why a rolled-back test transaction can lie
- You can configure probes, graceful shutdown, and memory for a Boot service in Kubernetes so that a deploy drops nothing and a database failover does not restart the fleet
- You can plan a 2.7 to 3.5 to 4.x migration across a fleet as ordinary pull requests, and say where Jackson 3, Hibernate 6 and 7, and the removed test annotations will bite
Close the page and write down, from memory: the six causes, in order of likelihood, for a
@Transactional method that did not roll back, and the three metric shapes that
distinguish a slow query, a leak, and plain load when the Hikari pool is exhausted. Then reach
back to Chapter E8's isolation chapter: which isolation level is the database default that
Spring's Isolation.DEFAULT inherits on MySQL, and which on PostgreSQL, and what
anomaly does each still permit that a checkout service must guard against in application code?