← All topics
Start ▶
Spring
Beans, DI, @Transactional, Spring Boot, Security and Cloud.
300 questions
Level:
No questions match — try other words or turn a level back on.
1
What is the Spring Framework and what problem does it solve?
Spring is a Java framework that creates your objects and wires them together for you (IoC/DI), and adds ready-made pieces on top: transactions, web, security and more.
2
What do you understand by IoC (Inversion of Control)?
With IoC, control over creating and wiring objects moves from your code to the framework. You say what you need; Spring decides when and how to create it.
3
What kinds of Dependency Injection are there, and which one is preferred?
There are three ways: constructor, setter and field. Usually people pick the constructor — the dependency becomes mandatory and the field stays final.
4
What is a bean? How is it different from a regular Java object?
A bean is an object that the Spring container creates and manages. The class itself is ordinary; the difference is that Spring creates it, wires it and tracks its lifecycle.
5
What is the difference between @Component, @Service, @Repository and @Controller?
All four turn a class into a bean. @Service, @Repository, @Controller are more specific flavours of @Component; on top of that, @Repository translates database errors into Spring exceptions.
6
What is the ApplicationContext and what does it do when the application starts?
The ApplicationContext is Spring's IoC container: it creates beans, holds them and wires them, and also gives access to configuration, events and resources.
7
How does @Autowired work?
Spring looks up a bean of the required type in the context and puts it into the constructor, setter or field. If it finds exactly one, it passes it in; if it finds none or several, startup fails.
8
If one interface has two implementations, which one does Spring inject?
It can't choose by itself and throws NoUniqueBeanDefinitionException. You tell it which one to use with @Primary or @Qualifier, or take all of them as a List/Map.
9
How is Spring Boot different from plain Spring?
Spring Boot is a layer on top of Spring: auto-configuration, ready-made starters, an embedded server, and running everything as a single jar.
10
Why do we need starters (spring-boot-starter-*)?
A starter is a "package" that, with a single dependency, brings in the libraries you need in versions that work with each other. Then Boot's auto-config sets them up.
11
What are application.properties and application.yml used for?
Both keep configuration (port, database URL, log level, etc.) outside the code. The only difference is the syntax: properties is flat key=value, yml is hierarchical.
12
How do you read a configuration value with the @Value annotation?
@Value("${key}") takes the value from the Environment and puts it into a field or parameter; with ${key:default} you can also give a default value.
13
What's inside @SpringBootApplication?
It's a combination of three annotations: @SpringBootConfiguration (i.e. @Configuration), @EnableAutoConfiguration and @ComponentScan.
14
What is the difference between @RestController and @Controller?
@RestController = @Controller + @ResponseBody: the object a method returns is written straight into the response as JSON. A plain @Controller usually returns a template (view) name.
15
What is the difference between @PathVariable and @RequestParam?
@PathVariable takes a piece of the URL path (/users/42), while @RequestParam takes a query parameter (/users?page=2). The first points to a resource, the second is for filters or options.
16
What does @RequestBody do?
It turns the JSON in the request body into a Java object. It's usually used in POST and PUT to accept a DTO.
17
Why do we need ResponseEntity?
With ResponseEntity you fully control the response: besides the body, you also set the HTTP status and headers.
18
How does a repository interface work in Spring Data JPA, given that we never write its implementation?
At startup Spring builds a proxy for the interface. Standard methods like save and findById come from the ready-made SimpleJpaRepository; the rest are turned into queries from the method name or from @Query.
19
How do you write a derived query (a query from the method name), and when does it become awkward?
The name is built from findBy + field names + conditions (And, Or, Between, OrderBy...). When the conditions pile up and the name gets long, it's better to switch to @Query or a Specification.
20
What are the @Entity and @Id annotations for?
@Entity maps a class to a table, and @Id marks the primary key field. Without @Id, JPA can't tell which row an object is.
21
What does @Transactional do?
It runs the method in a single transaction: if everything goes fine it commits, if a RuntimeException is thrown it rolls back. Data is never left half-saved.
22
What is a bean's default scope, and what other scopes are there?
Instance — singleton (default): one per context; prototype: a new one on every injection or getBean; request: one per HTTP request; session: one per HTTP session; application: one per ServletContext
23
What are profiles (spring.profiles.active) for?
With profiles you run the same code in different environments (dev, test, prod) with different settings and beans.
24
What is an embedded server in Spring Boot, and why don't we install Tomcat separately?
An embedded server is Tomcat (or Jetty, Undertow) packaged into the application as a library. When you run java -jar, the server starts along with it.
25
What is a "fat jar" in Spring Boot?
A fat jar is a single jar that holds your own classes plus all the dependency jars. Nothing else is needed for java -jar app.jar.
26
How do you declare a bean with @Configuration and @Bean, and when do you need it?
The object returned by a @Bean method in a @Configuration class becomes a bean. You need it for library classes you didn't write yourself, or for objects that are complicated to create.
27
How do you catch exceptions thrown in controllers in one place and return a clean response?
You write @ExceptionHandler methods in a @RestControllerAdvice class: the status and response body for each exception type live in one place.
28
How does Bean Validation (@Valid, @NotBlank, @Size) work in Spring?
You put constraint annotations on DTO fields and write @Valid on the controller parameter. Spring validates the request before it reaches the method and returns 400 if something is wrong.
29
What is Spring Boot Actuator, and what does /actuator/health show?
Actuator is a set of ready-made endpoints for monitoring the application: health, metrics, info, loggers and more. /actuator/health shows whether the application and its dependencies (database, disk, Redis) are alive.
30
How do you write logs in Spring Boot, and how do you change the log level?
In code you use an SLF4J Logger, with Logback underneath by default. You change the level with a setting like logging.level.<package>=DEBUG.
31
What are the main stages a bean goes through from creation to destruction?
Spring first creates the object, then injects its dependencies, calls the init callbacks and, if needed, wraps it in a proxy. When the context closes, the destroy callbacks run.
32
Which packages does @ComponentScan scan, and what happens if a class is outside the main package?
By default, the package containing @SpringBootApplication and all its subpackages are scanned. Spring doesn't see a @Component class outside it, so it doesn't become a bean.
33
When do you use @GetMapping, @PostMapping, @PutMapping and @DeleteMapping?
These are shorthand forms of @RequestMapping, each bound to one HTTP method. GET reads, POST creates a new resource, PUT replaces it completely, DELETE removes it.
34
What is the difference between PUT and PATCH in a REST API, and how do you write them in Spring?
PUT replaces the resource completely: a field you didn't send becomes empty. PATCH changes only the fields that arrived. PUT is idempotent, while PATCH has no such guarantee.
35
How do you read HTTP header and cookie values in a controller?
You read a header with @RequestHeader and a cookie with @CookieValue. Both are required by default; to make them optional, set required = false or a defaultValue.
36
What do the server.port and server.servlet.context-path settings do?
server.port is the port the embedded server listens on (default 8080). context-path adds a common prefix in front of all URLs, for example /shop.
37
What is the difference between CrudRepository, PagingAndSortingRepository and JpaRepository?
What it adds — CrudRepository: save, findById, findAll, deleteById, count, existsById; ListCrudRepository: the same, but returns List instead of Iterable; PagingAndSortingRepository: findAll(Pageable), findAll(Sort); JpaRepository: flush, saveAndFlush, deleteAllInBatch, getReferenceById and all of the above
38
How do the IDENTITY and SEQUENCE strategies in @GeneratedValue differ?
With IDENTITY the database assigns the id at INSERT time, so Hibernate has to INSERT every record immediately. With SEQUENCE the id is fetched from the sequence ahead of time, and batch inserts can work.
39
What does mappedBy mean in a @OneToMany and @ManyToOne relationship?
mappedBy marks the inverse side of the relationship: "the foreign key is controlled not by me but by the field on the other side". The FK column lives in the table that has the @ManyToOne.
40
What is the difference between FetchType.LAZY and FetchType.EAGER?
EAGER loads the related object right away together with the entity, while LAZY loads it the first time you touch it. In practice we set LAZY almost everywhere.
41
When do you need the @Table and @Column annotations?
When the table or column name (or a property like length or precision) differs from the default. For example, when the table name is a reserved word in SQL, or a column is named differently in a legacy database.
42
What happens if you add Spring Security to a project and configure nothing?
Every endpoint is locked and asks for a login. Boot creates a single user named "user" and prints its password to the log, randomly generated on each startup.
43
What is the difference between authentication and authorization?
Authentication is "who are you?": a login, password or token is checked. Authorization is "are you allowed to do this?": a role or permission is checked. The first comes before the second.
44
In Spring Security 6, how do you define which URLs are open and which are locked through a SecurityFilterChain bean?
In a @Configuration class you write a @Bean that returns a SecurityFilterChain, and inside authorizeHttpRequests you set rules with requestMatchers. The rules are checked top to bottom, with anyRequest at the very end.
45
What is AOP, and what problems does it solve in a real project?
AOP is a way to collect "side" logic that repeats across many methods (logging, transactions, security, timing) in one place. The business code stays clean.
46
Explain the AOP concepts of aspect, advice, pointcut and join point.
A join point is a point where an aspect can attach (in Spring, a method call). A pointcut is an expression that says which join points to pick. Advice is the code that runs there. An aspect is the class that holds the pointcuts and advice.
47
How do the @Before, @AfterReturning, @AfterThrowing, @After and @Around advice types differ?
When / What it can do — @Before: before the call / sees the arguments, can stop the call by throwing an exception; @AfterReturning: after a normal return / reads the result (returning = "result"); @AfterThrowing: when an exception is thrown / sees the exception, but can't "swallow" it; @After: always (like finally) /…
48
What does Spring Boot DevTools give you, and should it go to production?
DevTools is a set of conveniences for working locally: it quickly restarts the application when code changes, turns off the template cache, and has LiveReload. Not for prod, only for your own machine.
49
How do you test a controller endpoint with MockMvc?
@WebMvcTest brings up only the web layer, and MockMvc sends an HTTP request without opening a server, with the service mocked. Then you check the status, headers and the JSON body.
50
What is Spring Cloud, and what problems was it created to solve?
Spring Cloud is a set of projects on top of Boot. It covers the typical problems of a distributed system: central configuration, service discovery, a gateway, load balancing, circuit breakers.
51
Why do you need service discovery (for example, Eureka)?
Microservices run as many instances, and their IPs keep changing. With discovery, each instance registers itself in a registry, and the others ask for an address by service name.
52
What does @RequestMapping on a controller class give you?
@RequestMapping on the class gives a common URL prefix (and produces/consumes if needed) for every method in the controller. The path on the method is appended to it.
53
Why does an update or delete @Query in Spring Data JPA need @Modifying?
By default Spring Data assumes @Query is a SELECT. @Modifying tells it "this is an UPDATE or DELETE", and the query goes through executeUpdate. There's one more requirement: a transaction.
54
What is the difference between findById and getReferenceById?
findById reads from the database and returns an Optional, empty if there's no record. getReferenceById gives you a proxy without a SELECT, and only goes to the database when you touch a field; if the record doesn't exist, EntityNotFoundException is thrown at that point.
55
How does a Java object returned by a controller turn into JSON?
Spring MVC passes the object a @RestController method returns to an HttpMessageConverter. Jackson is on the classpath, Boot sets up MappingJackson2HttpMessageConverter, and it turns the object into JSON through its getters.
56
What changes when you put @Lazy on a bean?
Singleton beans are normally created at startup, but a @Lazy one is created the first time it's needed. If you put it on an injection point, Spring immediately hands over a proxy instead of the real bean.
57
What is the difference between @Valid and @Validated?
@Valid comes from Jakarta Bean Validation: it makes the object and the nested objects inside it get validated. @Validated comes from Spring: it knows about groups, and on a class it also validates method parameters.
58
Why did the javax.* imports change to jakarta.* in Spring Boot 3, and which Java version do you need?
Java EE moved to the Eclipse Foundation and became Jakarta EE, and for legal reasons the javax name could no longer be used. Spring 6 and Boot 3 are built on Jakarta EE 9+, and the minimum Java is 17.
59
How do you expose Actuator endpoints over HTTP, and which ones should you never leave open?
You list the endpoints you need in management.endpoints.web.exposure.include; by default only health is exposed over HTTP. env, heapdump and configprops reveal sensitive things, so don't open them to the internet.
60
How do you accept a file upload (MultipartFile) in a controller?
The request is multipart/form-data, and in the controller you take a MultipartFile parameter with @RequestParam or @RequestPart. The size limit is configured in spring.servlet.multipart.
61
Why don't you need @Autowired on a class with a single constructor?
Since Spring 4.3, if there's only one constructor, Spring just uses it. You only need @Autowired when there are several constructors, to tell Spring which one to pick.
62
Why is field injection (@Autowired private ...) not recommended?
Dependencies get hidden, fields can't be final, and you can't create the object normally in a test without Spring. You also stop noticing when the class has grown too big.
63
What's the difference between @Primary and @Qualifier, and which one wins if both are present?
@Primary is a general hint: "if there are several candidates, take this one". @Qualifier picks a specific bean at a specific injection point. When they clash, @Qualifier wins.
64
Why is it dangerous to keep mutable state in a singleton bean?
A singleton bean is used by many threads at once — each HTTP request runs on its own thread. If you write request data into a field, one user's data gets mixed up with another's.
65
When are @PostConstruct and @PreDestroy called?
@PostConstruct runs once, after the bean has been created and all dependencies are injected. @PreDestroy runs when the context is closing, before the bean goes away (it's never called for prototype beans).
66
What is a circular dependency, and what changed about it after Spring Boot 2.6?
Bean A depends on B, and B depends on A — that's a circular dependency. Since Boot 2.6 it's forbidden by default and the app fails at startup. The real fix is to fix the design.
67
Why does this code throw a NullPointerException?
@Value is injected into the field after the object is created. While the constructor runs, prefix is still null. Take the value as a constructor parameter instead.
68
If a setting is defined in several places, which value does Spring Boot use?
There's an order: command-line arguments > env variables > profile file (application-prod.yml) > the common application.yml > @PropertySource > defaults. The one on the left overrides the one on the right.
69
What's the difference between @ConfigurationProperties and @Value, and when do you use each?
One or two values — @Value. Lots of settings under one prefix — @ConfigurationProperties: a typed class, validation, IDE autocomplete.
70
When you see "No qualifying bean of type ... available", what do you check?
Spring couldn't find a bean of that type. Usually the annotation is missing, the class isn't covered by component scan, a conditional bean (@Profile, @ConditionalOn...) wasn't created, or the type is wrong.
71
How does save() in Spring Data JPA tell a new object from an existing one?
SimpleJpaRepository.save first checks whether the entity is new: if the id is null (0 for primitives) — persist, otherwise — merge. If there's a @Version field, it looks at that instead.
72
What happens if you put @Transactional on a private method?
Nothing — no transaction is opened. Spring works through a proxy, and the proxy only intercepts public methods called from outside (in Spring 6 with CGLIB, protected/package too). A private method is completely invisible to the proxy.
73
What are the ways to return an HTTP status code from a controller?
There are three: set the status yourself with ResponseEntity, put @ResponseStatus on the method or the exception class, or throw an exception and set the status in an @ExceptionHandler.
74
Why is it better to return a DTO instead of an entity in an API response?
An entity is the database structure, a DTO is the API contract. If you return the entity directly, sensitive fields leak out, lazy associations cause errors or extra queries, and every database change breaks the API.
75
How does Spring name a bean, and what happens when two beans end up with the same name?
For @Component the name is the class name with a lowercase first letter (orderService); for @Bean it is the method name. If two names collide, Boot fails at startup by default (BeanDefinitionOverrideException).
76
What response does the client get if a request to this endpoint is sent without the age parameter, or with age=abc?
If age is missing, the required parameter is absent, so 400. If abc comes in, it can't be converted to int, so again 400. But if you make it required = false and leave the type as primitive int, a request without the parameter gives 500.
77
Why does a bidirectional relationship cause infinite recursion when you return an entity directly as JSON?
Jackson writes Order and moves into items, from each item back into order, and the loop never stops, ending in a StackOverflowError or a depth error. The cleanest fix is to return a DTO, not the entity.
78
What is the difference between @Bean methods inside @Configuration and inside @Component?
A @Configuration class is wrapped in a CGLIB proxy, so when one @Bean method calls another, you get the singleton from the container. In a @Component (lite mode) that's an ordinary Java call, which creates a new object every time.
79
If you modify an entity inside a transaction, why is it written to the database even though you never call save()?
This is dirty checking. An entity loaded inside a transaction becomes managed, and Hibernate remembers its initial copy. On flush or commit it finds the changed fields and sends the UPDATE itself.
80
How is a profile-specific file like application-dev.yml loaded, and how does it merge with the main file?
application.yml is read first, then the active profile's application-{profile}.yml is laid over it: identical keys come from the profile file, the rest from the main file. With several profiles, the last one wins.
81
What is the difference between @Value("${...}") and @Value("#{...}")?
${...} is a property placeholder: the value comes from the Environment (yml, environment variables), and you can write a default after ":". #{...} is a SpEL expression: it is evaluated, and it can use other beans, methods and operators.
82
In Spring Security, why don't hasRole("ADMIN") and hasAuthority("ADMIN") behave the same?
hasRole adds the ROLE_ prefix itself and looks for ROLE_ADMIN. hasAuthority compares the string as it is. Depending on the name the authority was given under, one passes and the other gets 403.
83
If several @ExceptionHandler methods match one exception, which one does Spring pick?
Within a single advice, the handler closest to the exception in the hierarchy is chosen. If there are several advices, Spring looks at them in @Order, and the first advice that has a matching handler wins, even if another one has a more specific handler.
84
When @SpringBootTest tests multiply, why does the test suite suddenly become very slow?
Spring TestContext caches the context, and tests with the same configuration reuse it. If each test class brings a different mock, profile or property, the key changes and a new context is started, each taking several seconds.
85
/actuator/health shows DOWN, but the application's API works. What do you check?
Health is the sum of several indicators: db, diskSpace, redis, mail and so on. If one is DOWN, the overall status is DOWN too. You turn on the details and find which component is at fault.
86
What happens in an @Around advice if proceed() is not called, or its result is not returned?
If proceed() isn't called, the original method doesn't run at all. If it's called but the result isn't returned, the caller gets null; for a method returning a primitive, AopInvocationException. In both cases the system silently misbehaves.
87
How do you call another service with OpenFeign, and how are error responses handled?
You write an interface and annotate it with @FeignClient, and Spring Cloud generates the implementation. By default 4xx/5xx come out as FeignException, and with an ErrorDecoder you can turn them into your own exceptions.
88
What risk comes from storing an enum field without @Enumerated, or with EnumType.ORDINAL?
By default an enum is stored as ORDINAL, that is, its position number (0, 1, 2). If someone adds a new value in the middle or reorders them, the old numbers in the database take on a different meaning, and no error shows up anywhere.
89
When you use Lombok's @RequiredArgsConstructor, why is the @Qualifier on the field ignored?
When Lombok generates the constructor, by default it doesn't copy the field's @Qualifier to the parameter. Spring looks at the parameter, finds several matching beans, and either fails or picks the @Primary one.
90
How do you see the SQL queries Hibernate sends, with their parameters, and why is show-sql not enough?
spring.jpa.show-sql prints SQL without parameters straight to System.out. The right way is through a logger: org.hibernate.SQL=DEBUG shows the query, and in Hibernate 6 org.hibernate.orm.jdbc.bind=TRACE shows the parameter values.
91
What's the difference between REQUIRED and REQUIRES_NEW propagation in @Transactional?
REQUIRED (the default) joins an open transaction if there is one, otherwise opens a new one. REQUIRES_NEW always opens a new, separate transaction, and the outer one is suspended meanwhile.
92
What does @Transactional(readOnly = true) actually give you?
Hibernate turns off flush and dirty checking (saving memory and CPU), the JDBC connection becomes read-only, and some routing setups use it to send the query to a replica. But it doesn't 100% forbid writes.
93
Which exceptions make @Transactional roll back, and which don't?
By default only unchecked ones (RuntimeException and Error) cause a rollback. On a checked exception (IOException or your own class extending Exception) the transaction commits. You can change this with rollbackFor.
94
How do you use ProblemDetail to return all API errors in the same format?
Spring 6.1+ supports the RFC 9457 format (6.0 followed RFC 7807). spring.mvc.problemdetails.enabled=true switches the standard errors to it, and for your own exceptions you return a ProblemDetail from a @RestControllerAdvice or extend ErrorResponseException.
95
How do Pageable and Page work in Spring Data, and what should you watch for on a large table?
Pageable is the page number, size and sorting. Page returns the total count on top of the results, and that takes a separate COUNT query. If you don't need the total, use Slice.
96
What's the difference between writing a JPQL query and a native SQL query with @Query?
JPQL is written with entity and field names and isn't tied to a database. Native SQL uses tables and columns and unlocks the database's own features (window functions, JSONB, CTEs), but it won't port to another database.
97
What is the filter chain in Spring Security, and how is a request checked?
Spring Security is a chain of Servlet filters. Before a request reaches the controller it passes through the filters: first authentication (who are you?), then authorization (are you allowed?). Who the user is lives in the SecurityContext.
98
How should user passwords be stored, and how is that done in Spring?
You don't store passwords in plain text, and not with a plain hash (MD5, SHA-256) either. You need a slow, salted algorithm — BCrypt, Argon2 or PBKDF2. In Spring, PasswordEncoder does this.
99
How does @Async work, and which thread does it run on?
With @EnableAsync, Spring wraps the bean in a proxy. When you call an @Async method, the work is handed to an executor and the caller moves on without waiting. In Boot the default is a ThreadPoolTaskExecutor (threads named task-).
100
What's the difference between fixedRate, fixedDelay and cron in @Scheduled?
fixedRate counts time from when the previous run started, fixedDelay — from when the previous run finished. cron follows the calendar, for example every day at 03:00.
101
How does @Cacheable work, and when doesn't it behave as expected?
Before calling the method, the proxy builds a key from the arguments and checks the cache. On a hit the method isn't called and the value comes from the cache. On a miss the method runs and the result goes into the cache.
102
How do events work in Spring with ApplicationEventPublisher and @EventListener?
One bean publishes an event, others listen for it with @EventListener. By default it's all synchronous — the listener runs on the publisher's thread and inside its transaction.
103
RestTemplate, RestClient or WebClient — which one would you pick for a new project?
For a regular blocking app — RestClient (Spring 6.1+), with a fluent API. If it's reactive or you make lots of parallel calls — WebClient. RestTemplate still works, but it's in "maintenance" mode; don't use it in new code.
104
What's the difference between @SpringBootTest and @WebMvcTest?
@SpringBootTest starts the whole application — for integration tests. @WebMvcTest loads only the web layer (controllers, advice, filters, Jackson), and services are mocked — fast and focused.
105
What's the difference between @MockitoBean (formerly @MockBean) and a plain Mockito @Mock?
@Mock is for a plain unit test without Spring. @MockitoBean replaces a real bean in the Spring context with a mock, and every bean that injects it gets the mock too.
106
When do you choose programmatic transactions with TransactionTemplate over declarative @Transactional?
When the transaction needs to be smaller than a method: only part of a method is in the transaction, committing a big job in chunks, or a place where the proxy doesn't work (self-invocation). With TransactionTemplate the boundary is visible in the code.
107
How do you automatically fill in createdAt, updatedAt and createdBy fields in Spring Data JPA?
Spring Data has auditing: you enable @EnableJpaAuditing, attach AuditingEntityListener to the entity, and put @CreatedDate, @LastModifiedDate and @CreatedBy on the fields. An AuditorAware bean tells it who the user is.
108
What do you configure in Spring Security to return 401 and 403 responses in your own JSON format?
An error that originates in a filter never reaches @RestControllerAdvice. So you write an AuthenticationEntryPoint for 401 and an AccessDeniedHandler for 403, and wire them into the SecurityFilterChain through exceptionHandling().
109
How does @RefreshScope work, and what are the limitations of updating a setting without restarting the application?
@RefreshScope (Spring Cloud) wraps the bean in a proxy. When /actuator/refresh is called, the Environment is re-read, such beans are discarded, and they're recreated with the new value on the next call. It works per instance and doesn't suit every bean.
110
How do you test a controller with Spring Security enabled using @WebMvcTest?
You bring in the security configuration with @Import, provide the user with @WithMockUser or .with(user(...)) / .with(jwt()), and add .with(csrf()) to POSTs where needed. Then you check 200, 401 and 403 separately.
111
How do you test a client that calls an external HTTP API without hitting the real service?
@RestClientTest brings up only the HTTP client layer, and with MockRestServiceServer you provide the expected request and a fake response. That way the URL, headers, JSON and error cases are checked quickly, with no network.
112
How do you handle 4xx and 5xx responses when calling an external API with RestClient?
By default RestClient throws HttpClientErrorException for 4xx and HttpServerErrorException for 5xx. With onStatus or the builder's defaultStatusHandler you turn them into your own exceptions; if you need full control, use exchange().
113
How do Flyway migrations work in Spring Boot, and what rules do you follow with migration files?
With flyway-core added, Spring Boot runs the V1__...sql files from the db/migration folder in order at startup and records the result in the flyway_schema_history table. You never edit an applied file; you add a new version.
114
How do you cache responses in Spring MVC with ETag and Cache-Control headers?
For GET responses that rarely change, you set cacheControl(...) and eTag(...) on the ResponseEntity. The next time the client sends If-None-Match; if the version hasn't changed, Spring returns a 304 with no body and saves traffic.
115
What do you configure in Spring to return validation and business error messages in Uzbek, Russian and English?
The texts go into files like messages_uz.properties and messages_ru.properties, MessageSource reads them, and the language is determined from the Accept-Language header through a LocaleResolver. Bean Validation messages are also taken from these files in the {key} form.
116
How do you configure Spring Boot logging so logs are plain text locally and JSON in production?
In Spring Boot 3.4+, switching to JSON is a single setting, logging.structured.format.console (ecs, logstash or gelf), and you put it in the prod profile. In older versions you separate the appenders with <springProfile> inside logback-spring.xml.
117
How do you see in the logs when @Transactional opens a transaction and when it commits or rolls back?
You turn on DEBUG for the transaction manager in use (for example JpaTransactionManager) and TRACE for org.springframework.transaction.interceptor. In the log you see the lines "Creating new transaction", "Participating in existing transaction", "Committing" or "Rolling back" in sequence.
118
How do you write your own HealthIndicator, and when is it useful?
You create a bean that implements the HealthIndicator interface and return Health.up() or Health.down() from the health() method; its name is added to /actuator/health automatically. It's useful for showing a dependency on an external system, but you have to wire it into readiness carefully.
119
How do you build the strategy pattern by injecting all implementations of an interface as a List or Map?
If you ask for List<PaymentProvider>, Spring injects all beans of that type; if you ask for Map<String, PaymentProvider>, it injects a map keyed by bean name. That way a new implementation is added without an if/switch chain.
120
Why does the order of requestMatchers rules matter in a Spring Security configuration? What's wrong with this configuration?
The rules are checked top to bottom and the first match is applied. Here authenticated() for /api/** comes first, so the /api/admin/** rule below it never gets a turn, and any logged-in user can call the admin API.
121
Why doesn't a @Transactional (or @Cacheable, @Async) method work when it is called from within the same class?
Because these annotations work through a proxy. A call from outside goes through the proxy, but inside the class this.method() goes straight to the real object. The proxy is bypassed and the annotation does nothing.
122
What is the difference between a JDK dynamic proxy and a CGLIB proxy, and when does Spring use which?
A JDK proxy is built from an interface and intercepts only the interface methods. CGLIB generates a subclass of the class. Since Boot 2.0 CGLIB is the default (proxyTargetClass=true), even when there is an interface.
123
How does the N+1 problem appear in Spring Data JPA, and how do you detect and fix it?
You load a list with one query, then touch a lazy association on each element, and every one of them fires another query: 1 + N. The fix is JOIN FETCH, @EntityGraph, batch fetching or a DTO projection.
124
What causes LazyInitializationException, and what is the right way to fix it?
It appears when you touch a lazy association after the session (transaction) has closed. The right fix is to load the data you need up front inside the transaction (fetch join, entity graph, DTO), not to stretch the session.
125
What is spring.jpa.open-in-view, and why do many people recommend turning it off?
Open Session in View keeps the Hibernate session open for the whole HTTP request, until the JSON is written. In Boot it is on by default and warns at startup. It hides lazy errors, but in exchange it holds a DB connection for a long time and creates invisible queries.
126
What happens if you use @Transactional inside an @Async method, or call an @Async method from inside a transaction?
An async method runs on another thread, and a transaction is bound to its thread. So it doesn't see the caller's transaction: if it is @Transactional itself, it opens a separate new transaction, and it may not see data the caller hasn't committed yet.
127
How does @TransactionalEventListener work, and what traps does it have?
The listener doesn't run the moment the event is published, but when the transaction reaches the required phase (AFTER_COMMIT by default). If there is no transaction, by default it is not called at all.
128
How does optimistic locking (@Version) work, and when would you choose it?
The entity has a version field; the UPDATE goes out with where id = ? and version = ? and increments the version by one. If someone changed the row earlier, 0 rows are updated and an OptimisticLockingFailureException is thrown.
129
When do you need a pessimistic lock (@Lock(PESSIMISTIC_WRITE)), and what are its risks?
It locks the row at read time (SELECT ... FOR UPDATE), and others queue up to modify it. You need it when conflicts are frequent and a retry is expensive. The risks are waiting, deadlocks and pool exhaustion.
130
What is a BeanPostProcessor, and where does Spring itself use it?
A BeanPostProcessor is a hook into every bean after it is created: it is called before and after init. Spring uses it for @Autowired, @PostConstruct, @Async, the @Transactional proxies and validation.
131
What is the difference between BeanFactoryPostProcessor and BeanPostProcessor?
A BeanFactoryPostProcessor works on the bean definitions (BeanDefinition) before any beans are created. A BeanPostProcessor works on the finished bean objects.
132
What happens if you inject a prototype bean into a singleton bean, and how do you solve it?
The singleton is created once and injection happens once, so it keeps that one prototype instance forever. If you need a fresh one each time, use ObjectProvider, a @Lookup method or a scoped proxy.
133
How can you inject a request-scoped bean into a singleton service, when the singleton is created at application startup?
With a scoped proxy. The singleton gets a proxy instead of the real bean; on every call the proxy finds the instance for the current HTTP request and forwards the call to it.
134
Why does @ConditionalOnMissingBean show up so often in auto-configurations, and how do you tell which auto-configuration kicked in?
Boot creates a bean on the condition "if you haven't provided your own", which is why you can replace any default with your own bean. Which conditions matched shows up in the Conditions Evaluation Report printed with --debug, or in /actuator/conditions.
135
How do you use @Conditional to create a bean under your own condition?
The ready-made conditions are usually enough: @ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnBean. For more complex logic, you write a Condition implementation and add @Conditional(MyCondition.class).
136
How do you choose the HikariCP connection pool size? Is "bigger is better" correct?
No. The database can only run a certain number of queries well at the same time; extra connections just add queueing in the database, context switching and memory use. Usually a small pool (10-30) with short transactions works better than a big pool.
137
You see "Connection is not available, request timed out after 30000ms". What do you check?
Every connection in the pool is busy, and none was freed within 30 seconds. Most of the time the pool isn't too small; connections are being held too long: a slow query, an external call inside a transaction, an unclosed connection or a deadlock.
138
What path does an HTTP request take to a controller method in Spring MVC?
Tomcat → servlet filters (Security lives here too) → DispatcherServlet → HandlerMapping finds the controller method → interceptors → HandlerAdapter prepares the arguments (reads JSON, validates) → the method → an HttpMessageConverter writes the response.
139
What is the difference between HandlerInterceptor and a Servlet Filter, and when do you use which?
Filter / HandlerInterceptor — Level: Servlet container / Spring MVC; Knows which controller it is: no / yes (HandlerMethod); Wraps request/response: yes (wrapper) / no; Before/after Spring Security: configurable / always after; Exception goes to @ControllerAdvice: no / yes
140
How do you configure Jackson in Spring Boot: dates, null fields, unknown fields?
With spring.jackson.* settings or a Jackson2ObjectMapperBuilderCustomizer. By default Boot writes dates in ISO format and doesn't fail on an unknown field (FAIL_ON_UNKNOWN_PROPERTIES=false).
141
How do you write your own validator when the standard annotations aren't enough, and what are validation groups for?
You write an annotation and a ConstraintValidator for it. Groups let you validate the same DTO with different rules in different situations (create vs. update).
142
How do you build stateless JWT authentication with Spring Security?
Don't write your own filter; use oauth2ResourceServer().jwt(). Spring reads the token, checks the signature and expiry, and turns it into an Authentication. No session is opened.
143
What is CSRF protection, when do you need it, and when is it safe to turn off?
CSRF is a foreign site sending a request through the user's browser with the user's cookie. If the session lives in a cookie, you need protection. For an API that works only with a token in the Authorization header, it is usually turned off.
144
Why does a CORS error happen, and how do you configure it properly in Spring?
When a page on another domain sends a request, the browser checks the Access-Control-Allow-* headers to see whether the server allows it. If not, it doesn't hand the response to JavaScript. In Spring you configure CORS together with Security, with an explicit list of domains.
145
How does @PreAuthorize work, and how does it differ from URL-level checks?
With @EnableMethodSecurity on, @PreAuthorize checks a SpEL expression through a proxy before the method is called. URL rules run when the request comes in, while method security works at the business method level and can also decide based on the arguments.
146
What problems do you run into with @Cacheable around key choice, TTL and cache refresh?
Mainly these: a wrong key (collisions, or the cache never hits), no TTL (the cache grows forever and goes stale), local caches on several instances drifting apart, and someone mutating an object that sits in the cache.
147
What do Spring Data projections (interface and DTO) give you?
Instead of the whole entity, you fetch only the columns you need. The query gets lighter, the dirty checking and persistence context overhead goes away, and lazy problems become rarer.
148
How do you build a dynamic query from user-selected filters in Spring Data?
With Specification (on top of the JPA Criteria API), Querydsl or Query by Example. Each filter is a separate condition added depending on the incoming parameter, so you don't end up with a pile of findByAAndBAndC methods.
149
Why is saving 100,000 rows with saveAll so slow, and how do you speed it up?
By default every row becomes its own INSERT, an IDENTITY id turns batching off completely, and the persistence context holds every object in memory and slows down dirty checking. The fix: JDBC batching, a SEQUENCE id, flush/clear in chunks, or plain JDBC.
150
Why is spring.jpa.hibernate.ddl-auto=update dangerous in production, and what do you use instead?
update only changes the schema in the "add things" direction, and only roughly: it doesn't drop columns, can't rename them, doesn't migrate data, and doesn't record what it did anywhere. In prod you change the schema with Flyway or Liquibase migrations and keep ddl-auto at validate or none.
151
Why is Testcontainers better than H2 for integration tests, and how do you wire it into Spring Boot?
H2 only imitates PostgreSQL: the SQL dialect, types, indexes and locking behavior are different, so the test is green and prod breaks. Testcontainers starts a real database in Docker, and in Boot 3.1+ @ServiceConnection configures the connection automatically.
152
What does @DataJpaTest load, what doesn't it load, and what are its traps?
It loads only the JPA layer: entities, repositories, EntityManager, Flyway/Liquibase. Services and controllers aren't included. Each test runs in a transaction that's rolled back at the end, and by default an embedded database replaces the real one.
153
What traps does putting @Transactional on a test lead to?
The test method runs inside a transaction that's rolled back at the end. The database stays clean, but it hides real commits, lazy loading, AFTER_COMMIT listeners and behavior on other threads — the test passes, and prod falls over.
154
How does graceful shutdown work in Spring Boot, and what do you need to do so requests don't get cut off during a deploy?
With server.shutdown=graceful, once the stop signal arrives the app stops taking new requests, finishes the in-flight ones within timeout-per-shutdown-phase, then closes the beans. Since Boot 3.4 this is the default.
155
How do you add business metrics with Micrometer, and what mistakes should you avoid?
You create a Counter, Timer or Gauge through MeterRegistry, and Actuator exports them to Prometheus and others. The most common mistake is putting an unbounded value (user id, order id) in a tag: the number of metrics explodes.
156
How do you enable virtual threads in Spring Boot 3.2+, and what should you watch out for?
spring.threads.virtual.enabled=true (Java 21+) — Tomcat runs requests, @Async and scheduler tasks on virtual threads. Throughput goes up in apps with lots of blocking I/O, but you need to watch for pinning, unbounded concurrency and ThreadLocal.
157
Where does an exception thrown in an @Async void method go, and how do you keep it under control?
It never reaches the caller — the caller has already moved on. For void methods the error lands in AsyncUncaughtExceptionHandler (by default it just logs). In a method returning CompletableFuture, the error is stored inside the future and someone has to check it.
158
What happens if you don't set timeouts on external HTTP calls, and how do you configure them in RestClient?
A service that isn't responding holds your threads forever: Tomcat runs out of threads, and even though the problem is in one external API, the whole app freezes. Set connect and read timeouts explicitly on every client.
159
When is automatic retry on error dangerous, and how do you do it properly?
If the operation isn't idempotent (a payment, say), a retry can charge the money twice. Retries also add load: if everyone retries at once, a service that's just recovering goes down again. The right way is to retry only on transient errors, with exponential backoff, jitter and an idempotency key.
160
How do you connect to two different databases from one Spring Boot application?
Boot auto-config sets up just one DataSource. For the second one you write the DataSource, EntityManagerFactory and TransactionManager by hand, split the repositories by package, and mark one of them @Primary.
161
What's the difference between @Profile and @ConditionalOnProperty, and which is better for turning a feature on and off?
@Profile ties a bean to an environment name (dev, prod); @ConditionalOnProperty ties it to a specific setting. For toggling a feature, @ConditionalOnProperty is handier: it doesn't depend on the environment, you can see what's enabled, and it's easy to control in tests.
162
How should you write equals() and hashCode() in a JPA entity?
You have to account for new entities that don't have an id yet and for lazy proxies. The reliable option: compare by id (if id is null — not equal) and use a constant hashCode (for example, the class hash). Comparing all fields or using Lombok @Data gets you bugs.
163
Which mechanism do you pick to run something once after the application has started?
ApplicationRunner/CommandLineRunner or @EventListener(ApplicationReadyEvent.class). They're called after the context is fully up, with transactions and proxies already in place. @PostConstruct is too early for this kind of work.
164
How do you get the current user in the service layer, and what are the traps here?
Either via SecurityContextHolder.getContext().getAuthentication(), or you grab it in the controller with @AuthenticationPrincipal and pass it to the service as a parameter. The trap is that SecurityContext lives in a ThreadLocal by default: it doesn't carry over to @Async, CompletableFuture or new threads.
165
How are transaction isolation levels set in Spring, and what's the default?
You set them with @Transactional(isolation = ...); the default is Isolation.DEFAULT, meaning the database's own default: READ COMMITTED in PostgreSQL and Oracle, REPEATABLE READ in MySQL InnoDB. The higher the level, the fewer anomalies, but the more locks and retries.
166
How do you build audit logging with an aspect, marking methods with your own @Audited annotation?
You write the annotation with RUNTIME retention, bind it as an advice parameter in the aspect with the @annotation(audited) pointcut, and record the arguments, result or exception. The proxy limitations (self-invocation, non-public methods) apply here too.
167
Why is Set recommended over List in a @ManyToMany relationship, and what do you do if the join table needs an extra column?
When you remove one element from a List (bag), Hibernate deletes all the rows in the join table and rewrites the rest; with a Set a single DELETE goes out. If the join table needs a column like a date or a grade, instead of @ManyToMany you make a separate entity with two @ManyToOne.
168
Why does this code produce the error "Transaction silently rolled back because it has been marked as rollback-only"?
When the inner @Transactional method throws an exception, it is the same transaction as the outer one (REQUIRED), so the whole transaction is marked rollback-only. If the outer method swallows the exception and finishes normally, the commit attempt throws UnexpectedRollbackException.
169
How does Propagation.NESTED work, and how does it differ from REQUIRES_NEW?
NESTED doesn't open a new transaction: it sets a savepoint inside the open transaction, and if the inner part fails, only that part is rolled back to the savepoint. REQUIRES_NEW suspends the outer one and opens an independent transaction on a separate connection.
170
Why does a service that uses REQUIRES_NEW heavily hang under load?
Each REQUIRES_NEW asks the pool for a second connection while holding the outer transaction's connection. If as many threads as the pool size are in outer transactions at the same time, they all wait for a second connection and nobody releases one, which is a deadlock at the pool level.
171
How do you use CompletableFuture and a Spring executor to call three services in parallel and combine the results?
You start each call in your own executor with CompletableFuture.supplyAsync, put a limit on each with orTimeout or completeOnTimeout, and combine them with allOf. If you don't pass an executor, the commonPool is used, which is bad for blocking I/O.
172
When is @ElementCollection convenient, and what hidden cost does it have on large collections?
@ElementCollection stores a list of plain values or an @Embeddable that has no id of its own in a separate table, which is convenient for small collections like phones or tags. But because the elements have no id, on a change Hibernate often deletes the whole collection and writes it again.
173
What is the difference between flush and commit in Hibernate, and when does a flush happen automatically?
Flush sends the changes in the persistence context to the database as SQL, but the transaction is still open, so you can still roll back. Commit finishes the transaction. With FlushMode.AUTO, a flush happens before commit and before a query that touches the changed tables.
174
What happens if you fetch a collection with JOIN FETCH and paginate with Pageable?
Hibernate can't put a LIMIT in the SQL because the JOIN multiplies the rows; it pulls the whole result from the database, paginates in memory, and logs the HHH90003004 warning. On a big table this leads to slowness and OutOfMemoryError.
175
What does Hibernate's @DynamicUpdate annotation do, and when is it useful and when harmful?
By default Hibernate writes all of an entity's columns in an UPDATE, and it prepares that SQL at startup. With @DynamicUpdate only the changed columns are written. That's useful on wide tables, but the SQL is rebuilt every time and the statement cache works worse.
176
When several aspects (transaction, cache, your own logging aspect) apply to one method, how is their order determined?
Each advisor has an Ordered value: a smaller value means an outer layer, which runs first on the way in and last on the way out. You put @Order on your own aspect, and configure Spring's with @EnableTransactionManagement(order = ...) and @EnableCaching(order = ...).
177
One endpoint has to accept a card or a cash payment with different fields. How do you accept polymorphic JSON with Jackson, and what is the risk?
On the common interface you list the allowed types with @JsonTypeInfo(use = Id.NAME, property = "type") and @JsonSubTypes; Jackson creates the right class based on the type field. Never allow creating arbitrary types by the class name in the JSON, which is a source of well-known RCE vulnerabilities.
178
What is the difference between Spring AOP and full AspectJ (compile-time or load-time weaving), and when do you need AspectJ?
Spring AOP / AspectJ weaving — Mechanism: JDK dynamic proxy / CGLIB / advice is woven into the bytecode; Join point: method calls only / method, constructor, field get/set, static init; Self-invocation: doesn't work / works; Object created with new: doesn't work / works; Setup: nothing needed / the ajc compiler or…
179
In Spring Security 6, how do you configure two different sets of security rules, one for the API and one for web pages?
You create a separate SecurityFilterChain bean for each, mark which paths it applies to with securityMatcher, and set the order with @Order. A request goes through the first matching chain, and the others don't run.
180
What changed in the configuration when moving from Spring Security 5 to 6?
WebSecurityConfigurerAdapter was removed, so you now write SecurityFilterChain beans; authorizeHttpRequests instead of authorizeRequests, requestMatchers instead of antMatchers; @EnableMethodSecurity instead of @EnableGlobalMethodSecurity; jakarta instead of javax.
181
How are AuthenticationManager, ProviderManager and AuthenticationProvider related in Spring Security?
AuthenticationManager is an interface with a single method (authenticate). Its main implementation, ProviderManager, asks several AuthenticationProviders in turn; the first provider that recognizes the token type does the check. Adding a login method means adding a new provider.
182
When you use a native @Query with Pageable, how is the total count query produced, and when do you write the countQuery yourself?
Spring Data tries to derive the count query from the native query itself, but with JOIN, GROUP BY, DISTINCT or a CTE it comes out wrong or slow. In those cases you write countQuery explicitly, and if you don't need the total count, you return a Slice.
183
How do you write a HandlerMethodArgumentResolver to automatically supply the current tenant or user to a controller parameter?
You implement HandlerMethodArgumentResolver: supportsParameter says which parameter it handles, and resolveArgument builds the value from the request. Then you register it through WebMvcConfigurer.addArgumentResolvers.
184
How does content negotiation work in Spring MVC, and when do the 406 and 415 errors occur?
Spring reads the request body with a suitable HttpMessageConverter based on Content-Type; if no converter fits, 415. It writes the response based on the Accept header and the method's produces value; if no agreed type is found, 406.
185
Why does an advice with @ExceptionHandler(Exception.class) turn validation and 404 errors into 500s too, and how does ResponseEntityExceptionHandler help?
Spring MVC's internal errors (MethodArgumentNotValidException, HttpRequestMethodNotSupportedException, NoResourceFoundException) are also Exceptions; a general handler catches them and returns 500 instead of the right 4xx. If you extend ResponseEntityExceptionHandler, these errors come back with the standard status and a ProblemDetail.
186
When do you use DeferredResult, Callable and SseEmitter in Spring MVC for long-running requests?
They work in servlet async mode: after the controller method returns, the Tomcat thread is freed and the response is written later from another thread. Callable hands the work to a Spring executor, DeferredResult has its result filled in by an external event, and SseEmitter streams several events one after another.
187
How do you make @ConfigurationProperties immutable, and how do you make the application stop at startup on a bad setting?
You write the class as a record (or a class with a constructor); in Boot 3 constructor binding is automatic. You add @Validated and put constraints like @NotBlank and @Min on the fields; if a value is wrong, the context doesn't start.
188
In Kubernetes, how do you provide spring.datasource.url or a list-style setting through an environment variable?
Spring Boot does relaxed binding: dots become _, dashes are removed, everything is uppercase: SPRING_DATASOURCE_URL. A list element is given with an index: APP_ALLOWEDORIGINS_0_. Be careful with map keys, because an env var turns the key uppercase.
189
How do you write and register your own auto-configuration in Spring Boot 3?
You write an @AutoConfiguration class, put conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty on the beans, and list the class name in the META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports file. The old spring.factories way doesn't work for auto-configuration in Boot 3.
190
What is wrong with this @Async executor configuration, and how does it behave under load?
ThreadPoolTaskExecutor doesn't create new threads until the queue is full. Because the queue is unbounded, the pool never grows to 50 threads: it always runs 5 threads, while tasks pile up in the queue and fill memory.
191
The application runs as three instances and the @Scheduled job runs three times. How do you fix it?
@Scheduled runs independently in each JVM, and the instances don't know about each other. You need a distributed lock: ShedLock (a lock table in the database or Redis), a Quartz cluster, or running the job in one dedicated place (a Kubernetes CronJob).
192
A service method has no @Transactional and calls two repository methods. How does that work, and what is the risk?
Each repository call runs in its own transaction, through the @Transactional on SimpleJpaRepository. If the first one commits and the second fails, the data is left half-done; in addition, the returned entities are detached.
193
Why is a derived delete method like deleteByStatus so slow?
A derived delete first SELECTs all the matching entities into memory, then calls em.remove() for each: N DELETE queries plus cascades. For many rows you should write a single bulk DELETE with @Modifying @Query("delete ...").
194
You wrote a filter to log the request body, and now the controller gets an empty body. Why, and how do you do it properly?
The request body is an InputStream that can only be read once; after the filter reads it, nothing is left for the controller. ContentCachingRequestWrapper copies the body as the controller reads it, and you log it after the request completes.
195
What do you write in Spring MVC to automatically convert a request parameter or path variable into your own type (for example OrderId)?
You write a Converter<String, T> or a Formatter<T> and register it through WebMvcConfigurer.addFormatters (in Boot, just being a bean is enough). Then the controller parameter is directly an OrderId, and a bad value returns 400.
196
What serialization problems do you run into when storing @Cacheable results in Redis?
The default JDK serializer requires the class to be Serializable, writes binary, and can't read the data back when the class changes. A JSON serializer gives a readable format, but you have to think about type information, generics, and compatibility between old and new versions during a deploy.
197
When does a Resilience4j circuit breaker kick in, and how do you configure it in Spring Boot?
Three states: CLOSED, requests pass and failures are counted; if the failure rate exceeds the threshold it goes OPEN, and requests are rejected immediately; after the wait time it goes HALF_OPEN, a few trial requests are let through, and depending on the result it closes or opens again.
198
How do you choose among the SINGLE_TABLE, JOINED and TABLE_PER_CLASS strategies for entity inheritance in JPA?
SINGLE_TABLE stores everything in one table with a discriminator column: the fastest, but with many nullable columns. JOINED gives a separate table per subclass and uses JOINs: a clean schema, slower queries. TABLE_PER_CLASS produces a UNION in polymorphic queries and is rarely used.
199
How does a @LoadBalanced RestClient or WebClient work, and how does it differ from a Kubernetes Service?
@LoadBalanced adds an interceptor to the builder: the host in the URL (http://inventory) is treated as a service name, and Spring Cloud LoadBalancer gets the list of instances from discovery (Eureka, Consul or the Kubernetes API) and picks one. With a Kubernetes Service, the cluster network (kube-proxy) makes the choice.
200
Requests are hanging, but CPU is low. How do you find the cause with a thread dump?
With jcmd <pid> Thread.print or /actuator/threaddump you take 2-3 dumps a few seconds apart and compare where the http-nio-*-exec-* threads are stuck. If many threads are WAITING or TIMED_WAITING in the same place, that resource is the bottleneck.
201
If a synchronous @EventListener throws an exception, what happens to the code that published the event and to its transaction?
A plain @EventListener runs synchronously on the publishing thread, inside that transaction. The exception the listener throws comes out of the publishEvent() call and rolls back the outer transaction: even if the listener is "extra" work, the main operation is cancelled.
202
Why does the requestId written to MDC in this filter also show up in other users' logs?
Tomcat threads are reused from a pool, and MDC is a ThreadLocal. There's no MDC.remove in a finally, so when an exception happens the value stays on the thread; if the next request comes without the header, logs are written with the old requestId.
203
How do you return a 1 GB file or a large CSV report through a controller without filling up memory?
You stream the response instead of assembling it as a byte[]: a Resource (FileSystemResource) for a ready-made file, and StreamingResponseBody for generated data. And you read the data from the database in pages or as a Stream, and write it to the output right away.
204
What problems does @ManyToOne being EAGER by default cause?
In the JPA spec @ManyToOne and @OneToOne are EAGER by default: when an entity is loaded, the related object is fetched by force too. In JPQL queries this gives an extra SELECT per row (N+1), and you can't turn it off at the query level afterward.
205
What mistakes do you run into when working with cascade and orphanRemoval on @OneToMany?
The most common: putting CascadeType.ALL on the @ManyToOne side and deleting a shared object; replacing the collection with setItems(newList) and hitting an orphanRemoval error; filling in only one side of the relationship and leaving the foreign key null.
206
A user should be logged in from only one device at a time. How do you limit the number of sessions in Spring Security?
Inside sessionManagement you set maximumSessions(1) and register an HttpSessionEventPublisher bean, and Spring Security tracks each user's sessions in a SessionRegistry. With several instances the registry has to be shared too, which means Spring Session (Redis or JDBC).
207
What do you consider when choosing between a Long sequence and a UUID as a table's primary key, and how does a random UUID affect the index?
A Long sequence is compact and lands at the end of the B-tree index. A random UUID (v4) lets you generate the id without going to the database and can't be guessed, but it lands all over the index: inserts get slower on a big table and the cache works badly. A time-based UUID v7 largely removes that problem.
208
How do you map a PostgreSQL jsonb column in a Hibernate 6 entity, and what are the pitfalls?
Hibernate 6 needs no external library: you put @JdbcTypeCode(SqlTypes.JSON) on the field, it is written to jsonb, and Jackson does the JSON conversion. Watch out for the cost of dirty checking, queries on fields inside the JSON, and the lack of a schema.
209
Why doesn't an exception thrown inside a Filter reach @RestControllerAdvice, and how do you turn it into a clean response?
@ControllerAdvice runs inside the DispatcherServlet, while a Servlet Filter runs before it. An error in a filter goes straight out to the container, and Boot's /error page answers.
210
When is Hibernate's StatelessSession useful for bulk import or processing, and how does it differ from a regular Session?
StatelessSession works without a persistence context: no first-level cache, no dirty checking, no cascades, no lazy loading, and every insert/update becomes SQL immediately. Memory doesn't grow on a million-row import and it is faster, but you give up the JPA conveniences.
211
A Spring Boot application takes 90 seconds to start. How do you find the cause and speed it up?
I don't guess, I measure: the startup actuator (BufferingApplicationStartup) or log timestamps show which bean and which step is slow. The usual culprits are network calls at startup, a heavy @PostConstruct, unneeded auto-configurations, a large classpath scan, or Hibernate/Flyway.
212
A Spring application's heap slowly fills up over a few days and ends in OutOfMemoryError. How do you analyze it?
I take a heap dump (or let it be written automatically on OOM) and use Eclipse MAT's "dominator tree" and "leak suspects" to see who holds the memory and who references it. In Spring applications it's usually an unbounded cache, a ThreadLocal, a static collection, a huge persistence context or a queue that never drains.
213
Under high traffic, how do you coordinate the number of Tomcat threads, HikariCP connections and database connections?
I treat it as one chain. Incoming concurrency (Tomcat or virtual threads) can be much larger than the part that touches the database, but the pool limits the queries going to the database, and the real capacity of the database limits the pool. I do the math on the sum across all instances.
214
You need to send an event to Kafka after an order is saved. How do you guarantee in Spring that both happen?
There is no shared transaction between the database and Kafka, so if you do "save, then send", sooner or later one of them gets lost. The solution is a transactional outbox: the event is written to an outbox table in the same DB transaction, and a separate process sends it to Kafka and marks it. Consumers must tolerate duplicates.
215
How do you make an endpoint like "create a payment" idempotent?
The client sends a unique Idempotency-Key with each operation. The server runs the first request and stores the result under that key; if the same key comes again, it returns the stored response without redoing anything. Writing the key and doing the operation happen in one transaction, with a unique constraint.
216
In an application where each customer (tenant) has its own database, how do you pick the DataSource in Spring?
With AbstractRoutingDataSource: each time a connection is requested, it reads the current tenant key from a ThreadLocal and returns the matching DataSource. The key point is to set the tenant context at the start of the request, before the transaction, and clear it at the end.
217
Where and how should you do rate limiting in a Spring application?
If possible at the edge: in an API gateway or reverse proxy, before the request reaches the application. Limits that depend on business rules (a user's plan, sending SMS) live inside the application, with a shared counter (Redis) when there are many instances.
218
How does a microservice check tokens as an OAuth2 resource server, and what decisions do you make along the way?
The service verifies the JWT signature itself with the authorization server's public keys (JWKS), checks the iss, exp and aud claims, and turns scopes/roles into authorities. The decisions: JWT or opaque token, token lifetime, audience, and how to revoke.
219
When you use a cache, how do you deal with inconsistency with the database data and with cache stampedes?
For each cache I decide how stale the data is allowed to get and pick the strategy accordingly: TTL, evict after commit, versioned keys. Against a stampede: a single loader (request coalescing), refreshing in the background before expiry, and adding a random part to the TTL.
220
When is moving from Spring MVC to WebFlux worth it, and when not?
WebFlux pays off when you have many long-lived connections (streaming, SSE, a gateway, lots of parallel external calls) and the whole stack is reactive (R2DBC, reactive drivers). In an ordinary CRUD service, especially with JDBC/JPA and Java 21 virtual threads, the complexity outweighs the benefit.
221
How do you set up routing read queries to a replica database and writes to the primary in Spring, and what is risky about it?
A routing DataSource picks the replica or the primary based on the transaction's readOnly flag. A LazyConnectionDataSourceProxy goes on top so the connection is acquired after the transaction starts. The main risk is replication lag: a user may not see what they just wrote.
222
A single transaction is doing 10 minutes of work. What problems does that cause, and how would you redesign it?
A long transaction holds a connection, holds locks, prevents cleanup of old versions in MVCC (vacuum), and if it fails everything starts over from the beginning. I split it into small, idempotent chunks and turn it into a process that can resume where it stopped.
223
How do you manage configuration and secrets (passwords, API keys) in a Spring application?
Secrets are neither in the code nor in git. They come from the environment: a Kubernetes Secret, Vault or a cloud secret manager, short-lived and self-rotating if possible. Ordinary configuration is versioned and split per environment.
224
How do you version a REST API in Spring MVC, and which approach do you choose?
Example / Pro / Con — URL: /api/v2/orders / explicit, easy to cache and log / the URL is no longer just the "resource", it carries the version too; Header: X-API-Version: 2 / clean URL / awkward to try in a browser; Media type: Accept: application/vnd.shop.v2+json / fits HTTP / complex, poorly understood
225
In a distributed system, how do you follow a single request across all services' logs (trace id)?
In Boot 3, Micrometer Tracing gives every incoming request a trace and span id, or continues an incoming traceparent header, puts them into MDC and propagates them to outgoing HTTP/Kafka calls. If you add the trace id to the log pattern, one id shows you the whole path.
226
In a doctor appointment booking system, what do you do so two patients can't book the same time at once?
I give the main guarantee to the database: a unique constraint on the slot, or in PostgreSQL an exclusion constraint for time ranges. An application-level "check first, then write" loses under concurrent requests anyway, and locks are only a helper.
227
External partners call your API with an API key. How do you build this in Spring Security, and how do you store the keys?
You write a filter that takes the key from a header, validates it, and puts the partner into the SecurityContext as an Authentication. The database stores the hash of the key, not the key itself; each key is tied to an owner, permissions, an expiry and a rate limit.
228
When does enabling Hibernate's second-level cache pay off, and when does it do harm?
It helps for entities that rarely change, are read a lot and are fetched by id (reference data). For data that is written often, that several instances can't keep in sync, or that is changed through native SQL, it gives you stale data and extra complexity.
229
You need to export a table with a million rows to CSV. What do you do in Spring Data JPA instead of findAll()?
findAll() loads every row into the heap at once. You need Stream<T> or keyset-based batch reads, a fetch size, a readOnly transaction and detaching/clearing entities; a DTO projection or JdbcClient is often the most economical.
230
Every change to entities like contracts and tariffs has to be stored as "who, when, what it was, what it became". How do you choose between Envers, triggers and CDC?
Hibernate Envers writes a copy of the entity and a revision to an _aud table on every change, which is the fastest route for data that changes through JPA. If the database is also changed in other ways, triggers or CDC (Debezium) are more reliable; if the business meaning matters, you write explicit audit events.
231
What security problem does this endpoint have, and how do you fix it in Spring?
This is an IDOR: any authenticated user can swap the id and see someone else's order. The ownership check has to be in the query itself (where user_id = ?) or in @PostAuthorize/the service layer.
232
The database is temporarily down while the service is starting. Should the app crash or wait, and how do you handle this in Spring Boot?
By default Flyway, Hibernate and Hikari connect to the database at startup, and if they can't, the app fails to start. On Kubernetes that is usually right: the pod is restarted with backoff. For outages while running, though, the app must survive without dying: short timeouts and correct probes.
233
You need a declarative HTTP client for another service. How do you compare OpenFeign and Spring 6's @HttpExchange interfaces?
Both give you an HTTP client through an interface. @HttpExchange is part of Spring Framework itself, runs on top of RestClient/WebClient and needs no extra dependency; OpenFeign is tied to Spring Cloud and is now in maintenance mode only.
234
An endpoint responds in 2 seconds. How do you find out whether the time goes in Spring, in Hibernate or in the database?
First I split the time into layers with tracing or metrics: the HTTP request, each SQL statement, external calls. Then I check separately the number of queries (N+1), the plan of the slow SQL (EXPLAIN ANALYZE) and the JVM side (GC, pool wait). I don't optimize on guesses.
235
The application's memory grows slowly, and in the heap dump Hibernate's query plan cache takes a lot of space. How do IN (:ids) queries cause this?
Every different length of the IN list is a separate SQL string for Hibernate and a separate entry in the cache: ids from 1 to 1000 mean 1000 different queries. hibernate.query.in_clause_parameter_padding=true rounds lengths up to powers of 2 and cuts the variants sharply; very long lists need a different approach.
236
In production you occasionally get "Deadlock found when trying to get lock" (or "deadlock detected" in PostgreSQL). How do you analyze and fix it?
Two transactions lock the same rows in different orders. Find the queries in the database's deadlock log, make the lock order consistent, shorten the transaction and add a retry that is safe for deadlocks.
237
The traceId and userId in the log disappear inside @Async methods and CompletableFuture. Why, and how do you fix it?
MDC and SecurityContext are stored in a ThreadLocal, and a new thread doesn't inherit them. You add a TaskDecorator to the executor and copy the context yourself, or wire in Micrometer context-propagation.
238
With JWT, if a user logs out or gets blocked, how do you revoke their token before it expires?
A JWT can't be revoked by itself. You keep the access token lifetime short (5–15 minutes), store refresh tokens on the server and revoke them, and if needed add a denylist by jti/version or introspection.
239
How do you do soft delete (deleted = true) in Spring Data JPA, and what are its hidden costs?
In Hibernate 6.4+ you use @SoftDelete, in older versions @SQLDelete + @SQLRestriction. After that you deal separately with unique constraints, indexes, related tables, native queries and ever-growing volume.
240
How do you package a Spring Boot application into a container: Dockerfile, layered jar, buildpacks and JVM memory settings?
The main decisions are: build a cache-friendly image with a layered jar or buildpacks, a small JRE-based base image, a non-root user, and a MaxRAMPercentage that matches the container limit. Setting -Xmx equal to the limit leads to an OOMKill.
241
How do you split a large Spring Boot monolith into modules without breaking it into microservices?
I build a modular monolith: the code is split into modules by business area, each module has a public API and a private internals part, and modules talk to each other through an explicit interface or events. I enforce the boundaries with Spring Modulith or ArchUnit tests.
242
How do you plan splitting services out of a monolith, and which part do you start with?
With the strangler fig approach: I put a routing layer in front of the monolith and move functions one by one into a new service, gradually deleting the old code. I take first the part with a clear boundary that changes independently and exchanges little data with the rest. But before that there has to be an answer to "why are we splitting?".
243
Should you build a shared internal starter (a platform library) for all Spring services in the company? How do you weigh the benefits and risks?
Yes, if it standardizes the cross-cutting concerns (log format, tracing, security, error format, HTTP client defaults) and services can override it. The risk is a "god library" that couples everyone together, forced upgrades, and one bug spreading to every service. With small, versioned, optional modules, the benefit is large.
244
How do you plan migrating 40 services from Spring Boot 2.7 to 3.x?
First I remove the blockers (Java 17, javax → jakarta, third-party libraries), then migrate the platform and shared libraries, then move the services in waves ordered by risk and dependencies, using OpenRewrite. The period of running two versions in parallel should be short.
245
How do you standardize a single security policy across 50 services, and how do you verify it is followed?
I don't leave security to each team; I put "secure by default" into the platform: authentication and token verification in the shared starter, mTLS and policies on the network, automatic checks in CI (vulnerable libraries, secrets, configuration rules). Exceptions are visible and reviewed.
246
You need to rename a column in a big production table. How do you do it without stopping the service?
With expand/contract (parallel change): first I add the new column and the application writes to both, the data is copied in chunks, reads move to the new column, and only after every instance runs the new version is the old column dropped. Each step is a separate deploy and can be rolled back.
247
How do you configure liveness, readiness and startup probes for a Spring Boot service in Kubernetes?
Liveness only answers "has the process entered an unrecoverable state?" and doesn't check external dependencies. Readiness asks "can I take traffic right now?". The startup probe is for slow starts. I use Actuator's /actuator/health/liveness and /readiness groups and choose carefully which indicator goes into which group.
248
You're asked for "exactly-once" processing with Spring and Kafka. How do you explain it, and how do you approach it in practice?
Kafka's exactly-once guarantee only works inside Kafka: reading, processing and writing back to Kafka in one transaction. If the result goes to an external database or API, "exactly-once" is really at-least-once delivery plus idempotent processing. In practice that's what I design for.
249
How do you design a saga for an order process that spans several services: orchestration or choreography?
In a saga each service runs its own local transaction, and if a step fails, the earlier ones are undone with compensating actions. For many steps and a complex process, orchestration (one coordinator); for simple, short flows, choreography (events). State, timeouts and compensation have to be designed from the start.
250
Several teams are working in one large Spring codebase. How do you keep architectural boundaries from being broken?
I keep the rules in automated tests, not in a document: ArchUnit or Spring Modulith checks package and module dependencies in CI. On top of that I add code ownership (CODEOWNERS), a clear contract for module APIs, and an open "exception" process for breaking a boundary.
251
In a chain of services (A → B → C → D), if one slows down, what layers of protection do you build so the whole system doesn't stall?
A timeout on every call and a total deadline budget, bounded retries, a circuit breaker, bulkheads (isolating resources), fallbacks and load shedding. The strongest protection is shortening the synchronous chain or making it asynchronous.
252
When does shipping a Spring Boot application as a GraalVM native image pay off?
When very fast startup and low memory matter: serverless, many small services, CLI tools, fast autoscaling. For long-running, high-load services, a JVM with JIT often gives higher peak performance, while a native image adds build complexity and compatibility limits.
253
How do you choose between CDS, AOT and CRaC to reduce Spring Boot startup time and memory on the JVM?
CDS (Class Data Sharing) is the easiest and safest: startup gets noticeably shorter and you don't have to change any code. Spring AOT gives a bit more speed on the JVM, but limits the flexibility of profiles and conditions. CRaC gives the fastest startup, but requires handling connections and secrets across snapshot and restore, and the platform has to support it.
254
In a Spring system running across several regions, what architectural decisions do you make about data consistency?
First I separate which data needs strict consistency (balances, stock) and which is fine with eventual consistency (catalog, profile). Writes go to a "home region" or a single leader, reads come from local replicas, and there's an explicit rule for resolving conflicts. Every decision is a tradeoff between latency, availability and cost.
255
Pagination on a very large table is slow. How do you compare offset and keyset (seek) pagination, and how do you design the API?
Offset gets slow on deep pages because the database still reads all the skipped rows, and when data changes, rows get duplicated or dropped. Keyset fetches what comes after the last seen key using an index, so each page is fast and stable, but you can't jump to an arbitrary page. In the API I return a cursor (an opaque token).
256
How do you build a test strategy for a multi-service system, and how do you verify the contract between services?
By the pyramid: lots of fast unit tests, integration tests inside each service with real dependencies (Testcontainers), and between services contract tests (Pact or Spring Cloud Contract) instead of full e2e. E2E only for a few critical business flows.
257
How do you organize releases with feature flags, and what are the risks?
I separate deploy from release: the code ships to production with the flag off, then it's turned on step by step for groups of users, and if there's a problem it's turned off without a redeploy. The risks are flags piling up, combinations exploding, test coverage, and the flag system itself failing.
258
When audit log requirements and user data deletion requirements (for example the "right to be forgotten") conflict, how do you design the system?
I separate personal data (PII) from business records: audit and financial records link to the user through a pseudonym id, while PII lives separately and can be deleted. If needed, a separate encryption key per user: delete the key and the data becomes unreadable in every copy (crypto-shredding). Legal retention periods are defined separately.
259
How do you introduce observability standards (SLOs, alerting) for a whole platform?
For each service I define the SLIs users actually see (the share of successful requests, latency percentiles) and the SLO targets. I put alerts on symptoms, not causes: on how fast the error budget is burning. I make the naming and tags of metrics, logs and traces mandatory through the platform starter.
260
For processing a large volume of data, how do you choose between Spring Batch, a plain @Scheduled job and stream processing?
For a small, fast job where restart isn't required, @Scheduled + a lock. For a large bulk job that can be split into chunks, must resume where it stopped and must report, Spring Batch. When data arrives continuously and you need results fast, stream processing (Kafka Streams, Flink).
261
When should you introduce CQRS in a read-heavy system, and what complexity does it add to a Spring system?
When the requirements for the read and write models differ sharply: reads are many and complex (search, aggregates, different views), while writes have strict business rules. CQRS keeps the write model clean and gives reads separate, optimized models. The price is eventual consistency, synchronization infrastructure and maintaining two models.
262
When do you need an API gateway and a BFF (Backend for Frontend), and what do you use Spring Cloud Gateway for?
A gateway is the common entry point for all external traffic: routing, TLS, authentication, rate limiting, observability. A BFF is an aggregation layer tailored to one specific client (web, mobile). Business logic shouldn't go into the gateway, otherwise it becomes a narrow bottleneck that ties every team together.
263
How do you safely modernize an old Spring project on Java 8 with XML configuration?
I don't do a big rewrite, I go step by step: first lock in the current behavior with tests, then upgrade the build and the Java version, gradually replace XML with Java configuration, move to Spring Boot, and release each step separately. I run the work in parallel with new features and show the business the benefit.
264
A service's SLO is being violated, but the cause isn't clear. How do you run the incident and carry out the technical investigation?
My first job is to reduce the impact (rollback, shift traffic, switch off a feature), and I find the cause afterward. I separate the roles (incident commander, technical investigation, communication) and write facts into a timeline. I start the investigation with "what changed?" and narrow the signals layer by layer. At the end, a blameless postmortem.
265
In a SaaS system, how do you compare the tenant data isolation models: separate database, separate schema and shared schema?
Database per tenant / Schema per tenant / Shared schema — Isolation: highest / high / depends on app/RLS; Number of tenants: tens to hundreds / hundreds / thousands+; Cost: high / medium / low; Migration: per database / per schema / one; "Noisy neighbor": no / yes (one server) / yes; Restoring one tenant: easy /…
266
How do you rotate a database password without stopping services (secret rotation)?
With two active accounts or two passwords: a new account/password is created, applications move to the new one gradually (restarting or re-reading dynamically), and once all connections have moved the old one is removed. The best option is Vault dynamic secrets: short-lived logins and automatic rotation.
267
In a multi-service system, how do you manage library versions, their conflicts and security vulnerabilities (CVEs)?
I manage versions centrally through a BOM, turn updates into a steady stream with automatic PRs (Renovate/Dependabot), and a vulnerability scanner in CI blocks critical CVEs. With an SBOM I can quickly find which service has which library. The goal is constant small upgrades instead of a "big upgrade".
268
Design an order service in Spring Boot that handles 10,000 requests per second. What are the main architectural decisions?
First I pin down the requirements: the read/write ratio, peak load, consistency and latency. Then: a stateless horizontally scaled service, a short idempotent write path, heavy work asynchronous through outbox + Kafka, partitioning and caching in the database, and backpressure. I confirm every decision with a load test.
269
When you review Spring code, which mistakes do you look for first?
The things that silently fail to work: @Transactional/@Async/@Cacheable with the proxy bypassed, wrong transaction boundaries (an external call inside), N+1 and unbounded queries, state in a singleton, external calls without timeouts, security (IDOR, open endpoints, secrets in logs), and missing idempotency where there's a retry.
270
Your team says "we'll do everything with Spring Cloud" (Config Server, Eureka, Gateway). How do you evaluate that decision in a Kubernetes environment?
In Kubernetes / Spring Cloud / Usual choice — Service discovery: DNS + Service / Eureka / Kubernetes; Configuration: ConfigMap, Secret / Config Server / Kubernetes (+ Vault); Load balancing: Service / mesh / LoadBalancer / Kubernetes; API gateway: Ingress, Gateway API / Spring Cloud Gateway / SCG if you need complex…
271
What do you do with messages that fail in a Spring Kafka consumer: how do you pick between retry, retry topics, a DLT and message ordering?
Blocking retry stops the partition but keeps ordering; non-blocking retry topics don't stop the consumer but break ordering. Which one you take depends on how much ordering matters for the business. At the end you always need a DLT and someone watching it.
272
Should you strip the domain model completely of Spring and JPA annotations (hexagonal/clean architecture)? How do you decide?
For a complex, long-lived domain with a lot of business logic the separation pays off; in plain CRUD services it just multiplies mapping and layers with little benefit. I decide based on domain complexity, team size and how fast things change.
273
You need to choose the data layer for a new service: Spring Data JPA, jOOQ or JdbcClient. What criteria do you decide by?
JPA is productive with a rich domain model and lots of CRUD; jOOQ is for complex, type-checked SQL and reports; JdbcClient is simple, transparent and has the least abstraction. Often two of them work together in one service.
274
A service runs in 6 pods and a Flyway migration runs at startup. In a multi-instance deploy, who should run the migrations and when?
If pods migrate at startup, Flyway uses a lock so one of them runs it, but a long migration blocks startup and the probes kill the pod. It is more reliable to run the migration as a separate job (init/pre-deploy) and to make every migration compatible with both the old and the new code (expand/contract).
275
Why do people often avoid XA (JTA) transactions for writing to several databases at once, and what is done instead?
XA gives atomicity with a two-phase commit, but it is slow, holds resources locked for a long time, leaves "in-doubt" transactions when the coordinator crashes, and systems like Kafka don't support it. Instead you use an outbox, idempotent consumers and compensation.
276
The company needs to pick an identity provider: do we build on Spring Authorization Server ourselves, install Keycloak, or take a cloud service?
A cloud IdP gives the least operational load, Keycloak gives ready-made features and control on your own servers, and Spring Authorization Server gives maximum flexibility but the most work. The choice depends on requirements, data residency and team capacity.
277
A big promotion is a month away and traffic is expected to be 10 times the usual. How do you prepare a system made of Spring services?
First I run a load test with a realistic scenario to find the bottlenecks and separate the critical path. Then I tune autoscaling and pools, warm the cache in advance, and put together a plan to switch off secondary features with load shedding and feature flags. A runbook is ready for the day of the promotion.
278
How should internal services authenticate each other: mTLS, OAuth2 client credentials, or passing the user's token along?
Each one answers a different question: mTLS says "which service is connecting" (transport), client credentials says "the service's own permissions", and token propagation or token exchange says "on whose behalf". They are usually used together.
279
How do you decide between synchronous REST and asynchronous messaging (Kafka/RabbitMQ) for communication between services?
If the answer is needed immediately and the caller can't continue without the result, go synchronous; if the work can happen later, there are several consumers, or the services must run independently, go asynchronous. Each has different failure modes.
280
Someone proposes moving from REST to gRPC between internal services. How do you evaluate this decision in the Spring ecosystem?
gRPC gives a strict contract, small binary messages, HTTP/2 streaming and code generation; but it doesn't work with browsers directly, debugging and tooling are harder, and you have to configure load balancing and gateways separately.
281
How do you change the format of events in Kafka without breaking dozens of consumers (schema evolution)?
Events get a schema (Avro/Protobuf/JSON Schema) and a compatibility mode in the schema registry (usually BACKWARD or FULL). Changes that don't break compatibility are allowed, and those that do become a new event type or a new topic.
282
How do you build a multi-step process that runs for several days (for example a loan application: scoring, operator review, contract, money transfer) in Spring?
The process state lives in the database as an explicit state machine; every step is idempotent, and timers and waits survive a pod restart. As complexity grows, a workflow engine like Temporal or Camunda ends up cheaper than hand-written orchestration.
283
Two services share tables in one database. How do you separate them step by step?
First find out who writes to which table and assign one owner per table; the other service switches from reading directly to getting data through an API or events; then the schema is split, and finally the database is physically separated. Every step has to be reversible.
284
A product catalog needs full-text search. Is PostgreSQL full-text search enough, or do you add Elasticsearch/OpenSearch?
For a few million records, simple relevance and a single language, PostgreSQL FTS and pg_trgm are often enough and remove the sync problem. With facets, complex relevance, multiple languages, typo tolerance and heavy load, you need a separate search system and a reliable indexing pipeline.
285
Business reports run on the main OLTP database and slow down customer requests during the day. What architecture do you propose?
Reports need to be separated from the operational database: in the short term indexes and materialized views, in the medium term a separate replica, and in the long term I move the data with CDC into an analytical database (ClickHouse, BigQuery and the like) and build the reports there.
286
Where do you store files that users upload (images, PDFs, video), and how should Spring services work with them?
Files live neither in the database nor on the pod's disk but in object storage (S3, MinIO), with only the metadata in the database. The client uploads directly to storage with a presigned URL and downloads from it, and validation and processing happen afterward, asynchronously.
287
In a system where several services send email, SMS and push notifications, how do you design the notification service?
One central notification service takes in events, applies templates and user preferences, and sends per channel through queues. The most important parts: idempotency, the ability to swap providers, rate limits, retry, and tracking that a message was delivered.
288
You sent a request to a payment provider and got a timeout. Whether the money was charged is unknown. How do you design the system for such cases?
A timeout is not "failed", it is "unknown". You need to send the payment with your own idempotency key, store an UNKNOWN state, ask the provider for the status or wait for a callback, and close the differences with a daily reconciliation.
289
You need to send millions of reminders to users at a set time (for example, "your lesson starts in 1 hour"). How do you build this?
Each reminder is stored in the database with a due_at, picked up in batches by indexed time and split between workers with SKIP LOCKED; sending goes through a queue and is idempotent. A separate in-memory timer or cron per reminder is out of the question.
290
How do you design an API for an operation that takes several minutes (a big report, a bulk import)?
I don't hold the request synchronously: the endpoint accepts the work and returns 202 Accepted with the address of a job resource, background workers do the work, and the client polls for status or is notified by webhook/SSE. I design idempotency, cancellation, result storage and quotas up front.
291
In a multi-service system, where should authorization rules (who can do what) live: in the gateway, in each service, or in a central policy engine?
The gateway does only coarse checks (authentication, a general role). Decisions that depend on the resource are made in the service that owns the data. A central policy engine (OPA, Cedar, OpenFGA) pays off when the rules are complex and repeated across many services.
292
In a SaaS system one big customer's heavy requests are slowing the system down for all other customers (noisy neighbor). How do you handle it?
First find out who is taking which resource using per-tenant metrics; then per-tenant rate limits and quotas, separate pools and queues (bulkhead), moving heavy work to the background, and if needed splitting big customers into their own "cell".
293
Local cache (Caffeine), distributed cache (Redis) or a two-level cache: which would you pick for a service, and by what criteria?
A local cache is the fastest and simplest, but it is inconsistent between instances and duplicated in every pod; Redis is shared and more consistent, but adds network latency and a new point of failure. A two-level cache takes the best of both, but invalidation gets more complex.
294
How do you choose a deploy strategy for Spring services: rolling update, blue/green or canary?
A rolling update is simple and cheap, but two versions run at the same time; blue/green gives a fast rollback, but needs double the resources and a compatible schema; canary verifies risk on a small slice of traffic with measurements, but needs good metrics and automated analysis.
295
How do you plan disaster recovery for Spring services and their databases? Who sets RPO and RTO, and how?
RPO (how much data loss we can tolerate) and RTO (how fast we recover) are agreed with the business per service. They determine the backup type, replication, the standby region and the recovery drills. A backup that hasn't been tested is not a backup.
296
For REST APIs between services, how do you choose between contract-first (generating code from OpenAPI) and code-first (generating OpenAPI from code)?
In contract-first the API is agreed first: teams work in parallel and backward compatibility is checked in CI, but you live with generated code and extra build steps. Code-first is fast and developer-friendly, but the contract is easily broken by accidental code changes.
297
A team proposes building the new accounting module with event sourcing. How do you evaluate this decision?
With event sourcing you get full history and audit for free, and you can rebuild the state at any point in time and build new projections. But event schema evolution, rebuilding projections, eventual consistency and the team's experience are a serious cost. It pays off only if the domain truly rests on events.
298
In a multi-service system, what common standards do you set for working with money amounts and time?
Money is BigDecimal or a long in minor units, always together with the currency code and with an explicit rounding rule; time is a UTC Instant (ISO-8601) when stored and transmitted, with the user's time zone applied only for display. These rules must be the same in the API, events and the database.
299
Encrypting personal data (passport number, phone) in the database is now required. How do you build this in a Spring/JPA application, and how do you manage the keys?
If disk encryption isn't enough, I encrypt fields in the application itself (an AttributeConverter or the service layer), with keys in a KMS/Vault using envelope encryption. For search you need a separate blind index, and for key rotation a versioned encrypted value.
300
Log volume and cost have shot up, yet during an incident you still can't find the information you need. How do you rebuild the log strategy for the platform?
I make logs structured (JSON) with common fields, set clear rules for levels, remove noise or sample it, mask sensitive data, and set retention by log type. And for many questions, metrics and traces answer better than logs.
Sign up — studied questions get marked and your progress is saved.