Database connection pooling
suggest changeOpening a database connection is expensive. The client has to open a TCP socket, maybe negotiate TLS, authenticate (SCRAM password hashing is deliberately slow) and exchange session settings. PostgreSQL also starts a new server process for every connection. All of that happens before your first query runs.
A connection pool keeps a set of connections open and lends them out. A request borrows a connection, runs its queries and gives it back, and the next request reuses it. A pool also puts a cap on how many connections your app opens, which protects the database when traffic spikes.
The Relational databases article introduces the postgres, mysql_client and sqlite3 packages. This article looks at pooling in detail, mostly with the built-in Pool from package:postgres, and then shows how to write a small pool for anything that doesn't have one.
Setup
dependencies:
postgres: ^3.5.0
pool: ^1.5.0 # only needed for the generic pool at the end
The examples were run against a local PostgreSQL server with a database named app.
What a pool saves you
This program runs 200 trivial queries twice. The first loop opens and closes a connection for every query. The second uses a pool, which opens one connection and reuses it:
import 'package:postgres/postgres.dart';
final endpoint = Endpoint(
host: 'localhost',
database: 'app',
username: 'postgres',
password: 'secret',
);
const settings = ConnectionSettings(sslMode: SslMode.disable);
Future<void> main() async {
const n = 200;
// 1. A new connection for every query.
var sw = Stopwatch()..start();
for (var i = 0; i < n; i++) {
final conn = await Connection.open(endpoint, settings: settings);
await conn.execute('SELECT 1');
await conn.close();
}
print('connect per query: ${sw.elapsedMilliseconds} ms');
// 2. One pooled connection, reused for every query.
final pool = Pool.withEndpoints(
[endpoint],
settings: PoolSettings(sslMode: SslMode.disable),
);
sw = Stopwatch()..start();
for (var i = 0; i < n; i++) {
await pool.execute('SELECT 1');
}
print('pooled: ${sw.elapsedMilliseconds} ms');
await pool.close();
}
Output (times vary by machine):
connect per query: 6246 ms
pooled: 205 ms
That is about 30 ms per connection against 1 ms per query, and this is a server on the same machine with TLS turned off. Against a remote server with TLS the gap is bigger.
Creating a pool
Pool implements the same Session interface as Connection, so execute, prepare, run and runTx work the same way. Each call borrows a connection, uses it and gives it back.
You can create a pool from a list of endpoints:
final pool = Pool.withEndpoints(
[
Endpoint(host: 'db1.internal', database: 'app', username: 'app', password: pw),
],
settings: PoolSettings(
maxConnectionCount: 10,
sslMode: SslMode.require,
),
);
If you pass several endpoints, for example read replicas, the pool picks them in round-robin order. Pool.withSelector lets you choose the endpoint yourself for each request (by tenant or by read/write role, for example).
You can also build a pool from a connection URL, which is handy when the configuration comes from a DATABASE_URL environment variable. Pool settings go in the query string:
final pool = Pool.withUrl(
'postgresql://app:secret@localhost:5432/app'
'?sslmode=require&max_connection_count=10&application_name=orders-api'
'&connect_timeout=5&query_timeout=30',
);
The URL accepts max_connection_count, max_connection_age, max_session_use and max_query_count, plus the usual connection parameters. Durations are given in seconds. An unknown parameter throws an ArgumentError, so typos show up at startup.
PoolSettings
| Setting | Default | Meaning |
|---|---|---|
maxConnectionCount |
1 | Maximum number of open connections. This is also the maximum number of concurrent queries |
connectTimeout |
15 s | Maximum time to wait for a free connection, including the time to open a new one |
queryTimeout |
5 min | Default timeout for each query |
maxConnectionAge |
12 h | A connection older than this is closed instead of being reused |
maxSessionUse |
4 h | Total time a connection may spend lent out before it is replaced |
maxQueryCount |
100000 | Number of queries a connection may run before it is replaced |
applicationName |
none | Shown in pg_stat_activity on the server |
onOpen |
none | Callback run once on every new physical connection |
PoolSettings also accepts the other ConnectionSettings fields, such as sslMode, securityContext, timeZone and queryMode.
The default pool size is 1
The most common mistake with package:postgres is to create a pool without maxConnectionCount. With the default of 1, every query waits in line for the single connection, and the pool can't run anything in parallel. Here five requests arrive at the same time and each takes about 200 ms on the server:
import 'package:postgres/postgres.dart';
final endpoint = Endpoint(
host: 'localhost',
database: 'app',
username: 'postgres',
password: 'secret',
);
Future<void> runConcurrently(Pool pool, String label) async {
final sw = Stopwatch()..start();
// 5 requests at the same time, each taking ~200 ms on the server.
final results = await Future.wait([
for (var i = 0; i < 5; i++)
pool.execute('SELECT pg_backend_pid(), pg_sleep(0.2)'),
]);
final pids = results.map((r) => r.first[0]).toSet();
print('${label.padRight(22)}: ${sw.elapsedMilliseconds} ms, '
'distinct connections: ${pids.length}');
}
Future<void> main() async {
final defaultPool = Pool.withEndpoints(
[endpoint],
settings: PoolSettings(sslMode: SslMode.disable),
);
await runConcurrently(defaultPool, 'default settings');
await defaultPool.close();
final pool = Pool.withEndpoints(
[endpoint],
settings: PoolSettings(
sslMode: SslMode.disable,
maxConnectionCount: 5,
),
);
await runConcurrently(pool, 'maxConnectionCount: 5');
await runConcurrently(pool, 'second round');
await pool.close();
}
Output:
default settings : 1183 ms, distinct connections: 1
maxConnectionCount: 5 : 370 ms, distinct connections: 5
second round : 205 ms, distinct connections: 5
pg_backend_pid() returns the ID of the server process, which identifies the physical connection. With one connection the queries run one after another (5 × 200 ms). With five they run in parallel. The first round also pays for opening the connections, since the pool opens them lazily. In the second round all five are already open.
Waiting for a connection: connectTimeout
When all connections are busy, new requests wait. connectTimeout limits the total wait: the time spent waiting for a free slot plus the time to open a connection. When it runs out, the call throws TimeoutException:
import 'dart:async';
import 'package:postgres/postgres.dart';
final endpoint = Endpoint(
host: 'localhost',
database: 'app',
username: 'postgres',
password: 'secret',
);
Future<void> main() async {
final pool = Pool.withEndpoints(
[endpoint],
settings: PoolSettings(
sslMode: SslMode.disable,
maxConnectionCount: 1,
connectTimeout: Duration(milliseconds: 500),
),
);
// Occupy the only connection for 2 seconds.
final slow = pool.execute('SELECT pg_sleep(2)');
final sw = Stopwatch()..start();
try {
await pool.execute('SELECT 1');
} on TimeoutException catch (e) {
print('after ${sw.elapsedMilliseconds} ms: ${e.message}');
}
await slow;
print('slow query done, pool usable again: '
'${(await pool.execute('SELECT 1')).first[0]}');
await pool.close();
}
Output:
after 506 ms: Failed to acquire pool lock.
slow query done, pool usable again: 1
In a web server, catch this exception and return 503 Service Unavailable instead of letting requests pile up without limit. If you see these timeouts often, either the pool is too small or something holds connections for too long (slow queries, long transactions, or HTTP calls made inside a transaction).
Borrowing one connection for several statements
Each pool.execute call can run on a different connection. That's fine for independent queries, but some work needs the same connection from start to finish:
pool.runTx((tx) async { ... })borrows a connection, runs the callback in a transaction, commits or rolls back, and returns the connection.pool.run((session) async { ... })borrows a connection for several statements without a transaction.pool.withConnection((conn) async { ... })gives you theConnectionitself, for example to callprepareseveral times.
Never keep a reference to the session or connection after the callback returns. By then another request may be using it.
Session state leaks between borrowers
A pooled connection is reused as it is. Anything you change with SET stays on the connection and affects whoever borrows it next. The same goes for temporary tables and advisory locks. SET LOCAL inside a transaction is safe, because the change ends with the transaction:
import 'package:postgres/postgres.dart';
const showTimeout =
"SELECT pg_backend_pid(), current_setting('statement_timeout')";
Future<void> main() async {
final pool = Pool.withUrl(
'postgresql://postgres:secret@localhost:5432/app'
'?sslmode=disable&max_connection_count=2&application_name=orders-api',
);
// SET LOCAL lasts only until the transaction ends.
await pool.runTx((tx) async {
await tx.execute('SET LOCAL statement_timeout = 5000');
final r = await tx.execute(showTimeout);
print('in runTx (SET LOCAL): pid=${r.first[0]} timeout=${r.first[1]}');
});
var r = await pool.execute(showTimeout);
print('next borrower: pid=${r.first[0]} timeout=${r.first[1]}');
// A plain SET sticks to the physical connection.
await pool.run((session) async {
await session.execute('SET statement_timeout = 1234');
final r = await session.execute(showTimeout);
print('in run (SET): pid=${r.first[0]} timeout=${r.first[1]}');
});
r = await pool.execute(showTimeout);
print('next borrower: pid=${r.first[0]} timeout=${r.first[1]}');
final apps = await pool.execute(
"SELECT count(*) FROM pg_stat_activity WHERE application_name = 'orders-api'");
print('connections named orders-api: ${apps.first[0]}');
await pool.close();
}
Output (pids vary):
in runTx (SET LOCAL): pid=34088 timeout=5s
next borrower: pid=34088 timeout=0
in run (SET): pid=34088 timeout=1234ms
next borrower: pid=34088 timeout=1234ms
connections named orders-api: 1
Some rules follow from this:
- For a setting that only one piece of work needs, use
SET LOCALinsiderunTx. - For a setting that every connection should have, use the
onOpencallback (shown in the server example below). It runs once for each new physical connection. - If you have to use a plain
SET,RESETit in afinallyblock before the callback returns.
The query also shows that application_name makes the pool's connections easy to find on the server.
Errors and broken connections
The pool decides after each borrow whether to keep the connection:
- A normal server error, such as a constraint violation, leaves the connection healthy, so the pool keeps it.
- An exception thrown in a
runTxcallback rolls the transaction back, and the connection goes back to the pool. - A connection that was closed, or that hit an error which breaks the connection (a network failure, or the server terminating the backend), is thrown away. A new one is opened the next time it's needed.
import 'package:postgres/postgres.dart';
final endpoint = Endpoint(
host: 'localhost',
database: 'app',
username: 'postgres',
password: 'secret',
);
Future<int> pid(Pool pool) async =>
(await pool.execute('SELECT pg_backend_pid()')).first[0] as int;
Future<void> main() async {
final pool = Pool.withEndpoints(
[endpoint],
settings: PoolSettings(sslMode: SslMode.disable, maxConnectionCount: 1),
);
await pool.execute('DROP TABLE IF EXISTS accounts');
await pool.execute('CREATE TABLE accounts (id int PRIMARY KEY, balance int)');
await pool.execute('INSERT INTO accounts VALUES (1, 100)');
final before = await pid(pool);
// 1. A server error such as a unique violation.
try {
await pool.execute('INSERT INTO accounts VALUES (1, 50)');
} on ServerException catch (e) {
print('server error ${e.code}: ${e.message}');
}
print('same connection after server error: ${await pid(pool) == before}');
// 2. An exception thrown inside runTx rolls back and releases the connection.
try {
await pool.runTx((tx) async {
await tx.execute('UPDATE accounts SET balance = balance - 30 WHERE id = 1');
throw StateError('payment provider is down');
});
} on StateError catch (e) {
print('runTx failed: ${e.message}');
}
final balance = await pool.execute('SELECT balance FROM accounts WHERE id = 1');
print('balance after rollback: ${balance.first[0]}');
// 3. The server kills the connection (restart, failover, idle timeout...).
final victim = await pid(pool);
final admin = await Connection.open(endpoint,
settings: ConnectionSettings(sslMode: SslMode.disable));
await admin.execute(r'SELECT pg_terminate_backend($1)', parameters: [victim]);
await admin.close();
final after = await pid(pool);
print('killed pid $victim, next query ran on a new connection: ${after != victim}');
await pool.execute('DROP TABLE accounts');
await pool.close();
}
Output (pids vary):
server error 23505: duplicate key value violates unique constraint "accounts_pkey"
same connection after server error: true
runTx failed: payment provider is down
balance after rollback: 100
killed pid 33256, next query ran on a new connection: true
Even with maxConnectionCount: 1, the pool recovered from the killed connection on its own. There is one case it can't handle: a connection that dies while idle, where the client hasn't noticed yet. The next query on that connection fails. The pool then throws the connection away, so retrying once is usually enough. Only retry statements that are safe to repeat, such as reads or transactions that will run again in full.
Recycling connections
Connections don't live forever. Firewalls and load balancers drop connections that have been idle too long, server processes slowly use more memory, and after a failover or DNS change you want new connections to go to the new server. maxConnectionAge, maxSessionUse and maxQueryCount make the pool close old connections and open new ones. This example sets maxQueryCount very low so you can see it happen:
import 'package:postgres/postgres.dart';
Future<void> main() async {
final pool = Pool.withEndpoints(
[
Endpoint(
host: 'localhost',
database: 'app',
username: 'postgres',
password: 'secret',
),
],
settings: PoolSettings(
sslMode: SslMode.disable,
maxConnectionCount: 1,
maxQueryCount: 3, // tiny value to make the effect visible
),
);
final pids = <int>[];
for (var i = 0; i < 7; i++) {
final r = await pool.execute('SELECT pg_backend_pid()');
pids.add(r.first[0] as int);
}
// Number the connections 1, 2, 3... in the order they appeared.
final order = <int, int>{};
print(pids.map((p) => order.putIfAbsent(p, () => order.length + 1)).toList());
await pool.close();
}
Output:
[1, 1, 1, 2, 2, 2, 3]
In production, set maxConnectionAge to a value well below any idle timeout between you and the database (cloud load balancers often drop connections after 5 to 60 minutes). 30 minutes is a reasonable starting point.
A pool in a web server
Create one pool when the app starts, share it among all request handlers, and close it on shutdown. The pool is safe to use from concurrent async code in the same isolate:
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:postgres/postgres.dart';
late final Pool pool;
Future<void> main() async {
final env = Platform.environment;
pool = Pool.withEndpoints(
[
Endpoint(
host: env['DB_HOST'] ?? 'localhost',
port: int.parse(env['DB_PORT'] ?? '5432'),
database: env['DB_NAME'] ?? 'app',
username: env['DB_USER'] ?? 'postgres',
password: env['DB_PASSWORD'],
),
],
settings: PoolSettings(
sslMode: SslMode.disable,
maxConnectionCount: 10,
connectTimeout: Duration(seconds: 5),
queryTimeout: Duration(seconds: 10),
maxConnectionAge: Duration(minutes: 30),
applicationName: 'orders-api',
// Runs once for every new physical connection.
onOpen: (conn) async {
await conn.execute("SET idle_in_transaction_session_timeout = '30s'");
},
),
);
// Fail fast at startup if the database is unreachable.
await pool.execute('SELECT 1');
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8080);
print('listening on http://localhost:${server.port}');
late final StreamSubscription<ProcessSignal> sigint;
sigint = ProcessSignal.sigint.watch().listen((_) async {
print('shutting down...');
await sigint.cancel();
await server.close(); // stop accepting new requests
await pool.close(); // waits for queries in progress, then closes connections
print('bye');
});
await for (final req in server) {
unawaited(handle(req));
}
}
Future<void> handle(HttpRequest req) async {
try {
final r = await pool.execute(
"SELECT pg_backend_pid() AS pid, "
"current_setting('idle_in_transaction_session_timeout') AS idle_timeout",
);
final row = r.first.toColumnMap();
req.response.headers.contentType = ContentType.json;
req.response.write(jsonEncode(row));
} on TimeoutException {
req.response.statusCode = HttpStatus.serviceUnavailable;
req.response.write('database busy, try again');
} catch (e) {
req.response.statusCode = HttpStatus.internalServerError;
req.response.write('internal error');
stderr.writeln('request failed: $e');
} finally {
await req.response.close();
}
}
$ curl localhost:8080
{"pid":20692,"idle_timeout":"30s"}
$ curl localhost:8080
{"pid":20692,"idle_timeout":"30s"}
Both requests ran on the same physical connection, and the onOpen setting is in effect. pool.close() stops new borrows, waits for connections that are in use to come back and then closes everything. Pass force: true to close connections immediately, even in the middle of a query.
Pools and isolates
A Pool can't be shared between isolates, because each isolate has its own memory. If you run your server in several isolates (see Isolates) or several processes, each one creates its own pool, and the database sees the sum of all of them:
total connections = processes × isolates per process × maxConnectionCount
How big should the pool be?
Bigger is not better. The database does real work for each active connection, and past a certain point extra connections only add contention. Things to keep in mind:
- Start small. A common starting point for the whole system is roughly
2 × CPU coresof the database server active connections, divided among all app instances. Then measure. - Stay under the server limit. PostgreSQL's
max_connectionsdefaults to 100, and some of those are reserved for superusers. Leave room for migrations, admin tools and deploys, when old and new instances run side by side. - Long transactions shrink the pool. A connection is busy for the whole
runTxcallback, not only while queries run. Never await HTTP calls or other slow work while you hold a connection. - Many app instances? Put PgBouncer (in transaction pooling mode) between the apps and the database, so thousands of client connections share a few dozen server connections.
To see what the pool is doing, query pg_stat_activity on the server:
SELECT state, count(*)
FROM pg_stat_activity
WHERE application_name = 'orders-api'
GROUP BY state;
Many idle rows mean the pool is bigger than it needs to be. Rows in the idle in transaction state mean code is holding a transaction open while it does something else.
MySQL
package:mysql_client has its own MySQLConnectionPool. It has a few limitations to be aware of, such as leaking a connection when a withConnection callback throws. See the MySQL article for details and a workaround.
A generic pool with package:pool
Some drivers and clients come without a pool. package:pool gives you a counting semaphore (Pool(n)), and with it you can write a small, correct resource pool. The semaphore limits how many resources are in use at once, and a list holds the idle ones so they can be reused:
import 'dart:async';
import 'package:pool/pool.dart' as pkg;
/// A minimal pool for any resource that is expensive to create.
class ResourcePool<T> {
final Future<T> Function() _create;
final Future<void> Function(T) _destroy;
final Future<bool> Function(T)? _isHealthy;
final pkg.Pool _permits;
final _idle = <T>[];
int _created = 0;
ResourcePool({
required int maxSize,
required Future<T> Function() create,
required Future<void> Function(T) destroy,
Future<bool> Function(T)? isHealthy,
Duration? acquireTimeout,
}) : _create = create,
_destroy = destroy,
_isHealthy = isHealthy,
_permits = pkg.Pool(maxSize, timeout: acquireTimeout);
int get created => _created;
/// Borrows a resource, runs [fn] and always gives the resource back.
Future<R> use<R>(Future<R> Function(T resource) fn) {
return _permits.withResource(() async {
final resource = await _take();
var broken = false;
try {
return await fn(resource);
} catch (_) {
broken = true; // don't trust a resource that saw an error
rethrow;
} finally {
if (broken || _permits.isClosed) {
await _destroy(resource);
} else {
_idle.add(resource);
}
}
});
}
Future<T> _take() async {
while (_idle.isNotEmpty) {
final r = _idle.removeLast();
if (_isHealthy == null || await _isHealthy(r)) return r;
await _destroy(r);
}
_created++;
return _create();
}
Future<void> close() async {
await _permits.close(); // waits until all borrowed resources are returned
for (final r in _idle) {
await _destroy(r);
}
_idle.clear();
}
}
// A stand-in for a real connection.
class FakeConnection {
static var _next = 0;
final int id = ++_next;
Future<String> query(String sql) async {
await Future.delayed(Duration(milliseconds: 50));
return 'conn $id: $sql';
}
}
Future<void> main() async {
final pool = ResourcePool<FakeConnection>(
maxSize: 3,
create: () async {
await Future.delayed(Duration(milliseconds: 100)); // slow handshake
return FakeConnection();
},
destroy: (c) async => print('closing conn ${c.id}'),
acquireTimeout: Duration(seconds: 2),
);
final results = await Future.wait([
for (var i = 1; i <= 6; i++) pool.use((c) => c.query('job $i')),
]);
results.forEach(print);
print('connections created: ${pool.created}');
try {
await pool.use((c) async => throw StateError('protocol error'));
} on StateError catch (e) {
print('failed: ${e.message}');
}
print(await pool.use((c) => c.query('after error')));
await pool.close();
}
Output:
conn 1: job 1
conn 2: job 2
conn 3: job 3
conn 1: job 4
conn 2: job 5
conn 3: job 6
connections created: 3
closing conn 3
failed: protocol error
conn 2: after error
closing conn 1
closing conn 2
Six jobs shared three connections. The connection that saw an error was closed instead of being returned. Because the borrow and the return both happen inside use, a caller can't forget to give a connection back, which is the most common bug in hand-written pools. When acquireTimeout runs out, package:pool throws a TimeoutException, just like the PostgreSQL pool. The same pkg.Pool(n).withResource(...) call also works on its own to limit concurrency, for example to keep the number of parallel queries below a driver's pool size.
Best practices
- Create one pool per database at startup and share it. Never create a pool (or a connection) per request.
- Always set
maxConnectionCountwithpackage:postgres; the default of 1 runs every query one after another. - Set
connectTimeoutto a few seconds and return HTTP 503 when it runs out, instead of letting requests queue forever. - Hold connections briefly. Use
pool.executefor single statements. KeeprunTxandruncallbacks short and free of network calls to other services. - Don't leave session state behind. Use
SET LOCALin transactions, oronOpenfor settings every connection should have. - Recycle connections with
maxConnectionAgeso that they survive firewalls, failovers and server restarts. - Set
applicationNameso you can find your pool's connections inpg_stat_activity. - Close the pool on shutdown with
await pool.close(), after the HTTP server has stopped accepting requests. - Count every process and isolate when you compare your total connection count with the server's
max_connections.