[Kotlin/Spring] Transaction Management

Transaction management

Declarative transaction management

Programmatic transaction management

Coroutines and declarative transaction management

Transaction management in reactive programming environments

When applying declarative transaction management to functions that perform transactional work, the behavior differs depending on the type of function and the database library as follows. Assume coroutine extension libraries are used without reactive types.

  • Declarative transaction management + regular function + blocking JDBC library
    • Advantage: Declarative transaction management works.
    • Disadvantage: Blocking IO operations block the thread. You cannot make blocking IO operations non-blocking while keeping the transaction in the function. You can create a new coroutine, but the thread executing the function and the thread executing the coroutine are not the same thread, so the transaction is not propagated.
  • Declarative transaction management + regular function + non-blocking R2DBC library
    • Advantage: Declarative transaction management works.
    • Disadvantage: To execute IO using the R2DBC library from a regular function, you must block the thread. Running a coroutine inside a regular function requires creating a new coroutine.
  • Declarative transaction management + suspend function + blocking JDBC library
    • Advantage: By using coroutines to handle blocking IO within the function, IO operations can be made not to block the current thread. No new coroutine creation is required to run coroutines inside the function.
    • Disadvantage: Declarative transaction management does not work. With programmatic transaction management, you cannot handle blocking IO using coroutines.
  • Declarative transaction management + suspend function + non-blocking R2DBC library
    • Advantage: Declarative transaction management works. IO does not block the current thread. No new coroutine creation is required to run coroutines inside the function.


In conclusion, when using blocking JDBC libraries, transaction management requires blocking threads. If transaction management is not necessary, you can use coroutines to run blocking calls on separate threads to avoid blocking threads.

Managing transactions with blocking JDBC libraries requires storing transaction information in the current thread; if the thread changes during transactional work, the transaction information is not preserved.

References

  • <>

Comments