Prev Next

Spring / Spring Webflux Interview questions

1. What is Reactive Programming? 2. What is Spring Webflux? 3. Is Spring WebClient thread safe? 4. Is Spring RestTemplate deprecated? 5. What are the benefits of using Spring Webflux? 6. What is bodyToMono? 7. Difference between Mono and Flux. 8. How to handle errors in Spring WebFlux? 9. Difference between Spring MVC @async and Spring Webflux? 10. What is Reactor netty? 11. What are router functions? 12. What does Mono.defer() do? 13. When should we choose Reactor over RxJava? 14. How to handle an exception in a Spring Webflux based application? 15. What is bodyToFlux? 16. Disadvantages of Using Reactive Streams. 17. Difference between the Web client and Web Test Client? 18. Can we use SpringMvc and webflux together? 19. What are the main components of Spring Webflux? 20. What is the Flux API? 21. What is a Publisher? Explain its main interfaces. 22. Explain the difference between hot publishers and cold publishers. 23. Explain throttling. 24. What is Backpressure and how does it relate to Flux? 25. Can you use a Flux to represent a single result? Why would you use Mono instead? 26. What does "Nothing happens until you subscribe" mean? 27. How do you convert a Flux into a Mono>? 28. What is the difference between flatMap, concatMap, and switchMap? 29. How do you handle errors in a Mono/Flux pipeline? 30. When should you use Schedulers.boundedElastic()? 31. Difference between Mono.just() and Mono.defer(). 32. Difference between Mono.fromCallable and Mono.fromRunnable. 33. Difference between Project Reactor and WebFlux.
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. What is Reactive Programming?

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.

2. What is Spring Webflux?

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.

3. Is Spring WebClient thread safe?

Yes, WebClient is thread-safe since it is immutable.

4. Is Spring RestTemplate deprecated?

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.

5. What are the benefits of using Spring Webflux?

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.

6. What is bodyToMono?

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.

7. Difference between Mono and Flux.

A Mono, which can either return zero or one result before completing,

And a Flux, which can return zero to many, possibly infinite, results before completing.

8. How to handle errors in Spring WebFlux?

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.
9. Difference between Spring MVC @async and Spring Webflux?

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.

10. What is Reactor netty?

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.

11. What are router functions?

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();
}

12. What does Mono.defer() do?

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.

13. When should we choose Reactor over RxJava?

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.

14. How to handle an exception in a Spring Webflux based application?

Different ways to handle exceptions.

  • onErrorReturn,
  • onErrorResume,
  • onErrorMap,
  • and Handling Errors at a Global Level.
15. What is bodyToFlux?

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);

16. Disadvantages of Using Reactive Streams.

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.

17. Difference between the Web client and Web Test Client?

WebClientWebTestClient
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.
18. Can we use SpringMvc and webflux together?

No. SpringMVC cannot be run on Netty.

19. What are the main components of Spring Webflux?

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.

20. What is the Flux API?

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.

21. What is a Publisher? Explain its main interfaces.

A Publisher is a reactive component that emits a stream of data. The two main interfaces are Publisher and Subscriber.

22. Explain the difference between hot publishers and cold publishers.

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.

23. Explain throttling.

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.

24. What is Backpressure and how does it relate to Flux?

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.

25. Can you use a Flux to represent a single result? Why would you use Mono instead?

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.

26. What does "Nothing happens until you subscribe" mean?

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.

27. How do you convert a Flux into a Mono>?

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.

28. What is the difference between flatMap, concatMap, and switchMap?

  • 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.

29. How do you handle errors in a Mono/Flux pipeline?
  • 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.

30. When should you use Schedulers.boundedElastic()?

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())

31. Difference between Mono.just() and Mono.defer().

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));
32. Difference between Mono.fromCallable and Mono.fromRunnable.

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.

33. Difference between Project Reactor and WebFlux.

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.
«
»
Apache Shiro Interview questions

Comments & Discussions