Quick revision
The short answer
Without JPA relationships we load an Order and its OrderLines ourselves, either with two queries combined with Mono.zip or with one join query whose rows we group in code. We save the aggregate in one transaction with TransactionalOperator or @Transactional, inserting the order first so its generated id exists before the lines are inserted. We keep the aggregate small because there is no cascade or orphan removal, model it the way Spring Data JDBC does with an aggregate root, and size r2dbc-pool for the expected concurrency.
What to remember
In this answer, we saw how to work with an Order and its OrderLines in Spring Data R2DBC, which has no relationship mapping. We loaded the aggregate with two queries combined by Mono.zip, or with one ordered join query grouped by bufferUntilChanged, and avoided N+1 queries for lists with an IN query. We saved it in one transaction, header first so its id exists, then the lines with concatMap. We replaced cascade and orphan removal with a delete-and-reinsert rule in the style of Spring Data JDBC, kept aggregates small, and sized the r2dbc-pool with Little's law.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Without JPA relationships we load an Order and its OrderLines ourselves, either with two queries combined with Mono.zip or with one join query whose rows we group in code. We save the aggregate in one transaction with TransactionalOperator or @Transactional, inserting the order first so its generated id exists before the lines are inserted. We keep the aggregate small because there is no cascade or orphan removal, model it the way Spring Data JDBC does with an aggregate root, and size r2dbc-pool for the expected concurrency.
Why this question is asked
Every business system has objects that belong together: an order and its lines, an invoice and its items, a playlist and its tracks. With JPA we would write @OneToMany and let Hibernate load and save the children. Spring Data R2DBC has no relationship mapping, so this everyday task becomes a design decision. Interviewers ask it to see whether a candidate can turn domain modelling into explicit, correct reactive code, and whether they understand transactions and connection use in that model. In this answer, we will recap what an aggregate is, load one in two ways, save it in one transaction, handle updates and deletes without cascade, and finish with the connection pool.
1A Quick Recap: Aggregates and What We Lose Without JPA
An aggregate is a cluster of objects that we treat as one unit for changes. The order is the aggregate root, the object the outside world refers to, and the lines belong to it: nobody saves a line on its own, and when the order is deleted, its lines go with it. Domain-driven design uses this idea to decide where transaction boundaries go.
In JPA, @OneToMany(cascade = ALL, orphanRemoval = true) implements most of this for us. Spring Data R2DBC maps one table to one class and stops there. So we model two tables, orders and order_lines with an order_id foreign key, map each to a record, and write the aggregate's loading and saving logic in a small repository class of our own.
2Loading Option 1: Two Queries Combined
The clearest way to load one order is two queries, one for the header and one for the lines, combined with Mono.zip.
Notice how each step reads: collectList gathers the lines into one List, and zip waits for both results. If the order does not exist, the header Mono is empty and zip completes empty, so the caller can use switchIfEmpty to return a 404.
But there is a catch when loading many orders. Calling findById for each of 100 orders runs 200 queries, the classic N+1 problem. For a list, we load the headers, collect their ids, load all lines with one query using WHERE order_id IN (:ids), and group the lines by order id in memory. That is 2 queries for any number of orders.
3Loading Option 2: One Join Query, Grouped in Code
The second option is one query that joins both tables and returns one row per line, then groups the rows back into orders.
| o.id | line_id | sku | Group |
|---|---|---|---|
| 7 | 70 | PEN | order 7 |
| 7 | 71 | INK | order 7 |
| 8 | 80 | PAD | order 8 starts: id changed |
| 9 | null | null | order 9 with no lines |
bufferUntilChanged closes a group when o.id changes, so rows must be ordered by o.id.The ORDER BY o.id is essential: bufferUntilChanged starts a new group each time the order id changes, so it only works when rows of the same order are adjacent. The LEFT JOIN keeps orders that have no lines, which is why a line can be null. This option makes one round trip and streams orders as they are assembled, but it repeats the header columns on every line row. Two queries are simpler to read and maintain; the join wins when round trips are expensive or the result is streamed.
4Saving the Aggregate in One Transaction
Saving has an ordering constraint: the lines need the order's id, and the database only generates it during the insert of the header. So we insert the header first, then insert the lines with that id, all in one transaction.
The as(tx::transactional) call applies a TransactionalOperator to the whole chain, so the header and all lines commit together, or roll back together if any insert fails. @Transactional on the method works the same way. We use concatMap rather than flatMap because a transaction runs on one connection, which executes one statement at a time; concatMap sends them in order instead of piling them up. For many lines, a single multi-row INSERT through DatabaseClient saves round trips.
5Updates and Deletes Without Cascade or Orphan Removal
Without dirty checking or orphan removal, we decide how changes to lines are written. The simplest correct approach, and the one Spring Data JDBC itself uses, is to treat the aggregate as a whole: update the header, delete all its lines, and insert the current lines again, in one transaction. It costs a few extra statements but cannot leave orphaned or stale lines behind. If lines are many or have their own identity referenced elsewhere, we compare old and new lines and issue only the needed inserts, updates and deletes, at the cost of more code.
Deleting an order means deleting its lines first, or declaring ON DELETE CASCADE on the foreign key so the database does it. Both are fine; the important thing is that it is written down somewhere, because no framework will do it for us. This is also why we keep aggregates small. An order with a few dozen lines is cheap to rewrite. An aggregate that pulls in customers, products and shipments turns every save into a large transaction and is a sign the model needs splitting, with references between aggregates kept as plain ids.
6Sizing the Connection Pool
Each transaction holds one connection from r2dbc-pool for its whole duration, and each repository call outside a transaction borrows one briefly. Spring Boot creates the pool when r2dbc-pool is on the classpath, and its size is set with spring.r2dbc.pool.initial-size and spring.r2dbc.pool.max-size (the default maximum is small, 10 in recent versions; check your version). Little's law sizes it: at 300 saves per second, each holding a connection for 20 ms, we need about 6 connections on average, so a maximum of 15 to 20 gives headroom. Set max-acquire-time so a request fails quickly when the pool is exhausted rather than waiting forever, and remember that the database's own connection limit is shared by every instance of the service.
7Follow-up questions
Why not just use Spring Data JDBC instead?
Spring Data JDBC models aggregates in exactly this way and does it for us: one aggregate root with its owned entities, saved by deleting and reinserting children. But it is blocking. In a reactive service we copy its modelling style by hand with R2DBC. If the service does not need to be reactive, Spring Data JDBC on virtual threads is often the simpler choice.
Can the two loading queries run in parallel?
Outside a transaction, yes: Mono.zip subscribes to both, and each borrows its own connection from the pool, so they overlap. Inside a transaction, both share one connection, and the driver runs them one after the other. Parallelism also means two connections per request, which matters for pool sizing.
How do we prevent two users overwriting each other's changes to the same order?
Add a version column to the root and annotate it with @Version. Spring Data R2DBC then adds the version to the WHERE clause of the update and fails with an OptimisticLockingFailureException if another transaction changed the order first. Because the root is updated on every change to its lines, the root's version protects the whole aggregate.
8Conclusion
In this answer, we saw how to work with an Order and its OrderLines in Spring Data R2DBC, which has no relationship mapping. We loaded the aggregate with two queries combined by Mono.zip, or with one ordered join query grouped by bufferUntilChanged, and avoided N+1 queries for lists with an IN query. We saved it in one transaction, header first so its id exists, then the lines with concatMap. We replaced cascade and orphan removal with a delete-and-reinsert rule in the style of Spring Data JDBC, kept aggregates small, and sized the r2dbc-pool with Little's law.
Open with
Since Spring Data R2DBC has no relationships, I model the order header and the order lines as two plain mapped records and write a small aggregate repository myself.
Then, if they want more
To load one order I run two queries, findById for the header and findByOrderId collected into a list, and combine them with Mono.zip; for a list of orders I avoid N+1 by loading all lines with one IN query and grouping them by order id.
Alternatively I can run one LEFT JOIN ordered by order id and group the rows with bufferUntilChanged, which is one round trip but repeats header columns.
To save, I insert the header first so the database generates its id, then insert the lines with that id using concatMap, and wrap the whole chain in TransactionalOperator or @Transactional so it commits or rolls back as one unit.
There is no cascade or orphan removal, so for updates I follow the Spring Data JDBC style: update the root, delete its lines and reinsert the current ones, in the same transaction, and I add a version column on the root for optimistic locking. That only works well if aggregates stay small, so other aggregates are referenced by id.
Finally, I use r2dbc-pool and size it with Little's law from the request rate and transaction time, with a max acquire time so exhaustion fails fast.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring WebFlux, Project Reactor reference guide
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You are designing a reactive service with R2DBC that needs an Order with its OrderLines....": https://scrivio-interview-library.netlify.app/spring-boot/webflux/74917d3897/