Search code examples
project-reactorspring-data-r2dbcr2dbc

Reactive R2DBC for simple RESTful calls


Since R2DBC is reactive and non blocking I would like to understand the benefit of using R2DBC in a simple RESTful CRUD service

Assume a spring boot application is exposing a RESTful service using a repository below

public interface CustomerRepository extends ReactiveCrudRepository<Customer, Long> {

    @Query("SELECT * FROM customer WHERE last_name = :lastname")
    Flux<Customer> findByLastName(String lastName);

}

This repository is called from a service and the results needs to be transformed in the service before returning to controller.

Flux<Customer> customers = repository.findAll();

In order to access the complete list of customers , I need to invoke blockLast() on the Flux which makes it blocking and defeats the purpose of using reactive components

Does that mean that there is no benefit of using R2DBC in this simple example ? Am I missing something ?

Can flux be used only for asynchronous subscription where the processing of Flux collections happens in a different thread ?


Solution

    1. Since the method retuns a Flux, it returns a promise that can complete sometime in future.
    2. The thread calling this method should not block - that's the whole point of reactive. If you use .blockLast(), you will make the calling thread block. As Michael said in this answer, this should only be done when you are integrating reactive and non-reactive code together.
    3. Here is a diagram that explains how async. computations are work (reactive, CompletableFuture, etc.). Hopefully this clears your doubts;

    enter image description here

    As you can see in the diagram, if you do .blockLast(), you lose out on true non-blocking. Ideally, the calling thread should get free immediately so that it can do other work.

    1. A properly written reactive application will be a single chain with the subscription happening at the upper-most layer. The entire application should be an async pipeline. You should use applications like BlockHound to check if your threads are blocking anywhere.

    "Can flux be used only for asynchronous subscription where the processing of Flux collections happens in a different thread ?" - Flux is nothing but a promise that says it can finish some time in future. As the diagram shows, callbacks will execute on the thread that the async. computation finished on. You can switch this thread using .publishOn().