Video in progress

Why do we need a connection pool, and what happens if we open a new connection on every request?

Opening a new database connection is expensive: TCP, authentication, and in PostgreSQL a separate backend process per connection. A pool keeps ready connections and hands them out again and again, so a request gets a connection in microseconds instead of milliseconds, and the database doesn't choke on the number of connections.

📖 Answer

PostgreSQL starts a separate OS process for every connection. If you open a new connection on every HTTP request, under load you end up with 2000 processes, max_connections runs out, and new users get the too many clients already error.

In Spring Boot the default pool is HikariCP:

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    hikari:
      maximum-pool-size: 10
      connection-timeout: 3000   # ms, how long to wait for a free connection
      max-lifetime: 1800000      # 30 minutes

Nothing changes in your code: when you call connection.close(), the connection isn't actually closed, it goes back to the pool.

A question interviewers often ask: "if we make the pool 200, will it be faster?" Usually not. The database works in parallel according to the number of CPUs and disks, and too many connections only add queueing and context switching. A small pool (10-20) works better than a big one in most cases. If the pool runs out often, look first for a slow query or a long transaction.