David
David

Reputation: 816

Is it "okay" to build a Spring Reactive API with some Blocking Operations

I'm just kind of getting started with Spring and I want to build a RESTful API for a project I'm working on. My backend has a lot of HTTP calls to third-party services, I've decided that it would be prudent to implement a Reactive design and have the architecture be non-blocking. I'm using Retrofit and it has a callback-based async API which will work fine for me. Here's the problem; I've already implemented my database and models using Hibernate and JPA, it's really mature and can handle everything from migrations to validations and everything in between, I like using JPA, but it's blocking and so doesn't fit neatly in my architecture design. Is it okay to have the reactive stack everywhere else and perhaps migrate the persistence stuff to a reactive model later when the tooling and frameworks are almost at par with JPA? The main issue is creating the database schema at start-up, if there's a solution to that, I'd be glad to work with it.

Upvotes: 0

Views: 3794

Answers (1)

Toerktumlare
Toerktumlare

Reputation: 14712

blocking in any fully reactive webflux application is bad from a performance perspective.

Webflux starts with a very few number of threads, which means that if you block there is a high risk that your application will (under load) be susceptible to thread starvation, this because no new threads spawn in reactive applications, and your applications small thread pool will be blocked waiting for responses from your database.

There is a workaround which is that you place all potential blocking calls instead on its own scheduler, using the subscribeOn operator. This is documented in the reactor documentation

Just remember by wrapping blocking calls, you will not get the benefits from reactive programming, like a smaller memory footprint, and potentially higher throughput. But at least you will not suffer from thread starvation.

Those calls will instead behave like "regular calls" to a "regular spring boot web server" since those calls will get assigned a single thread that will follow the call throughout execution.

Upvotes: 4

Related Questions