Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Spring › Data access and transactions

Connection pool and OSIV

Why connections run short even though the queries finish quickly

Why it exists — Every time a DB connection is made, it has to go through a TCP connection and a login procedure, and there is also a limit on the number of connections the DB can accept at once. A connection pool opens a set number of connections in advance and lets requests take turns using them, which saves connection setup time and keeps the number of connections to the DB from exceeding that number even when requests pile up.

Where it's used today — In Spring Boot, the pool size is set with HikariCP's maximum-pool-size, and it is adjusted so that the pool size multiplied by the number of servers does not exceed the DB limit. If there is a long external API call unrelated to the DB, OSIV is turned off with spring.jpa.open-in-view=false and the external call is moved outside the transaction, so that the connection is not held during that time.

A request does its database work, then calls an external API, and then responds. Database connections are borrowed from a pool and returned to it. Depending on when a connection is returned (the Open Session in View setting, OSIV for short), the number of requests that a pool of the same size can withstand differs greatly.

Partly checked against real execution · All 216 combinations were run with Spring Boot 4.1.1, Hibernate 7.4.5, HikariCP 7.0.2, and MySQL 8.4.11. The numbers of successes and timeouts all match, and 211 combinations match down to every request (a request on the 5-second limit can differ from run to run)

Concepts in this lab

Connection pool
A technique that creates several database connections in advance and reuses them. Opening a new connection is an expensive operation, so instead of opening and closing a connection for every request, the application borrows one and returns it. If every connection is in use, a new request waits until one is returned, and an exception is thrown if it cannot get one within a set time (connectionTimeout in HikariCP, 30 seconds by default). The default implementation in Spring Boot is HikariCP.
Open Session in View
Why it exists — If you read a lazily fetched field in a controller or a view template after the transaction has ended, a LazyInitializationException occurs. OSIV keeps the persistence context open until the request ends, so you can read associated entities even while rendering the page.
Where it's used today — A small service that renders pages on the server is sometimes used with it left on. An API server with many requests turns it off with spring.jpa.open-in-view=false and returns the needed associated data by copying it into a DTO inside the transaction.
A setting that keeps the persistence context open after the transaction ends, until request processing finishes (the response is written). It is convenient because lazy fetching also works in controllers and views. However, after the first database access during a request, the request keeps holding the database connection until the response is finished, so a service with many requests can run short of connections. It is on by default in Spring Boot.
Persistence context
The logical space in JPA that holds and manages entities. Entities that you load or save are kept here, and JPA tracks the changes made to them and applies those changes to the database when the transaction ends. It usually shares its lifecycle with one transaction (in a web request with Open Session in View (OSIV) turned on, it lasts until the request ends). Features such as the first-level cache, dirty checking, and transactional write-behind work on top of it.
Bottleneck
The slowest part of a system, which limits the processing performance of the whole. No matter how much you improve the other parts, overall performance does not improve while this part stays the same. Performance improvement starts with finding it by measurement.

Try these

Running with the default settings

  1. 0.0s: Request 1 borrows connection 1 and starts its database work.
  2. 0.1s: Request 2 borrows connection 2 and starts its database work.
  3. 0.2s: Request 3 borrows connection 3 and starts its database work.
  4. 0.3s: Request 4 arrives. All connections in the pool (3) are in use, so it waits.
  5. 0.4s: Request 5 arrives. All connections in the pool (3) are in use, so it waits.
  6. 0.5s: Request 1 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 1 and holds it until the response is finished.
  7. 0.5s: Request 6 arrives. All connections in the pool (3) are in use, so it waits.
  8. 0.6s: Request 2 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 2 and holds it until the response is finished.
  9. 0.6s: Request 7 arrives. All connections in the pool (3) are in use, so it waits.
  10. 0.7s: Request 3 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 3 and holds it until the response is finished.
  11. 0.7s: Request 8 arrives. All connections in the pool (3) are in use, so it waits.
  12. 2.5s: Request 1 finishes its response. It now returns connection 1.
  13. 2.5s: Request 4 borrows connection 1 and starts its database work. It waited 2.2s.
  14. 2.6s: Request 2 finishes its response. It now returns connection 2.
  15. 2.6s: Request 5 borrows connection 2 and starts its database work. It waited 2.2s.
  16. 2.7s: Request 3 finishes its response. It now returns connection 3.
  17. 2.7s: Request 6 borrows connection 3 and starts its database work. It waited 2.2s.
  18. 3.0s: Request 4 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 1 and holds it until the response is finished.
  19. 3.1s: Request 5 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 2 and holds it until the response is finished.
  20. 3.2s: Request 6 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 3 and holds it until the response is finished.
  21. 5.0s: Request 4 finishes its response. It now returns connection 1.
  22. 5.0s: Request 7 borrows connection 1 and starts its database work. It waited 4.4s.
  23. 5.1s: Request 5 finishes its response. It now returns connection 2.
  24. 5.1s: Request 8 borrows connection 2 and starts its database work. It waited 4.4s.
  25. 5.2s: Request 6 finishes its response. It now returns connection 3.
  26. 5.5s: Request 7 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 1 and holds it until the response is finished.
  27. 5.6s: Request 8 finishes its database work and starts the external API call. OSIV is on, so it does not return connection 2 and holds it until the response is finished.
  28. 7.5s: Request 7 finishes its response. It now returns connection 1.
  29. 7.6s: Request 8 finishes its response. It now returns connection 2.

