Database Operations · Lesson 87 of 112

Database Connections and Connection Pooling

What you will learn

  • What a connection is and what it costs
  • Why opening a new connection for every request is wasteful
  • How a connection pool works: borrow, use, give back
  • What happens when every connection is busy
  • How to think about the size of a pool

1. What a connection is

A program does not talk to a database directly. It first opens a connection: a channel with a login, a session and a set of settings (lesson 1.6). Every query, every transaction and every COMMIT travels over one connection.

With a database server (lesson 1.5) a connection is not free:

  • the program and the server must meet and agree (network, login, settings);
  • the server keeps memory and a session for each open connection;
  • the server only allows a limited number of connections at the same time. The limit and its default are different in every product, so check your product's documentation.

SQLite is a library inside your program, so it has no server and no login, but the shape of the problem is the same, and we can measure it.

2. Opening every time is slow

A web page might run three queries. A shop with many visitors runs thousands of queries a minute. If each request opens a connection, runs one query and closes it, most of the time goes into opening and closing.

import sqlite3, time, os, tempfile

path = os.path.join(tempfile.mkdtemp(), "shop.db")
setup = sqlite3.connect(path)
setup.execute("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, price INTEGER)")
setup.executemany("INSERT INTO products (name, price) VALUES (?, ?)", [("Shirt", 500), ("Scarf", 300), ("Cap", 150)])
setup.commit()
setup.close()

N = 2000
t = time.perf_counter()
for _ in range(N):
    x = sqlite3.connect(path); x.execute("SELECT 1").fetchone(); x.close()
open_each = time.perf_counter() - t

shared = sqlite3.connect(path)
t = time.perf_counter()
for _ in range(N):
    shared.execute("SELECT 1").fetchone()
reuse = time.perf_counter() - t
print(f"open each time: {open_each*1000:.0f} ms, reuse one: {reuse*1000:.0f} ms for {N} queries")
open each time: 1226 ms, reuse one: 3 ms for 2000 queries

The numbers come from one run on one computer and will differ on yours. The size of the gap is the point: here, opening each time took hundreds of times longer. With a network and a login in between, as in a server database, the gap is usually larger, not smaller.

3. The idea of a pool

A connection pool opens a fixed number of connections once, keeps them open, and lends them out. A request borrows one, uses it, and gives it back instead of closing it.

 requests        pool (2 connections)        database
  A ──borrow──►  [ conn 1 ] ◄──────────────►
  B ──borrow──►  [ conn 2 ] ◄──────────────►
  C  waits...    (none free)

Here is a tiny pool. The standard library queue.Queue does the lending and waiting for us:

import queue

class Pool:
    def __init__(self, path, size):
        self.free = queue.Queue()
        self.opened = 0
        for _ in range(size):
            self.free.put(sqlite3.connect(path, check_same_thread=False))
            self.opened += 1

    def get(self, timeout=0.2):
        return self.free.get(timeout=timeout)   # waits; raises queue.Empty when none is free in time

    def give_back(self, con):
        self.free.put(con)

pool = Pool(path, size=2)
print("connections opened:", pool.opened)

con = pool.get()
print(con.execute("SELECT COUNT(*) FROM products").fetchone())
pool.give_back(con)
connections opened: 2
(3,)

(check_same_thread=False lets one connection be used by different threads, one at a time. Real pools take care of this for you.)

4. When the pool runs dry

Two connections mean two requests at a time. A third has to wait:

a = pool.get()
b = pool.get()
print("two borrowed, none left")
try:
    pool.get()
except queue.Empty:
    print("third request gave up after 0.2 s: pool exhausted")
pool.give_back(a)
c = pool.get()
print("after a give-back, a request succeeds again:", c is a)
two borrowed, none left
third request gave up after 0.2 s: pool exhausted
after a give-back, a request succeeds again: True

A real pool does the same: the third request waits for a free connection and gives up (an error) if none comes in time. That is a feature. It protects the database from being flooded: better to make some requests wait than to open thousands of connections and bring the server down.

The most common bug is a leak: code borrows a connection and never gives it back, for example because an error happened in between. Do the give-back in a try ... finally block (or a with block), so it happens even when something fails. After enough leaks the pool runs dry and the whole application seems frozen, although the database is fine.

Worked example: choosing a pool size

A small shop's website has one application server. The server handles at most 8 requests at the same time, and each request keeps a database connection for about 20 milliseconds.

Question Reasoning
How many connections can be in use at once? At most 8, one per request being handled
Is a pool of 100 useful? No: 92 connections would sit idle and cost the database memory
Is a pool of 2 enough? It would work, but 6 of the 8 requests would often wait
A reasonable start? Around 8, then watch how long requests wait and adjust

