R2DBC and Reactive Security

Introduction

Blocking JDBC on Netty event loops hurts WebFlux scalability. R2DBC (Reactive Relational Database Connectivity) offers non-blocking database access for MySQL, PostgreSQL, and others. Spring Security WebFlux secures reactive endpoints with ServerHttpSecurity. This chapter connects R2DBC to WebFlux and outlines a reactive JWT filter pattern.

Prerequisites

Add R2DBC Dependencies

MySQL example:

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<dependency>
    <groupId>io.asyncer:r2dbc-mysql</groupId>
    <artifactId>r2dbc-mysql</artifactId>
</dependency>

PostgreSQL: io.r2dbc:r2dbc-postgresql instead.

Configure R2DBC

yaml
spring:
  r2dbc:
    url: r2dbc:mysql://localhost:3306/demo
    username: root
    password: your_password

Pool settings:

yaml
spring:
  r2dbc:
    pool:
      initial-size: 5
      max-size: 20

Entity and Repository

java
@Table("users")
public record User(@Id Long id, String email, String displayName) {}
 
public interface UserRepository extends ReactiveCrudRepository<User, Long> {
    Mono<User> findByEmail(String email);
}

Controller:

Code explanation:

  • ReactiveCrudRepository returns Mono / Flux
  • No @Transactional on reactive repo same as JPA—use TransactionalOperator

Transactions (Awareness)

R2DBC supports reactive transactions:

API evolves—check Spring Framework docs for your version.

R2DBC vs JDBC + JPA

JDBC/JPAR2DBC
BlockingYesNo
MaturityFull featuresSubset; no lazy loading like JPA
MyBatisYesNo direct MyBatis
Team skillCommonSteeper

Hybrid architecture: WebFlux gateway + blocking microservice behind is valid.

Spring Security WebFlux

JWT filter implements WebFilter:

Reactive chain uses contextWrite for security context—not SecurityContextHolder thread local.

End-to-End Reactive Stack Checklist

  • WebFlux + R2DBC + reactive security
  • No blocking JDBC on Netty threads
  • WebTestClient integration tests
  • Actuator health includes R2DBC indicator

FAQ

JPA with WebFlux?

Not supported same stack—pick R2DBC or blocking MVC + JPA.

R2DBC migration tools?

Flyway/Liquibase often run at startup blocking—acceptable in init phase.

MySQL R2DBC driver name?

r2dbc-mysql (asyncer) common on Boot 3—verify BOM version.

Reactive security 401?

WebFilter order—JWT filter before AuthorizationWebFilter.

Performance win guaranteed?

Measure—small apps may see no gain vs tuned MVC.

Learn more?

Official Spring Security WebFlux and Spring Data R2DBC reference docs.