How does Rails handle database connection pooling?

Answer

Rails uses connection pooling to reuse database connections efficiently. A pool of connections is maintained per database per process. The pool size is configured in database.yml via the pool option (default: 5). When a thread needs a connection, it checks one out from the pool; when done, it checks it back in. Active Record connection adapter manages this via ActiveRecord::ConnectionAdapters::ConnectionPool. If all connections are in use and a new request arrives, it waits up to checkout_timeout seconds (default: 5). For Puma (multi-threaded), set pool size ≥ number of threads. Use with_connection in background threads to ensure proper checkout/checkin.