Learning objectives
After reading this article you will be able to:
- Connect with psycopg and pass values as parameters instead of building SQL strings
- Size one pool per process with psycopg_pool or SQLAlchemy
- Configure TLS with the server's CA and a client certificate through libpq parameters
In Python, almost every PostgreSQL connection goes through libpq, PostgreSQL's official client library: psycopg uses libpq, and SQLAlchemy uses psycopg. That makes TLS simpler, because the parameters are the same ones psql and pg_dump use. What usually goes wrong is around it: queries built with f-strings, a new connection per request, a pool opened before the workers fork.
This guide uses psycopg (the 3 line, package psycopg, not psycopg2) and SQLAlchemy on top of it. If you are still picking a database, see the best database for Python.
What do you need before you start?#
- Python installed and a virtual environment for the project.
- A reachable PostgreSQL server, with a user, password and database.
- If the server requires TLS with its own CA, the CA file and, if it asks for a client certificate, the client certificate and key.
python -m venv .venv
source .venv/bin/activate # on Windows: .venv\Scripts\activate
pip install "psycopg[binary,pool]" sqlalchemy
pip freeze > requirements.txtThe binary extra bundles libpq in the package, with nothing to compile; the pool extra installs psycopg_pool.
The URL follows the format postgresql://user:password@host:5432/database and lives in an environment variable, never in the code. Reserved characters in the password need percent-encoding (urllib.parse.quote("p@ss", safe="") returns p%40ss). See why in what environment variables are.
export DATABASE_URL="postgresql://app:password@db.example.com:5432/app"How do you connect and query with psycopg?#
For a script, one connection inside a with block is enough. When the block ends, psycopg commits the open transaction (or rolls back, if there was an exception) and closes the connection.
# script.py
import os
import psycopg
TLS = {
"sslmode": "verify-full",
"sslrootcert": "certs/ca.pem", # server CA
"sslcert": "certs/client-cert.pem", # client certificate
"sslkey": "certs/client-key.pem", # client key
}
with psycopg.connect(os.environ["DATABASE_URL"], **TLS) as conn:
conn.execute(
"CREATE TABLE IF NOT EXISTS users ("
" id serial PRIMARY KEY, email text UNIQUE NOT NULL, name text)"
)
conn.execute(
"INSERT INTO users (email, name) VALUES (%s, %s)"
" ON CONFLICT (email) DO NOTHING",
("ana@example.com", "Ana"),
)
row = conn.execute(
"SELECT id, name FROM users WHERE email = %s", ("ana@example.com",)
).fetchone()
print(row)Keyword arguments to connect are merged into the connection string and override what came in the URL. If the server doesn't ask for a client certificate, drop sslcert and sslkey from the dictionary.
%s is a parameter placeholder, not string formatting: psycopg sends the value separately from the SQL, which is what stops SQL injection. Never use an f-string or Python's % to put values into the query. A single value still goes in a tuple: ("ana@example.com",), with the comma.
How do you use a connection pool with psycopg_pool?#
Opening a connection costs a network round trip plus the TLS handshake. In an API or a bot, open one pool per process and borrow connections from it:
# db.py
import atexit
import os
from psycopg_pool import ConnectionPool
TLS = {
"sslmode": "verify-full",
"sslrootcert": "certs/ca.pem",
"sslcert": "certs/client-cert.pem",
"sslkey": "certs/client-key.pem",
}
pool = ConnectionPool(
os.environ["DATABASE_URL"],
kwargs=TLS,
min_size=1,
max_size=5, # connection ceiling for THIS process
open=False, # open explicitly, after the workers fork
)
def open_pool():
pool.open()
pool.wait() # fail early if the database doesn't answer
atexit.register(pool.close)# users.py
from db import pool
def find_by_email(email: str):
with pool.connection() as conn:
return conn.execute(
"SELECT id, name FROM users WHERE email = %s", (email,)
).fetchone()pool.connection() returns the connection to the pool when the block ends, committing if everything worked and rolling back on an exception. Call open_pool() at process startup: in the framework's startup hook or, with Gunicorn, after each worker is born. A pool opened before the fork (with gunicorn --preload, for example) would share the same connections across processes. In FastAPI and other async code, the idea is the same with AsyncConnectionPool, opened and closed in the app's lifespan. Running those servers is covered in how to host FastAPI, Flask or Django.
The psycopg_pool docs recommend always passing open explicitly, because the default may change.
How big should the pool be?#
Each Gunicorn or Uvicorn worker is a process with its own pool. Four workers with max_size=5 can open 20 connections, and more apps on the same database add more. Keep the total under the server's limit, with headroom for migrations and a SQL client you open by hand. Go over it and you get the 'too many connections' error.
How do you set up TLS with a CA and a client certificate?#
libpq has six sslmode values. Only two protect you from an impostor server:
sslmode |
Encrypts | Checks the certificate | Checks the host name |
|---|---|---|---|
disable |
No | No | No |
allow, prefer |
Maybe | No | No |
require |
Yes | No | No |
verify-ca |
Yes | Yes, against the CA | No |
verify-full |
Yes | Yes, against the CA | Yes |
Use verify-full, which the PostgreSQL documentation recommends in most security-sensitive environments. verify-ca also verifies the chain, but accepts any server with a certificate signed by that CA. If a root CA file exists, require behaves like verify-ca, but the documentation discourages relying on that. Never fix a certificate error by dropping to require: the encryption stays, but you no longer know who you are talking to.
The other three parameters point to files:
sslrootcert: the CA that signs the server certificate.sslcert: the certificate the client presents, when the server asks for one.sslkey: the private key for that certificate.
On Linux and macOS, libpq rejects a key other users can read: run chmod 600 certs/client-key.pem. libpq also reads the PGSSLMODE, PGSSLROOTCERT, PGSSLCERT and PGSSLKEY variables, so you can set up TLS without touching the code, and psql and pg_dump pick up the same ones. Keep the certs/ folder out of Git, like any secret.
How do you connect with SQLAlchemy?#
SQLAlchemy picks the driver from the URL prefix, and the default driver for postgresql:// depends on the SQLAlchemy version. Make psycopg explicit with postgresql+psycopg://, swapping the prefix of the URL that came from the variable:
# engine.py
import os
from sqlalchemy import create_engine, text
from sqlalchemy.engine import make_url
url = make_url(os.environ["DATABASE_URL"]).set(drivername="postgresql+psycopg")
engine = create_engine(
url,
pool_size=5,
max_overflow=0, # never goes past pool_size
pool_pre_ping=True, # drops connections that died
connect_args={
"sslmode": "verify-full",
"sslrootcert": "certs/ca.pem",
"sslcert": "certs/client-cert.pem",
"sslkey": "certs/client-key.pem",
},
)
with engine.connect() as conn:
row = conn.execute(
text("SELECT id, name FROM users WHERE email = :email"),
{"email": "ana@example.com"},
).first()
print(row)
with engine.begin() as conn: # transaction that commits at the end
conn.execute(
text("UPDATE users SET name = :name WHERE email = :email"),
{"name": "Ana Smith", "email": "ana@example.com"},
)connect_args goes straight to psycopg.connect, with the same libpq parameters. The :email markers are parameters, not text. With the ORM, Session(engine) uses this same engine and pool.
An engine's connection total is pool_size + max_overflow. With the defaults (5 and 10), each process can reach 15. Setting max_overflow to zero keeps the math predictable. Create the engine once per process. If your code uses multiprocessing or os.fork(), the SQLAlchemy docs recommend calling engine.dispose(close=False) in the child process, so it opens its own pool without touching the parent's connections.
To close everything on shutdown, call engine.dispose() (or pool.close(), with psycopg_pool).
Which errors show up most often?#
connection to server at "db.example.com" (203.0.113.7), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
FATAL: password authentication failed for user "app"
SSL error: certificate verify failed: self-signed certificate in certificate chain
private key file "certs/client-key.pem" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root
FATAL: no pg_hba.conf entry for host "203.0.113.7", user "app", database "app", no encryption
FATAL: sorry, too many clients already| Message | Likely cause | Fix |
|---|---|---|
Connection refused |
Wrong host or port, server down or port blocked | Check the URL and the network |
password authentication failed |
Wrong user or password, or a password without percent-encoding | Encode the password in the URL |
certificate verify failed |
sslrootcert doesn't point to the CA that signed the server |
Use the right CA, never require |
has group or world access |
Other users can read the client key | chmod 600 on the key |
no pg_hba.conf entry ... no encryption |
The server requires TLS and the client connected without it | Set sslmode=verify-full |
too many clients already |
The sum of the pools went over the limit | Lower max_size or pool_size |
For the first line, the full checklist is in ECONNREFUSED on the database. For the certificate error, see the self-signed certificate error when connecting to a database.
How to do this on Square Cloud#
PostgreSQL hosting on Square Cloud starts on the Standard plan, from R$44.99 per month. You create the database in the dashboard (name and memory, from 1024 MB), and it is ready in seconds in the same datacenter as your applications, with an average latency of about 1 ms. PostgreSQL ships with the pgvector and pg_cron extensions.
- Copy the full connection URL, shown once at creation (resetting the password shows it again), into the application's
DATABASE_URLvariable, in the dashboard, the API, the CLI or VS Code. The URL isn't added to your variables on its own, and the change applies on the next restart. - Download the certificate in the dashboard. TLS is mandatory: the client trusts the downloaded CA and, on PostgreSQL, also presents the
.pem.sslrootcertpoints to the CA, andsslcertandsslkeyto the.pem. Don't swap this forsslmode=require. - Put the files in the application, in the ZIP or through the dashboard's file manager. At start, the platform runs
pip install -r requirements.txt, and the disk persists across restarts and deploys. If libpq rejects the key with thehas group or world accesserror, the start command runs as a shell command and can fix the permission before the server starts, for example:chmod 600 certs/client-key.pem && gunicorn -w 2 -b "0.0.0.0:$PORT" app:app. - Size the pools: each database accepts up to 256 connections, with no pooler in front, so workers times
max_size(orpool_size + max_overflow), summed across every application that uses the database, have to fit under that ceiling.
The database also accepts connections from outside, so the same URL and certificates work in psql on your machine. Limits and plans on PostgreSQL hosting.
Database hosting
MongoDB, PostgreSQL, MySQL and Redis next to your app
FAQs
Should I use psycopg2 or psycopg?
For a new project, psycopg (the 3 line), the successor to psycopg2 with async support and its own pool in psycopg_pool. psycopg2 still works, but in SQLAlchemy each has its own URL prefix: postgresql+psycopg2 and postgresql+psycopg.
Why not build the query with an f-string?
Because the value becomes part of the SQL, and malicious text becomes a command: that is SQL injection. With %s and a tuple of values, psycopg sends the data separately from the query.
What is the difference between sslmode=require and verify-full?
require encrypts but doesn't prove the server is who it claims to be. verify-ca checks the certificate against the CA, and verify-full also checks the host name, the mode the PostgreSQL documentation recommends for security-sensitive environments.
How many connections does SQLAlchemy open by default?
The default pool keeps up to 5 connections (pool_size) and opens up to 10 extra at peak (max_overflow), so up to 15 per engine. Multiply by the number of processes to get the total.
More in Databases
See all 32 articles- How much does database hosting cost?Cloud database hosting costs from zero to hundreds of dollars a month. See what sets the price: instance, disk, traffic, snapshots, and how to estimate yours.
- How to host a database for your appTo host a database, pick an engine, create the instance, store the connection string in an environment variable and test the connection. Step-by-step guide.
- What is Redis used for?Redis is an in-memory data store that keeps key-value pairs and rich data structures. Learn how it works, what it is used for and when not to use it.
- How to back up your databaseBack up MySQL, PostgreSQL and MongoDB with mysqldump, pg_dump and mongodump, then restore the dump. See the commands, how to verify and common mistakes.