Spring / Spring Webflux Interview questions
- >?
Reactive programming is a programming paradigm that deals with asynchronous data streams and the specific propagation of change, which means it implements modifications to the execution environment in a certain order.
The primary benefits of reactive programming are, better utilization of computing resources on multicore and multi-CPU hardware and better performance by truncating serialization.
Spring WebFlux is part of Spring 5, it is a parallel version of Spring MVC and supports fully non-blocking reactive streams. It supports the backpressure concept and uses Netty as the inbuilt server to run reactive applications.
Yes, WebClient is thread-safe since it is immutable.
RestTemplate allows you to consume Rest resources in a synchronous manner, which means it will block the thread before it receives a response. RestTemplate has been deprecated since Spring 5.
The spring-webflux is not necessarily faster but it is better in dealing with the issues of scalability and efficient use of hardware resources. It is also better at dealing with the issues of latency.
The method bodyToMono() is extracts the body to a Mono instance. The method Mono.block() subscribes to this Mono instance and blocks until the response is received while Mono.subscribe() method is non-blocking.
A Mono
And a Flux
Handle Errors With,
- onErrorReturn (), to return a static default value whenever an error occurs.
- onErrorResume (), to compute a dynamic fallback value, (or) execute an alternative path with a fallback method, (or) Catch, wrap and re-throw an error.
- Global Level by customizing the Global Error Response Attributes and implement the Global Error Handler.
Spring Async I/O model during its communication with the client is blocking while Spring Webflux doesn't block.
Spring WebFlux supports more Web/App servers such as Netty, Undertow.
Processing the request body in Spring Async is blocking while it is non-blocking with Spring Webflux.
Reactor Netty is an asynchronous event-driven network application framework. It provides non-blocking and backpressure-ready TCP, HTTP, and UDP clients and servers. As the name implies, it's based on the Netty framework.
RouterFunction is a functional alternative to the @RequestMapping and @Controller annotation style used in standard Spring MVC.
We can use it to route requests to the handler functions.
1 2 3 4 5 | @Bean public RouterFunction<ServerResponse> listEmployees(EmployeeService es) { return route().GET("/employee", req -> ok().body(es.findAll())) .build(); } |
Mono. defer(monoSupplier) lets you provide the whole expression that supplies the resulting Mono instance. The evaluation of this expression is deferred until somebody subscribes. Inside of this expression you can additionally use control structures like Mono.
When you run Mono.just() it creates immediately an Observable(Mono)and reuses it but when you use defer it doesn't create it immediately it creates a new Observable in every subscribe.
RxJava support project which is based on JDK8- and Project Reactor supports JDK 8+. RxJava has too many problems which can cause Out of Memory if you can't use it well. It is preferred to use Reactor for JDK8+ projects.
Different ways to handle exceptions.
- onErrorReturn,
- onErrorResume,
- onErrorMap,
- and Handling Errors at a Global Level.
Similar to bodyToMono, however here it is used to to retrieve a collection resource of type Flux from endpoint /stocks.
Flux<Stock> stockFluxObj = client.get() .uri("/stocks") .retrieve() .bodyToFlux(Stock.class); stockFluxObj.subscribe(System.out::println);
Troubleshooting a Reactive application is difficult compared to the regular applications.
There is an extra learning curve when implementing reactive applications.
There is limited support for reactive data stores since traditional relational data stores have yet to embrace the reactive paradigm.
| WebClient | WebTestClient |
| Web client acts as a reactive client who performs non-blocking HTTP requests. | Webtestclient also acts as a reactive client that can be used in tests.. |
| It can handle reactive streams with backpressure. | It can bind directly to WebFlux application by applying mock request and response objects. |
| It can take advantage of JAVA 8 Lambdas. | It can connect to any server over an HTTP connection. |
No. SpringMVC cannot be run on Netty.
There are 2 main components of Spring Webflux: RouterFunction and the HandlerFunction. The RouterFunction is responsible for mapping incoming requests to the appropriate HandlerFunction. The HandlerFunction is responsible for handling the request and returning a response.
The Flux API is a reactive programming library for Java that allows developers to easily build asynchronous applications. The library is based on the Reactive Streams specification, and provides a wide variety of operators that can be used to manipulate data streams.
A Publisher is a reactive component that emits a stream of data. The two main interfaces are Publisher and Subscriber.
A hot publisher is a publisher that emits data even if there is no Subscriber subscribed to it. A cold publisher is a publisher that only emits data when there is at least one Subscriber subscribed to it.
Throttling limits the amount of data that can be transferred between two systems in a given period of time. This is often done to prevent one system from overloading another system with too much data, or to prevent one user from consuming too much of a shared resource.
Backpressure is a mechanism where a Subscriber tells a Publisher how much data it can handle. In a Flux, if a source is producing 10,000 items/sec but the DB can only save 100/sec, backpressure (using strategies like buffer, drop, or latest) prevents the system from running out of memory.
Yes, a Flux can emit one item and complete. However, using Mono provides semantic clarity. It tells the consumer exactly what to expect (at most one value), which simplifies the API and allows the use of specific operators (like zip for single results) that are more intuitive for single-item processing.
Reactive streams are lazy. Both Mono and Flux are just blueprints of an execution plan. Data doesn't start moving, and computations (like DB calls or API requests) don't trigger until a .subscribe() call is made.
- >?
You use the .collectList() operator. This is common when you need to gather all items from a stream before sending them to a legacy API that doesn't support streaming.
- flatMap: Subscribes to inner publishers eagerly and flattens them. It does not preserve the original order of elements (they are interleaved/asynchronous).
- concatMap: Similar to flatMap but waits for each inner publisher to complete before starting the next one. It preserves order but is slower because it is sequential.
- switchMap: Every time a new element arrives from the source, it cancels the previous inner subscription and starts a new one. Ideal for search-as-you-type scenarios.
- onErrorReturn(value): Provides a default fallback value.
- onErrorResume(e -> ...): Switches to a fallback publisher (another Mono or Flux).
- retry(n): Re-subscribes to the source if an error occurs.
You use it when you have to wrap a blocking I/O call (like a legacy JDBC driver or File I/O) inside a reactive pipeline. It provides a thread pool that grows as needed but is capped to prevent resource exhaustion.
Example: Mono.fromCallable(() -> blockingCall()).subscribeOn(Schedulers.boundedElastic())
The key difference between Mono.just() and Mono.defer() lies in when the value or the Mono pipeline is generated.
Mono.just() creates a Mono eagerly at the time of code assembly, capturing the value immediately. The same value is emitted to all subsequent subscribers.
Mono.defer() creates a new Mono instance for each subscriber, with the value being generated at the moment of subscription.
| Feature | Mono.just() | Mono.defer() |
|---|---|---|
| Execution Time | Eager: Value is computed when Mono.just() is called (during pipeline assembly). |
Lazy: Value is computed only when a subscriber subscribes (at subscription time). |
| Value to Subscribers | All subscribers receive the exact same pre-computed value. | Each subscriber can receive a different, freshly computed value. |
| Input Type | Takes a direct value T (must be non-null). |
Takes a Supplier<Mono<T>> (a function that returns a Mono). |
| Use Case | Use for static, constant, or already-computed non-null values. | Use for dynamic values, values that need to be up-to-date, or when the value fetching has side effects or can fail. |
In the Mono.just() case, if a delay occurs between subscriptions, all subscribers still receive the original timestamp. With Mono.defer(), each subscription triggers the System.currentTimeMillis() call again, ensuring the most current timestamp is used.
// Using Mono.just() Mono<Long> justMono = Mono.just(System.currentTimeMillis()); // Time captured NOW, when 'justMono' is created. // Subscribe multiple times: all print the same time justMono.subscribe(time -> System.out.println("Just Time: " + time)); justMono.subscribe(time -> System.out.println("Just Time: " + time)); // Using Mono.defer() Mono<Long> deferMono = Mono.defer(() -> Mono.just(System.currentTimeMillis())); // The supplier (lambda) is executed only upon subscription. // Subscribe multiple times: each can print a different time deferMono.subscribe(time -> System.out.println("Defer Time: " + time)); // Small delay here deferMono.subscribe(time -> System.out.println("Defer Time: " + time));
In Project Reactor, the primary difference is that Mono.fromCallable creates a Mono that can return a value (or throw an exception), while Mono.fromRunnable creates a Mono that only signals completion without emitting any value (a Mono
| Feature | Mono.fromCallable | Mono.fromRunnable |
|---|---|---|
| Return Value | Emits at most one value (T). | Emits no value (Mono<Void>), only a completion signal. |
| Input Type | Takes a java.util.concurrent.Callable (has a call() method). |
Takes a java.lang.Runnable (has a run() method). |
| Exception Handling | Can throw checked exceptions, which are captured and propagated as onError. |
Cannot throw checked exceptions (only RuntimeExceptions are propagated). |
| Use Case | Wrapping blocking operations that return data (e.g., DB calls). | "Fire and forget" tasks like logging or status updates with no result needed. |
| Laziness | Lazy: Executed only upon subscription. | Lazy: Executed only upon subscription. |
In essence, fromCallable is for tasks that compute a result, and fromRunnable is for tasks that perform an action.
Project Reactor is a foundational library for building non-blocking, reactive applications in Java, providing types like Mono and Flux. WebFlux is a Spring web framework that uses Reactor for high-concurrency, asynchronous HTTP handling. Reactor is the reactive engine, while WebFlux is the framework implementing it for web services.
- Role: Project Reactor is a library that implements the Reactive Streams specification (similar to RxJava). Spring WebFlux is a web framework.
- Layer: Reactor is a low-level library for asynchronous data streams, whereas WebFlux is a high-level abstraction for building reactive APIs, often running on Netty.
- Dependency: WebFlux is built upon Project Reactor; it uses it as its core library.
- Use Case: Use Reactor for general-purpose reactive programming (e.g., data processing). Use WebFlux for reactive web servers or clients.
