Help language development. Donate to The Perl Foundation

DBIish::Pool cpan:RBT last updated on 2020-07-03


DBIish::Pool - Database connection pooling for DBIish


my %connection-parameters = database => 'foo', user => 'bar', password => secret();
my $pool = => 'Pg', initial-size => 1, max-connections => 10, min-spare-connections => 1,
                     max-idle-duration =>, |%connection-parameters);

my $dbh = $pool.get-connection()

${SELECT 1});



This module is useful for apps supporting multiple parallel users which arrive at an inconsistent rate, such as a web application. In addition to connection reuse it allow configuring a maximum number of simultaneous connections to ensure the database does not go over capacity.

Database connection reuse improves performance significantly for very simple transactions, or long distance networks using SSL encrypted connections. 300% has been seen within the same network for web requests, where each request was establishing a new connection.

To use, create a pool, then take a connection from that pool. The connection is returned to the pool when dispose is called. Calling dispose is important as otherwise you may exhaust the pool due to garbage collection being unpredictable.

See your database driver for a description of the connection parameters allowed. These are the same as the C call.

my $pool = => 'Pg', max-connections => 20, max-idle-duration =>,
    min-spare-connections => 3,  initial-size => 5, |%dbiish-connection-parameters);

sub do-db-work() {
  my $dbh = $pool.get-connection();

  my $sth = $dbh.prepare(q{ SELECT session_state FROM sessions WHERE session_id = ? });

  my $ret = $sth.allrows();

  return $ret;



Returns a connection from the pool, establishing a new connection if necessary, when one becomes available. The connection is checked for connectivity prior to returning it to the client.

Once max-connections is reached, this routine will not return a connection until one becomes available. Ensure you call dispose after finished using the connection to shorten this timeframe as garbage collection is not predictable.

If preferred, you may obtain a connection asynchronously.

my $dbh = await $pool.get-connection(:async);

Pool Statistics

A small Hash with pool connection statistics is available. This can be useful for automated monitoring purposes.

my %stats = $pool.stats();

Statistics fields include: * inuse ➡ Number of connections currently in use. * idle ➡ Number available for immediate use. * starting ➡ Number starting up. * scrub ➡ Numbers recently disposed, currently being scrubbed. * total ➡ Total of the inuse, idle, starting, and scrub counters. Due to short race conditions, this may not add up at times. * waiting ➡ Number of unfilled connect calls.