If the shop later runs four such servers, the database sees up to 4 × 8 = 32 connections, which must stay under its own limit. The numbers are made up. Real sizes come from measuring (lesson 12.3), not from a formula.

Settings travel with the connection

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). A connection carries its own settings (lesson 1.6), and a pooled connection keeps them when it is lent to the next request. In SQLite, foreign key checking is one such setting:

PRAGMA foreign_keys;
foreign_keys
------------
           1
(1 row)

A request switches it off for a "quick fix" and forgets to switch it back on:

PRAGMA foreign_keys = OFF;
PRAGMA foreign_keys;
foreign_keys
------------
           0
(1 row)
PRAGMA foreign_keys;
foreign_keys
------------
           1
(1 row)

A request switches it off for a "quick fix" and forgets to switch it back on:

PRAGMA foreign_keys = OFF;
PRAGMA foreign_keys;
foreign_keys
------------
           0
(1 row)
PRAGMA foreign_keys;
foreign_keys
------------
           1
(1 row)

A request switches it off for a "quick fix" and forgets to switch it back on:

PRAGMA foreign_keys = OFF;
PRAGMA foreign_keys;
foreign_keys
------------
           0
(1 row)

The next borrower of that connection now works without the safety net:

DELETE FROM customers WHERE customer_id = 1;
SELECT COUNT(*) AS orphan_orders FROM orders o LEFT JOIN customers c ON c.customer_id = o.customer_id WHERE c.customer_id IS NULL;
orphan_orders
-------------
            9
(1 row)
DELETE FROM customers WHERE customer_id = 1;
SELECT COUNT(*) AS orphan_accounts FROM accounts a LEFT JOIN customers c ON c.customer_id = a.customer_id WHERE c.customer_id IS NULL;
orphan_accounts
---------------
              1
(1 row)
DELETE FROM students WHERE student_id = 1;
SELECT COUNT(*) AS orphan_enrollments FROM enrollments e LEFT JOIN students s ON s.student_id = e.student_id WHERE s.student_id IS NULL;
orphan_enrollments
------------------
                 3
(1 row)

With enforcement on, that delete would have been refused (lesson 3.5). Now rows point at a parent that no longer exists. This is why a pool must hand out connections in a known state: reset settings, and end any open transaction, before giving one back. (Press Reset data to bring the deleted rows back.)

5. Pools in practice

  • Most database libraries and web frameworks include a pool, or have one you switch on. Use it instead of writing your own, as the one above is only for learning.
  • Some setups put a separate pooling program between the application and the database server. Which tools exist, and their settings, depend on the product; read your product's documentation.
  • A pool does not make slow queries fast. It only removes the cost of opening connections. Slow queries are the job of indexes and plans (chapter 7).
  • A connection can carry an open transaction (chapter 6). Always COMMIT or ROLLBACK before giving a connection back, or the next borrower inherits half-finished work.

Common mistakes

  • Opening a connection per query in a busy program.
  • Forgetting to give the connection back when an error happens (a leak). Use finally or with.
  • Making the pool huge "to be safe". Idle connections cost memory, and the database has a limit.
  • Ignoring the total across servers: ten application servers with a pool of 20 each can ask for 200 connections.
  • Giving back a connection with an open transaction.

Key takeaways

  • Every query travels over a connection; opening one costs time and server memory, and servers allow only a limited number.
  • A pool opens a fixed number of connections once and lends them out.
  • When no connection is free, a request waits or fails: this protects the database.
  • Always give connections back, even when errors happen.
  • Size the pool from the number of simultaneous requests, then adjust by measuring.

Practice

1. In your own words, what is a connection pool?

Show answer

A set of database connections opened in advance and reused: a request borrows one, uses it and gives it back instead of opening and closing a new one.

2. Why did the third pool.get() in the lesson fail?

Show answer

Both connections of the two-connection pool were borrowed, and none was given back within 0.2 seconds, so queue.Empty was raised.

3. What is a connection leak and how do you prevent it?

Show answer

Code that borrows a connection and never gives it back, for example after an error. Prevent it by giving back in a finally block or using a with block.

4. Four application servers each have a pool of 25 connections. The database allows 80 connections. Is there a risk?

Show answer

Yes: 4 × 25 = 100 connections could be requested, more than 80. Lower the pool sizes or raise the limit, after checking the database can cope.

5. Why must a connection have no open transaction when it is given back?

Show answer

The next request that borrows it would continue inside the old transaction, seeing half-finished changes or holding locks, and the work might be committed or rolled back by accident.

6. Does a bigger pool make slow queries faster? Explain.

Show answer

No. A pool only saves the cost of opening connections. A slow query stays slow; it needs an index or a better query (chapter 7).