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
- Spring WebFlux Basics
- Spring Security and JWT Authentication
- MySQL track or PostgreSQL for SQL basics
Add R2DBC Dependencies
MySQL example:
<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
spring:
r2dbc:
url: r2dbc:mysql://localhost:3306/demo
username: root
password: your_passwordPool settings:
spring:
r2dbc:
pool:
initial-size: 5
max-size: 20Entity and Repository
@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:
ReactiveCrudRepositoryreturnsMono/Flux- No
@Transactionalon reactive repo same as JPA—useTransactionalOperator
Transactions (Awareness)
R2DBC supports reactive transactions:
API evolves—check Spring Framework docs for your version.
R2DBC vs JDBC + JPA
| JDBC/JPA | R2DBC | |
|---|---|---|
| Blocking | Yes | No |
| Maturity | Full features | Subset; no lazy loading like JPA |
| MyBatis | Yes | No direct MyBatis |
| Team skill | Common | Steeper |
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
-
WebTestClientintegration 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.