Result of this run

Code

# application.yml
spring.datasource.hikari.maximum-pool-size: 3
spring.datasource.hikari.connection-timeout: 5000   # fail after waiting 5s
spring.jpa.open-in-view: true

// controller method (class declaration, imports, and the declarations of the example types and fields omitted)
OrderDto get(long id) {
    Order order = orderService.find(id);       // @Transactional, database work 0.5s
    Delivery d = deliveryApi.track(order);     // external API 2s (no database use)
    return OrderDto.of(order, d);
}

Assumptions of this model

Requests are assumed to arrive at 0.1-second intervals, and there are assumed to be enough server threads to handle them (200 by default in Tomcat). The limit on waiting for a connection is fixed at 5 seconds (the HikariCP default is 30 seconds). All 216 combinations (pool size 1, 3, and 10, 1, 8, and 20 requests, three database work times, four external call times, and OSIV on and off) were actually run and checked. Pool sizes and request counts in between were not run. A Spring Boot 4.1.1 application (Hibernate 7.4.5, HikariCP 7.0.2, embedded Tomcat) was started with the application.yml and the controller method on the screen and connected to MySQL 8.4.11, requests were sent at 0.1-second intervals, and the values that HikariCP reports (the time spent waiting for a connection, the time the connection was held, and timeouts) were recorded for each request. The numbers of successes and timeouts matched the screen in all 216 combinations. The combinations where the result and the times of every single request also matched the screen (the wait time and the time until the response within 0.15 seconds) number 211. In the other five, a request whose wait time is within 0.1 seconds of the 5-second limit succeeded or failed the opposite way from the screen (two combinations), a request that arrived later got a connection first (one combination), or processing was late by tens to hundreds of milliseconds (two combinations). The screen calculates on the assumption that the request that arrived first gets a connection first, but the real pool did not strictly keep that order. It was confirmed by execution that with OSIV on the connection is returned when the response ends and with OSIV off it is returned when the transaction ends, and that with OSIV off a LazyInitializationException is thrown when the controller accesses a lazily loaded association. The times on the screen are calculated from the settings (the arrival interval, the database work time, the external call time, and the 5-second limit). In the check, the database work was a select sleep inside the transaction and the external call was a RestClient call to another HTTP server that responds after a set time, and both were made to end at the set time. Even so, the connection was held on average 2.4ms longer than on the screen. As a result, a request whose wait time lands exactly on the 5-second limit did not get a connection in 26 of 27 cases in the real runs, and the screen also calculates it as a failure. A request whose wait time falls 0.1 seconds short of the limit got a connection in most cases (the shortest time left before the limit was 64ms). The success or failure of a request on such a boundary is decided by a difference of tens of milliseconds, so it can differ from run to run. The connection numbers in the diagram and the step text are labels added to tell the connections apart. That a larger pool makes connections compete on the database side and slows it down was not confirmed by execution and follows the widely known explanation (max_connections, the limit on connections that the MySQL used for the check accepts, was 151). The client, the application, and the database ran in Linux containers on one PC (Java 21).

Previous lab: JdbcTemplate and exception translation · Next lab: Servlets

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these